问:
git history changes after a checkout
I have a history that I'm happy with:

```<code>$ git log --oneline -n60
b1bbe6a JIRA-1569 later fixes
b021112 JIRA-1569 later fixes
0734203 JIRA-1569 adding new statuses
b38c4a2 Merge branch 'feature/MultipleStars' of feature/MultipleStars
0e2bcbd Merge remote-tracking branch 'remotes/origin/feature/AutoStars' into feature/MultipleStars
d8d6be9 JIRA-1520 Removed the datasource reference from web.xml to fix java naming lookup issue
d8085e0 JIRA-1569 fix filter
9641af1 JIRA-1569 displaying MR info
ecb3b3c JIRA-1569 commit
002820d JIRA-1569 include statuses and dates in the response
7b912c8 JIRA-1569 translate SP to ibatis
9de1c77 JIRA-3107 : Put a condition for userid (only for IVR reqeust) to avoid concurrent login session check.
e78716c JIRA-3181 - Mass Reformat and removal of Imports
2907ffc JIRA-3057 Auto accept WS Changes.                <<<<<---HERE!!!!!
212379a JIRA-3057 Auto Accept changes.
2f79bbc JIRA-76 MP Payment Acceptance with fixed Acceptance type
842c02f JIRA-59 Multiple Payee dashboard changes
3552c15 JIRA-3056 Auto Accept Changes in request response
f03d150 Merge pull request #25 in JIRA/My from release/digitalStarts to feature/RealTimeStars
4c9a7d6 JIRA-2274 Added blah, blah in the correct position and rererred the right package name.
288eb2b JIRA-2274 - Update RTP Payments in Transaction Staging
9dfdf7c JIRA-2272, JIRA-51 - Initial commit - Fetch CP RTP value and RTP Routing number Validation
a16ce9a JIRA-2378 - Settings file to build web service
</code>```

But, I do a checkout (which I marked as HERE above):

```<code>$get checkout 2907ffc
</code>```

And now I get a different history:

```<code>$ git log --oneline
2907ffc JIRA-3057 Auto accept WS Changes.
212379a JIRA-3057 Auto Accept changes.
3552c15 JIRA-3056 Auto Accept Changes in request response
f03d150 Merge pull request #25 in CQP3/consumer-portal-webservice from release/digitalClearXChangePhase2 to feature/RealTimePayments
4c9a7d6 JIRA-2274 Added blah, blah in the correct position and rererred the right package name.
288eb2b JIRA-2274 - Update RTP Payments in Transaction Staging
</code>```

These 2 commits have disappeared from the history: .

```<code>2f79bbc JIRA-76 MP Payment Acceptance with fixed Acceptance type
842c02f JIRA-59 Multiple Payee dashboard changes
</code>```

I thought I understood git fairly well, but this has me very confused.

答:
If a commit has multiple ancestors, you'll see all of them interleaved in the log, ordered by their timestamps.  So I'm guessing you have a situation like this:

```<code>A --> B --> C ---> D
        \
         -----> E ----> F
</code>```

You were originally at A, so your log showed you A, B, C, E, D, F.  You then checked out (say) C, so now all you can see is C and D.

The easiest way to confirm this is to re-run git log with the --graph flag.

Title: git history changes after a checkout

Body:
I have a history that I'm happy with:

$ git log --oneline -n60
b1bbe6a JIRA-1569 later fixes
b021112 JIRA-1569 later fixes
0734203 JIRA-1569 adding new statuses
b38c4a2 Merge branch 'feature/MultipleStars' of feature/MultipleStars
0e2bcbd Merge remote-tracking branch 'remotes/origin/feature/AutoStars' into feature/MultipleStars
d8d6be9 JIRA-1520 Removed the datasource reference from web.xml to fix java naming lookup issue
d8085e0 JIRA-1569 fix filter
9641af1 JIRA-1569 displaying MR info
ecb3b3c JIRA-1569 commit
002820d JIRA-1569 include statuses and dates in the response
7b912c8 JIRA-1569 translate SP to ibatis
9de1c77 JIRA-3107 : Put a condition for userid (only for IVR reqeust) to avoid concurrent login session check.
e78716c JIRA-3181 - Mass Reformat and removal of Imports
2907ffc JIRA-3057 Auto accept WS Changes.                <<<<<---HERE!!!!!
212379a JIRA-3057 Auto Accept changes.
2f79bbc JIRA-76 MP Payment Acceptance with fixed Acceptance type
842c02f JIRA-59 Multiple Payee dashboard changes
3552c15 JIRA-3056 Auto Accept Changes in request response
f03d150 Merge pull request #25 in JIRA/My from release/digitalStarts to feature/RealTimeStars
4c9a7d6 JIRA-2274 Added blah, blah in the correct position and rererred the right package name.
288eb2b JIRA-2274 - Update RTP Payments in Transaction Staging
9dfdf7c JIRA-2272, JIRA-51 - Initial commit - Fetch CP RTP value and RTP Routing number Validation
a16ce9a JIRA-2378 - Settings file to build web service

But, I do a checkout (which I marked as HERE above):

$get checkout 2907ffc

And now I get a different history:

$ git log --oneline
2907ffc JIRA-3057 Auto accept WS Changes.
212379a JIRA-3057 Auto Accept changes.
3552c15 JIRA-3056 Auto Accept Changes in request response
f03d150 Merge pull request #25 in CQP3/consumer-portal-webservice from release/digitalClearXChangePhase2 to feature/RealTimePayments
4c9a7d6 JIRA-2274 Added blah, blah in the correct position and rererred the right package name.
288eb2b JIRA-2274 - Update RTP Payments in Transaction Staging

These 2 commits have disappeared from the history: .

2f79bbc JIRA-76 MP Payment Acceptance with fixed Acceptance type
842c02f JIRA-59 Multiple Payee dashboard changes

I thought I understood git fairly well, but this has me very confused.

Body:
If a commit has multiple ancestors, you'll see all of them interleaved in the log, ordered by their timestamps.  So I'm guessing you have a situation like this:

A --> B --> C ---> D
        \
         -----> E ----> F

You were originally at A, so your log showed you A, B, C, E, D, F.  You then checked out (say) C, so now all you can see is C and D.

The easiest way to confirm this is to re-run git log with the --graph flag.


来源: stackexchange

问:
ASP.Net MVC List of Checkboxes
I am passing a model to a view, which containt a List of items. A DefaultCategories has an id (int), a description (string), and a selected boolean property.

I need to list these items, with a checkbox, and check the ones where the selected property is true.

So, I was trying this:

```<code>    <h1>
        Assigned Categories</h1>
    <table>
        <%foreach (var cat in Model.DefaultCategories)
{%>
        <tr>
            <td>
                <%=cat.Category %>
            </td>
            <td>
                <%=Html.CheckBoxFor(...) %>
            </td>
        </tr>
        <%
}%>
    </table>
</code>```

I'm not sure how to handle the CheckBoxFor. I will also need to query these checkboxes when the Submit is clicked....

答:
This is to bind the checkbox to the Description. Instead of a forech, why don't you use a datagrid?</p>

```<code><% Html.Telerik().Grid<ModelName>(TempData[SomeList] as List<T>)
                            .Name("Grid")
                            .DataKeys(keys => { keys.Add(x => x.Id); })
                            .Columns(cols =>
                            {
                               cols.Template(o =>
                               {

                                  %>
                                   <%=Html.SecureCheckBoxFor(model => model.Description, Model.Description)
                                <%}).Title("Select");
                            })
                            .EnableCustomBinding(true)
                            .Render();
                    %>
</code>```

ContentLicense: CC BY-SA 2.5

Title: ASP.Net MVC List of Checkboxes

Body:
I am passing a model to a view, which containt a List of items. A DefaultCategories has an id (int), a description (string), and a selected boolean property.

I need to list these items, with a checkbox, and check the ones where the selected property is true.

So, I was trying this:

        Assigned Categories

        <%foreach (var cat in Model.DefaultCategories)
{%>

                <%=cat.Category %>

                <%=Html.CheckBoxFor(...) %>

        <%
}%>

I'm not sure how to handle the CheckBoxFor. I will also need to query these checkboxes when the Submit is clicked....

Body:
This is to bind the checkbox to the Description. Instead of a forech, why don't you use a datagrid?

<% Html.Telerik().Grid<ModelName>(TempData[SomeList] as List<T>)
                            .Name("Grid")
                            .DataKeys(keys => { keys.Add(x => x.Id); })
                            .Columns(cols =>
                            {
                               cols.Template(o =>
                               {

                                  %>
                                   <%=Html.SecureCheckBoxFor(model => model.Description, Model.Description)
                                <%}).Title("Select");
                            })
                            .EnableCustomBinding(true)
                            .Render();
                    %>


问:
How does Cloudfront communicate with ELB?
INTERNET -> Cloudfront -> ELB -> Instance

Does traffic from Cloudfront to ELB need to be encrypted? Does AWS forward traffic internally or is it a normal public request which would be vulnerable to man-in-the-middle attacks if not served via https?

答:
I used CloudFront --> API Gateway --> Authorizer Lambda --> Route 53 -->  --> HA Proxy --> Trust Verification of API Gateway --> Internal ELB --> EC2

here are more details  http://knowmg.blogspot.com/2017/11/why-do-i-need-haproxy-in-aws-stack.html

ContentLicense: CC BY-SA 3.0


问:
Reading 2 text files and sending the newer text to new txt file
is there a way in C# to read 2 seperate text files and which ever is the newer text place into a new text folder? and have possibly loop constantly to look into them?</p>

答:
You can use the GetLastWriteTime property of a file to determine which one is newer, and you can use File.Copy (or File.Move) to place it into a new folder:

```<code>static void CopyNewestFileToLocation(string fileOne, string fileTwo, string destination)
{
    // Argument validation
    if (fileOne == null) throw new ArgumentNullException(nameof(fileOne));
    if (fileTwo == null) throw new ArgumentNullException(nameof(fileTwo));
    if (destination == null) throw new ArgumentNullException(nameof(destination));

    if (!File.Exists(fileOne)) throw new FileNotFoundException(
        "File specified for fileOne parameter does not exist", fileOne);
    if (!File.Exists(fileTwo)) throw new FileNotFoundException(
        "File specified for fileTwo parameter does not exist", fileTwo);

    if (!Directory.Exists(destination))
    {
        try
        {
            Directory.CreateDirectory(destination);
        }
        catch (Exception e)
        {
            var msg = $"Unable to create specified directory: {destination}" +
                      $"\nException Details:\n{e}";

            throw new ArgumentException(msg);
        }
    }

    // Find newest file and copy it
    if (File.GetLastWriteTime(fileOne) > File.GetLastWriteTime(fileTwo))
    {
        File.Copy(fileOne, Path.Combine(destination, Path.GetFileName(fileOne)));
    }
    else // TODO: decide what to do if they're equal
    {
        File.Copy(fileTwo, Path.Combine(destination, Path.GetFileName(fileTwo)));
    }
}
</code>```

Example Usage

```<code>CopyNewestFileToLocation(@"f:\public\temp\temp.txt", @"f:\public\temp\temp2.txt",
    @"f:\public\temp\newLocation");
</code>```

Body:
You can use the GetLastWriteTime property of a file to determine which one is newer, and you can use File.Copy (or File.Move) to place it into a new folder:

static void CopyNewestFileToLocation(string fileOne, string fileTwo, string destination)
{
    // Argument validation
    if (fileOne == null) throw new ArgumentNullException(nameof(fileOne));
    if (fileTwo == null) throw new ArgumentNullException(nameof(fileTwo));
    if (destination == null) throw new ArgumentNullException(nameof(destination));

    if (!File.Exists(fileOne)) throw new FileNotFoundException(
        "File specified for fileOne parameter does not exist", fileOne);
    if (!File.Exists(fileTwo)) throw new FileNotFoundException(
        "File specified for fileTwo parameter does not exist", fileTwo);

    if (!Directory.Exists(destination))
    {
        try
        {
            Directory.CreateDirectory(destination);
        }
        catch (Exception e)
        {
            var msg = $"Unable to create specified directory: {destination}" +
                      $"\nException Details:\n{e}";

            throw new ArgumentException(msg);
        }
    }

    // Find newest file and copy it
    if (File.GetLastWriteTime(fileOne) > File.GetLastWriteTime(fileTwo))
    {
        File.Copy(fileOne, Path.Combine(destination, Path.GetFileName(fileOne)));
    }
    else // TODO: decide what to do if they're equal
    {
        File.Copy(fileTwo, Path.Combine(destination, Path.GetFileName(fileTwo)));
    }
}

Example Usage

CopyNewestFileToLocation(@"f:\public\temp\temp.txt", @"f:\public\temp\temp2.txt",
    @"f:\public\temp\newLocation");


问:
Visual studio code clang executable
I've installed visual studio code on my Ubuntu VM and am using c++.  I keep getting the following error covering the pages tab at the top which is really frustrating:

Please install clang or check configuration clang.executable

I have installed clang using apt-get install llvm.  I have installed the c++ support from the packages so I'm not trying to do anything complicated here.

I have googled till I'm now blue in the face, has anyone else come across this and now how to get around this.

答:
It seems clang is not installed properly on your ubuntu. Install clang by:

```<code>sudo apt-get install clang

clang -v //Now see installed version
</code>```

Now, error should be fixed.

Title: Visual studio code clang executable

Body:
It seems clang is not installed properly on your ubuntu. Install clang by:

sudo apt-get install clang

clang -v //Now see installed version

Now, error should be fixed.


问:
setting empty value inside select if is empty select AngularJS
can someone tell me how can I make empty value, that if nothing is in list of select, show "n/a"

```<code>demo
</code>```

https://codepen.io/Turqus/pen/wPrKrr?editors=1010

template

```<code>    <div ng-app="test" ng-controller="select">
  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
 </select>

 <select class="form-control" ng-model="selectedList">
   <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>
</div>
</code>```

答:
```<code><select class="form-control" ng-model="selectedList">
  <option disabled selected value
         ng-show="downloadedLists.length == 0">n/a</option>
  <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>
</code>```

Body:
can someone tell me how can I make empty value, that if nothing is in list of select, show "n/a"

demo

https://codepen.io/Turqus/pen/wPrKrr?editors=1010

template

  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
 </select>

 <select class="form-control" ng-model="selectedList">
   <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>


问:
How does one statisfy a class constraint in an instance of a class that requires a type constructor rather than a concrete type?
I'm currently in Chapter 8 of Learn you a Haskell, and I've reached the section on the Functor typeclass. In said section the author gives examples of how different types could be made instances of the class (e.g Maybe, a custom Tree type, etc.) Seeing this, I decided to (for fun and practice) try implementing an instance for the Data.Set type; in all of this ignoring Data.Set.map, of course.

The actual instance itself is pretty straight-forward, and I wrote it as:

```<code>instance Functor Set.Set where
  fmap f empty = Set.empty
  fmap f s = Set.fromList $ map f (Set.elems s)
</code>```

But, since I happen to use the function fromList this brings in a class constraint calling for the types used in the Set to be Ord, as is explained by a compiler error:

```<code>Error occurred
ERROR line 4 - Cannot justify constraints in instance member binding
*** Expression    : fmap
*** Type          : Functor Set => (a -> b) -> Set a -> Set b
*** Given context : Functor Set
*** Constraints   : Ord b
</code>```

See: Live Example

I tried putting a constraint on the instance, or adding a type signature to fmap, but neither succeeded (both were compiler errors as well.)

Given a situation like this, how can a constraint be fulfilled and satisfied? Is there any possible way?

Thanks in advance! :)

答:
You can do this using a CoYoneda Functor.</p>

```<code>{-# LANGUAGE GADTs #-}

data CYSet a where
    CYSet :: (Ord a) => Set.Set a -> (a -> b) -> CYSet b

liftCYSet :: (Ord a) => Set.Set a -> CYSet a
liftCYSet s = CYSet s id

lowerCYSet :: (Ord a) => CYSet a -> Set.Set a
lowerCYSet (CYSet s f) = Set.fromList $ map f $ Set.elems s

instance Functor CYSet where
  fmap f (CYSet s g) = CYSet s (f . g)

main = putStrLn . show
  $ lowerCYSet
  $ fmap (\x -> x `mod` 3)
  $ fmap abs
  $ fmap (\x -> x - 5)
  $ liftCYSet $ Set.fromList [1..10]
-- prints "fromList [0,1,2]"
</code>```

Body:
I'm currently in Chapter 8 of Learn you a Haskell, and I've reached the section on the Functor typeclass. In said section the author gives examples of how different types could be made instances of the class (e.g Maybe, a custom Tree type, etc.) Seeing this, I decided to (for fun and practice) try implementing an instance for the Data.Set type; in all of this ignoring Data.Set.map, of course.

The actual instance itself is pretty straight-forward, and I wrote it as:

instance Functor Set.Set where
  fmap f empty = Set.empty
  fmap f s = Set.fromList $ map f (Set.elems s)

But, since I happen to use the function fromList this brings in a class constraint calling for the types used in the Set to be Ord, as is explained by a compiler error:

Error occurred
ERROR line 4 - Cannot justify constraints in instance member binding
*** Expression    : fmap
*** Type          : Functor Set => (a -> b) -> Set a -> Set b
*** Given context : Functor Set
*** Constraints   : Ord b

See: Live Example

I tried putting a constraint on the instance, or adding a type signature to fmap, but neither succeeded (both were compiler errors as well.)

Given a situation like this, how can a constraint be fulfilled and satisfied? Is there any possible way?

Thanks in advance! :)

Body:
You can do this using a CoYoneda Functor.

{-# LANGUAGE GADTs #-}

data CYSet a where
    CYSet :: (Ord a) => Set.Set a -> (a -> b) -> CYSet b

liftCYSet :: (Ord a) => Set.Set a -> CYSet a
liftCYSet s = CYSet s id

lowerCYSet :: (Ord a) => CYSet a -> Set.Set a
lowerCYSet (CYSet s f) = Set.fromList $ map f $ Set.elems s

instance Functor CYSet where
  fmap f (CYSet s g) = CYSet s (f . g)

main = putStrLn . show
  $ lowerCYSet
  $ fmap (\x -> x `mod` 3)
  $ fmap abs
  $ fmap (\x -> x - 5)
  $ liftCYSet $ Set.fromList [1..10]
-- prints "fromList [0,1,2]"


问:
Error: No Provider for MediaCapture in Ionic2
I am trying to use the most simple form of the MediaCapture for Ionic 2. I created a brand new project and added it as mentioned here.

But when I try to use it:

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@ionic-native/media-capture';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(private mediaCapture: MediaCapture) {

  }

}
</code>```

This error comes in (at the end of it is my environment info):

```<code>Runtime Error
Uncaught (in promise): Error: No provider for MediaCapture! Error at g (http://127.0.0.1:8100/build/polyfills.js:3:7133) at injectionError (http://127.0.0.1:8100/build/main.js:1511:86) at noProviderError (http://127.0.0.1:8100/build/main.js:1549:12) at ReflectiveInjector_._throwOrNull (http://127.0.0.1:8100/build/main.js:3051:19) at ReflectiveInjector_._getByKeyDefault (http://127.0.0.1:8100/build/main.js:3090:25) at ReflectiveInjector_._getByKey (http://127.0.0.1:8100/build/main.js:3022:25) at ReflectiveInjector_.get (http://127.0.0.1:8100/build/main.js:2891:21) at AppModuleInjector.NgModuleInjector.get (http://127.0.0.1:8100/build/main.js:3856:52) at resolveDep (http://127.0.0.1:8100/build/main.js:11260:45) at createClass (http://127.0.0.1:8100/build/main.js:11117:35) at createDirectiveInstance (http://127.0.0.1:8100/build/main.js:10954:37) at createViewNodes (http://127.0.0.1:8100/build/main.js:12303:49) at createRootView (http://127.0.0.1:8100/build/main.js:12208:5) at callWithDebugContext (http://127.0.0.1:8100/build/main.js:13339:42) at Object.debugCreateRootView [as createRootView] (http://127.0.0.1:8100/build/main.js:12800:12)
Stack
Error: Uncaught (in promise): Error: No provider for MediaCapture!
Error
    at g (http://127.0.0.1:8100/build/polyfills.js:3:7133)
    at injectionError (http://127.0.0.1:8100/build/main.js:1511:86)
    at noProviderError (http://127.0.0.1:8100/build/main.js:1549:12)
    at ReflectiveInjector_._throwOrNull (http://127.0.0.1:8100/build/main.js:3051:19)
    at ReflectiveInjector_._getByKeyDefault (http://127.0.0.1:8100/build/main.js:3090:25)
    at ReflectiveInjector_._getByKey (http://127.0.0.1:8100/build/main.js:3022:25)
    at ReflectiveInjector_.get (http://127.0.0.1:8100/build/main.js:2891:21)
    at AppModuleInjector.NgModuleInjector.get (http://127.0.0.1:8100/build/main.js:3856:52)
    at resolveDep (http://127.0.0.1:8100/build/main.js:11260:45)
    at createClass (http://127.0.0.1:8100/build/main.js:11117:35)
    at createDirectiveInstance (http://127.0.0.1:8100/build/main.js:10954:37)
    at createViewNodes (http://127.0.0.1:8100/build/main.js:12303:49)
    at createRootView (http://127.0.0.1:8100/build/main.js:12208:5)
    at callWithDebugContext (http://127.0.0.1:8100/build/main.js:13339:42)
    at Object.debugCreateRootView [as createRootView] (http://127.0.0.1:8100/build/main.js:12800:12)
    at g (http://127.0.0.1:8100/build/polyfills.js:3:7133)
    at l (http://127.0.0.1:8100/build/polyfills.js:3:6251)
    at http://127.0.0.1:8100/build/polyfills.js:3:6805
    at t.invokeTask (http://127.0.0.1:8100/build/polyfills.js:3:15213)
    at Object.onInvokeTask (http://127.0.0.1:8100/build/main.js:4415:37)
    at t.invokeTask (http://127.0.0.1:8100/build/polyfills.js:3:15134)
    at n.runTask (http://127.0.0.1:8100/build/polyfills.js:3:10390)
    at a (http://127.0.0.1:8100/build/polyfills.js:3:5313)
Ionic Framework: 3.0.1
Ionic App Scripts: 1.3.0
Angular Core: 4.0.0
Angular Compiler CLI: 4.0.0
Node: 6.10.1
OS Platform: macOS Sierra
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) Ap
</code>```

答:
You need to add MediaCapture class in poviders of your app.module.ts file found in app folder.</p>

```<code>import { MediaCapture } from '@ionic-native/media-capture';

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
   //
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, MediaCapture ]
})

export class AppModule {}
</code>```

Body:
I am trying to use the most simple form of the MediaCapture for Ionic 2. I created a brand new project and added it as mentioned here.

But when I try to use it:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@ionic-native/media-capture';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(private mediaCapture: MediaCapture) {

  }

}

This error comes in (at the end of it is my environment info):

Runtime Error
Uncaught (in promise): Error: No provider for MediaCapture! Error at g (http://127.0.0.1:8100/build/polyfills.js:3:7133) at injectionError (http://127.0.0.1:8100/build/main.js:1511:86) at noProviderError (http://127.0.0.1:8100/build/main.js:1549:12) at ReflectiveInjector_._throwOrNull (http://127.0.0.1:8100/build/main.js:3051:19) at ReflectiveInjector_._getByKeyDefault (http://127.0.0.1:8100/build/main.js:3090:25) at ReflectiveInjector_._getByKey (http://127.0.0.1:8100/build/main.js:3022:25) at ReflectiveInjector_.get (http://127.0.0.1:8100/build/main.js:2891:21) at AppModuleInjector.NgModuleInjector.get (http://127.0.0.1:8100/build/main.js:3856:52) at resolveDep (http://127.0.0.1:8100/build/main.js:11260:45) at createClass (http://127.0.0.1:8100/build/main.js:11117:35) at createDirectiveInstance (http://127.0.0.1:8100/build/main.js:10954:37) at createViewNodes (http://127.0.0.1:8100/build/main.js:12303:49) at createRootView (http://127.0.0.1:8100/build/main.js:12208:5) at callWithDebugContext (http://127.0.0.1:8100/build/main.js:13339:42) at Object.debugCreateRootView [as createRootView] (http://127.0.0.1:8100/build/main.js:12800:12)
Stack
Error: Uncaught (in promise): Error: No provider for MediaCapture!
Error
    at g (http://127.0.0.1:8100/build/polyfills.js:3:7133)
    at injectionError (http://127.0.0.1:8100/build/main.js:1511:86)
    at noProviderError (http://127.0.0.1:8100/build/main.js:1549:12)
    at ReflectiveInjector_._throwOrNull (http://127.0.0.1:8100/build/main.js:3051:19)
    at ReflectiveInjector_._getByKeyDefault (http://127.0.0.1:8100/build/main.js:3090:25)
    at ReflectiveInjector_._getByKey (http://127.0.0.1:8100/build/main.js:3022:25)
    at ReflectiveInjector_.get (http://127.0.0.1:8100/build/main.js:2891:21)
    at AppModuleInjector.NgModuleInjector.get (http://127.0.0.1:8100/build/main.js:3856:52)
    at resolveDep (http://127.0.0.1:8100/build/main.js:11260:45)
    at createClass (http://127.0.0.1:8100/build/main.js:11117:35)
    at createDirectiveInstance (http://127.0.0.1:8100/build/main.js:10954:37)
    at createViewNodes (http://127.0.0.1:8100/build/main.js:12303:49)
    at createRootView (http://127.0.0.1:8100/build/main.js:12208:5)
    at callWithDebugContext (http://127.0.0.1:8100/build/main.js:13339:42)
    at Object.debugCreateRootView [as createRootView] (http://127.0.0.1:8100/build/main.js:12800:12)
    at g (http://127.0.0.1:8100/build/polyfills.js:3:7133)
    at l (http://127.0.0.1:8100/build/polyfills.js:3:6251)
    at http://127.0.0.1:8100/build/polyfills.js:3:6805
    at t.invokeTask (http://127.0.0.1:8100/build/polyfills.js:3:15213)
    at Object.onInvokeTask (http://127.0.0.1:8100/build/main.js:4415:37)
    at t.invokeTask (http://127.0.0.1:8100/build/polyfills.js:3:15134)
    at n.runTask (http://127.0.0.1:8100/build/polyfills.js:3:10390)
    at a (http://127.0.0.1:8100/build/polyfills.js:3:5313)
Ionic Framework: 3.0.1
Ionic App Scripts: 1.3.0
Angular Core: 4.0.0
Angular Compiler CLI: 4.0.0
Node: 6.10.1
OS Platform: macOS Sierra
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) Ap

Body:
You need to add MediaCapture class in poviders of your app.module.ts file found in app folder.

import { MediaCapture } from '@ionic-native/media-capture';

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
   //
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, MediaCapture ]
})

export class AppModule {}


问:
How can I get an object inside a javascript event handler?
I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

```<code>var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () {
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}
</code>```

What I expect is:

```<code>this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3
</code>```

But what I get is:

```<code>this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3
</code>```

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

答:
This is because of the way closures work in JavaScript. The onclick reference on all the 3 elements store the same function which after the loop has entry pointing to last entry. Hence the result. You can get your result by wrapping it in another function having the needed entry. Following is one way to do it:

```<code>var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    function setOnClickHandler(entry) {
        document.getElementById(entry.id).onclick = function () {
            console.log("this.id: " + this.id);
            console.log("entry.id: " + entry.id);
        };
    }

    setOnClickHandler(entry);
}
</code>```

I've written a small post on this.

Body:
I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () {
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}

What I expect is:

this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3

But what I get is:

this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

Body:
This is because of the way closures work in JavaScript. The onclick reference on all the 3 elements store the same function which after the loop has entry pointing to last entry. Hence the result. You can get your result by wrapping it in another function having the needed entry. Following is one way to do it:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    function setOnClickHandler(entry) {
        document.getElementById(entry.id).onclick = function () {
            console.log("this.id: " + this.id);
            console.log("entry.id: " + entry.id);
        };
    }

    setOnClickHandler(entry);
}

I've written a small post on this.


问:
How to force JavaScript integer to keep a zero before numbers?
How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

```<code>var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);
</code>```

答:
As I know the only way is keeping it as string or adding the 0 just before showing it

var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(0 + mapcode.toString());```

ContentLicense: CC BY-SA 4.0

Body:
How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);


问:
Style link based on active route in React Router v4
I have a Navlink element as follows:

```<code>  <NavLink isActive={this.isActiveFunc.bind(this)} className={classes.subLink} to={{ pathname: "/admin/users" }}>
       <ListItem button className={classes.nested}>
           <ListItemText inset primary="Users" />
       </ListItem>
  </NavLink>
</code>```

When this link is active I want the ListItemText to be styled differently. To do this I tried applying the following logic

```<code> isActiveFunc = (match, location) => {
    this.setState({activePath: match.path});
    return match
  };
</code>```

Whereafter I can set the style if the activePath state matches the to path. However, this yields an error:

TypeError: Cannot read property 'path' of null

答:
How much control do you have over styling the ListItemText?  Can you pass it a prop or className if it is active?:

```<code><NavLink className={classes.subLink} to={{ pathname: "/admin/users" }}>
   <ListItem button className={classes.nested}>
       <ListItemText inset primary="Users" passDownAClassName={props.match.path == "/admin/users" ? 'active-class' : 'inactive-class'} />
   </ListItem>
</NavLink>
</code>```

Or :

```<code><NavLink className={classes.subLink} to={{ pathname: "/admin/users" }}>
   <ListItem button className={classes.nested}>
       <ListItemText inset primary="Users" isActive={props.match.path == "/admin/users"} />
   </ListItem>
</NavLink>
</code>```

Body:
I have a Navlink element as follows:

  <NavLink isActive={this.isActiveFunc.bind(this)} className={classes.subLink} to={{ pathname: "/admin/users" }}>
       <ListItem button className={classes.nested}>
           <ListItemText inset primary="Users" />
       </ListItem>
  </NavLink>

When this link is active I want the ListItemText to be styled differently. To do this I tried applying the following logic

 isActiveFunc = (match, location) => {
    this.setState({activePath: match.path});
    return match
  };

Whereafter I can set the style if the activePath state matches the to path. However, this yields an error:

TypeError: Cannot read property 'path' of null

Body:
How much control do you have over styling the ListItemText?  Can you pass it a prop or className if it is active?:

<NavLink className={classes.subLink} to={{ pathname: "/admin/users" }}>
   <ListItem button className={classes.nested}>
       <ListItemText inset primary="Users" passDownAClassName={props.match.path == "/admin/users" ? 'active-class' : 'inactive-class'} />
   </ListItem>
</NavLink>

Or :

<NavLink className={classes.subLink} to={{ pathname: "/admin/users" }}>
   <ListItem button className={classes.nested}>
       <ListItemText inset primary="Users" isActive={props.match.path == "/admin/users"} />
   </ListItem>
</NavLink>


问:
if-else not working in __construct()
php's if else is not working in __construct(). If SESSION is not empty, i create it, and log, else I log it. But none of logs happens { if {} { log } else { log}. It logs only the last line after if else.

```<code><?php

class Controller  {

    public function __construct() {

        // parent::__construct();

        if( empty($_SESSION) ) {
            $nowStr = '' . time() .'_';
            $sesname = !empty( $givArr['sesname'] ) ? $givArr['sesname'] : uniqid ($nowStr).uniqid() ;
            $oldSesname = session_name($sesname);
            session_start();
            $_SESSION['name']=$sesname;
            file_put_contents( PATH_LOG . 'n ses171113', PHP_EOL.' ###################### src\core\Controller.php   STARTED _SESSION='. json_encode( $_SESSION ) . PHP_EOL.PHP_EOL, FILE_APPEND ) ;
        } // DOES NOT LOG NEVER
        else {
            file_put_contents( PATH_LOG . ' ses171113', PHP_EOL.' ###################### src\core\Controller.php   CONTINUE _SESSION='. json_encode( $_SESSION ) . PHP_EOL.PHP_EOL, FILE_APPEND ) ;
        } // DOES NOT LOG NEVER

        file_put_contents( PATH_LOG . ' ses171113', PHP_EOL.' ###################### src\core\Controller.php   case out of scope =' . PHP_EOL.PHP_EOL, FILE_APPEND ) ;  //  LOGS

    }
</code>```

答:
Your code is broken. $_SESSION is superglobal, so checking if it exists if futile is you started the session. Aside from that you access $givArr which is non existing variable.

I strongly recommend you do error_reporting(E_ALL); at the very first line of your scripts as you are simply muting all the useful error reports. Also static analysis of your code is something you should consider doing.

Title: if-else not working in __construct()

Body:
php's if else is not working in __construct(). If SESSION is not empty, i create it, and log, else I log it. But none of logs happens { if {} { log } else { log}. It logs only the last line after if else.

<?php

class Controller  {

    public function __construct() {

        // parent::__construct();

        if( empty($_SESSION) ) {
            $nowStr = '' . time() .'_';
            $sesname = !empty( $givArr['sesname'] ) ? $givArr['sesname'] : uniqid ($nowStr).uniqid() ;
            $oldSesname = session_name($sesname);
            session_start();
            $_SESSION['name']=$sesname;
            file_put_contents( PATH_LOG . 'n ses171113', PHP_EOL.' ###################### src\core\Controller.php   STARTED _SESSION='. json_encode( $_SESSION ) . PHP_EOL.PHP_EOL, FILE_APPEND ) ;
        } // DOES NOT LOG NEVER
        else {
            file_put_contents( PATH_LOG . ' ses171113', PHP_EOL.' ###################### src\core\Controller.php   CONTINUE _SESSION='. json_encode( $_SESSION ) . PHP_EOL.PHP_EOL, FILE_APPEND ) ;
        } // DOES NOT LOG NEVER

        file_put_contents( PATH_LOG . ' ses171113', PHP_EOL.' ###################### src\core\Controller.php   case out of scope =' . PHP_EOL.PHP_EOL, FILE_APPEND ) ;  //  LOGS

    }


问:
Can Matrices be passed as arguments in Octave?
I am implementing the non-vectorized form of the cost function in octave. This is the code from my .m file

function computeCost(X, y, theta)
sigma=0;
theta0 = 0;
m = length(y);

for i = 1:m
sigma = sigma+ theta*X(i)-y(i);
end;

J = ((sigma)^2)/2*m;

end;
```

<p>My octave code is:</p>

<pre class="lang-matlab prettyprint-override"><code>>> X= [1,1; 1,2; 1,3; 1,4;];
>> y= [2;4;6;8];
>> J = computeCost(X, y, 0.5);
</code>```

where X and y are matrices. However, I am getting this output on my CLI Window:

Error: computeCost(X, y, 0.5) undefined near line 1, column 5
```

I've checked my code, there is no apparent issue. Is it because Octave does not accept matrices as parameters for its functions?

答:
The answer to your question is clearly YES: The name MATLAB is an abbreviation of Matrix laboratory. Octave and Matlab are specially designed to facilitate working with matrices.

The problem in your code is: Your function definition is incomplete. You have not defined J as return value. The error message you see is a bit missleading because it should state column 10 as place of the error. When you change the first line of your code to

```<code>function J = computeCost(X, y, theta)
</code>```

It will work as expected and output the value 648.

Body:
I am implementing the non-vectorized form of the cost function in octave. This is the code from my .m file

function computeCost(X, y, theta)
sigma=0;
theta0 = 0;
m = length(y);

for i = 1:m
sigma = sigma+ theta*X(i)-y(i);
end;

J = ((sigma)^2)/2*m;

end;

My octave code is:

>> X= [1,1; 1,2; 1,3; 1,4;];
>> y= [2;4;6;8];
>> J = computeCost(X, y, 0.5);

where X and y are matrices. However, I am getting this output on my CLI Window:

Error: computeCost(X, y, 0.5) undefined near line 1, column 5

I've checked my code, there is no apparent issue. Is it because Octave does not accept matrices as parameters for its functions?

Body:
The answer to your question is clearly YES: The name MATLAB is an abbreviation of Matrix laboratory. Octave and Matlab are specially designed to facilitate working with matrices.

The problem in your code is: Your function definition is incomplete. You have not defined J as return value. The error message you see is a bit missleading because it should state column 10 as place of the error. When you change the first line of your code to

function J = computeCost(X, y, theta)

It will work as expected and output the value 648.


问:
GitKraken - Delete Account
Does anyone know how to delete an account in GitKraken? I have searched the whole web for instructions but did not find anything.</p>

答:
Click gitkraken account to go to account, or click Manage Account from the user menu dropdown in-app.

In Manage Users on a subscription, click Delete next to the user on the list followed by Remove User for confirmation to remove a user and free up a license.

Title: GitKraken - Delete Account


问:
NSTask / Process deprecated methods and properties
In the most recent Apple documentation both NSTask and Process have several deprecated methods and properties, although there's nothing marked with an API Availability Macro.

Instance Properties

```<code>@property(copy) NSString *launchPath;
@property(copy) NSString *currentDirectoryPath;

var launchPath: String? { get set }
var currentDirectoryPath: String { get set }
</code>```

Instance Methods

```<code>- (void)launch;

func launch()
</code>```

Type Methods

```<code>+ (NSTask *)launchedTaskWithLaunchPath:(NSString *)path
                             arguments:(NSArray<NSString *> *)arguments;

class func launchedProcess(launchPath path: String,
                 arguments: [String]) -> Process
</code>```

There seemingly are no replacements available, so what gives?

答:
There seemingly are no replacements available

There are, the API is now URL related

Instance Properties

```<code>@property(copy) NSURL *executableURL;
@property(copy) NSURL *currentDirectoryURL;

var executableURL: URL? { get set }
var currentDirectoryURL: URL? { get set }
</code>```

Instance Methods

```<code>- (BOOL)launchAndReturnError:(out NSError * _Nullable *)error;

func run() throws
</code>```

Type Methods

```<code>+ (NSTask *)launchedTaskWithExecutableURL:(NSURL *)url
                                arguments:(NSArray<NSString *> *)arguments
                                    error:(out NSError * _Nullable *)error
                       terminationHandler:(void (^)(NSTask *))terminationHandler;

class func run(_ url: URL,
               arguments: [String],
               terminationHandler: ((Process) -> Void)? = nil) throws -> Process
</code>```

Body:
In the most recent Apple documentation both NSTask and Process have several deprecated methods and properties, although there's nothing marked with an API Availability Macro.

Instance Properties

@property(copy) NSString *launchPath;
@property(copy) NSString *currentDirectoryPath;

var launchPath: String? { get set }
var currentDirectoryPath: String { get set }

Instance Methods

- (void)launch;

func launch()

Type Methods

+ (NSTask *)launchedTaskWithLaunchPath:(NSString *)path
                             arguments:(NSArray<NSString *> *)arguments;

class func launchedProcess(launchPath path: String,
                 arguments: [String]) -> Process

There seemingly are no replacements available, so what gives?

Body:
There seemingly are no replacements available

There are, the API is now URL related

Instance Properties

@property(copy) NSURL *executableURL;
@property(copy) NSURL *currentDirectoryURL;

var executableURL: URL? { get set }
var currentDirectoryURL: URL? { get set }

Instance Methods

- (BOOL)launchAndReturnError:(out NSError * _Nullable *)error;

func run() throws

Type Methods

+ (NSTask *)launchedTaskWithExecutableURL:(NSURL *)url
                                arguments:(NSArray<NSString *> *)arguments
                                    error:(out NSError * _Nullable *)error
                       terminationHandler:(void (^)(NSTask *))terminationHandler;

class func run(_ url: URL,
               arguments: [String],
               terminationHandler: ((Process) -> Void)? = nil) throws -> Process


问:
CSS - automatic div width
I have html structure that can change depending on the page context. On some pages looks like:

```<code><div class="container">
  <div class="column">
    blah
  </div>
</div>
</code>```

And on others:

```<code><div class="container">
  <div class="column">
    blah
  </div>
  <div class="column">
    blah
  </div>
</div>
</code>```

So, the container has a fluid width (100%).

The .column div is fluid too, and should have the width of its container in the first example, ie. 100%,
and in the second example 50% width and aligned to left.

Like:

```<code>----------------------------
|                           |
|         column1           |
|                           |
-----------------------------
</code>```

and

```<code>----------------------------
|            |              |
|  column2   |  column2     |
|            |              |
-----------------------------
</code>```

How can I do this?

I should also note that I can't change any markup within column1/column2 (can't add classes or anything like that, maybe only using javascript hacks or capture the php output and using regex :)

答:
The best I can come up with is JavaScript: http://jsfiddle.net/V5Au7/.

Some pretty annoying gotchas:

This assumes that the only divs in the #container are the ones with the class name of "column."

This assumes that the columns have no borders, padding, or margin.

You could run into sub-pixel problems, by relying on percentages. Of course, this probably won't be a problem if you stick with just one or two columns.

There's gotta be some CSS-only way that can also work in IE6. I can feel it, I just can't find it.

Title: CSS - automatic div width

Body:
I have html structure that can change depending on the page context. On some pages looks like:

    blah

And on others:

    blah

    blah

So, the container has a fluid width (100%).

The .column div is fluid too, and should have the width of its container in the first example, ie. 100%,
and in the second example 50% width and aligned to left.

Like:

----------------------------
|                           |
|         column1           |
|                           |
-----------------------------

and

----------------------------
|            |              |
|  column2   |  column2     |
|            |              |
-----------------------------

How can I do this?

I should also note that I can't change any markup within column1/column2 (can't add classes or anything like that, maybe only using javascript hacks or capture the php output and using regex :)


问:
Finding duplicate values only for 2 highest values in a dict
Code:

```<code>candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")
</code>```

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

答:
To find the duplicates that are the maximum of the values or the second highest, you can try this:

```<code>candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
tie_breakers = [a for a, b in candidates_and_fp_votes.items() if list(candidates_and_fp_votes.values()).count(b) > 1 and b in [d for c, d in sorted(candidates_and_fp_votes.items(), key=lambda x:x[-1])[-2:]]]
</code>```

Output:

```<code>['c', 'd']
</code>```

Body:
Code:

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

Body:
To find the duplicates that are the maximum of the values or the second highest, you can try this:

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
tie_breakers = [a for a, b in candidates_and_fp_votes.items() if list(candidates_and_fp_votes.values()).count(b) > 1 and b in [d for c, d in sorted(candidates_and_fp_votes.items(), key=lambda x:x[-1])[-2:]]]

Output:

['c', 'd']


问:
Print out an array in uppercase Java
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

```<code>package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}
</code>```

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

答:
You can read the values and uppercase them directly:</p>

```<code>String firstName = userInput.nextLine().toUpperCase();
</code>```

Title: Print out an array in uppercase Java

Body:
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

Body:
You can read the values and uppercase them directly:

String firstName = userInput.nextLine().toUpperCase();


问:
loop through string to find substring
I have this string:

```<code>text = "book//title//page/section/para";
</code>```

I want to go through it to find all // and / and their index.

I tried doing this with:

```<code>if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));
}
</code>```

I was also thinking about using:

```<code>Foreach(char c in text)
</code>```

but it will not work since // is not a single char.

How can I achieve what I want?

I tried this one also but did not display result

```<code>string input = "book//title//page/section/para";
string pattern = @"\/\//";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }
</code>```

Thank you in advance.

答:
Would it be possible using Split?

So:

```<code>string[] words = text.Split(@'/');
</code>```

And then go through the words? You would have blanks, due to the //, but that might be possible?

Title: loop through string to find substring

Body:
I have this string:

text = "book//title//page/section/para";

I want to go through it to find all // and / and their index.

I tried doing this with:

if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));
}

I was also thinking about using:

Foreach(char c in text)

but it will not work since // is not a single char.

How can I achieve what I want?

I tried this one also but did not display result

string input = "book//title//page/section/para";
string pattern = @"\/\//";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }

Thank you in advance.

Body:
Would it be possible using Split?

So:

string[] words = text.Split(@'/');

And then go through the words? You would have blanks, due to the //, but that might be possible?


问:
Postgres executable for standalone mode in Ubuntu
I installed Postgres 9.5 on Ubuntu 16.10 a while ago, following instructions here.

I need to run Postgres in standalone mode for a database vacuum. I need to run this command:

```<code>postgres --single -D /full/path/to/datadir postgres
</code>```

But the postgres command is not available:

```<code>$ postgres
No command 'postgres' found, did you mean:
 Command 'postgrey' from package 'postgrey' (universe)
postgres: command not found
</code>```

Its not available in the postgres user path either:

```<code>dbuser@pgserver:~$ sudo -i
root@pgserver:~# su postgres
postgres@pgserver:/root$ postgres
No command 'postgres' found, did you mean:
 Command 'postgrey' from package 'postgrey' (universe)
postgres: command not found
</code>```

Where is this utility, or what do I need to install to have access to it?

答:
The postgres command (as well as pg_ctl and others) are in /usr/lib/postgresql/9.5/bin.

Notably, they have to be run by a non-privileged user like postgres. Here's what I did to resolve my issue:

Make home directory for postgres user:

```<code>$ sudo -i
$ mkdir /home/postgres
$ chown postgres:postgres /home/postgres
$ usermod -d /home/postgres/ postgres
</code>```

Edit the PATH:

```<code>$ su - postgres
$ vim ~/.bash_profile
</code>```

Append:

```<code>PATH=$PATH:/usr/lib/postgresql/9.5/bin
export PATH
</code>```

Run su - postgres to access the commands:

```<code>$ postgres --single -D /full/path/to/datadir postgres
PostgreSQL stand-alone backend 9.5.7
backend>
</code>```

Body:
I installed Postgres 9.5 on Ubuntu 16.10 a while ago, following instructions here.

I need to run Postgres in standalone mode for a database vacuum. I need to run this command:

postgres --single -D /full/path/to/datadir postgres

But the postgres command is not available:

$ postgres
No command 'postgres' found, did you mean:
 Command 'postgrey' from package 'postgrey' (universe)
postgres: command not found

Its not available in the postgres user path either:

dbuser@pgserver:~$ sudo -i
root@pgserver:~# su postgres
postgres@pgserver:/root$ postgres
No command 'postgres' found, did you mean:
 Command 'postgrey' from package 'postgrey' (universe)
postgres: command not found

Where is this utility, or what do I need to install to have access to it?

Body:
The postgres command (as well as pg_ctl and others) are in /usr/lib/postgresql/9.5/bin.

Notably, they have to be run by a non-privileged user like postgres. Here's what I did to resolve my issue:

Make home directory for postgres user:

$ sudo -i
$ mkdir /home/postgres
$ chown postgres:postgres /home/postgres
$ usermod -d /home/postgres/ postgres

Edit the PATH:

$ su - postgres
$ vim ~/.bash_profile

Append:

PATH=$PATH:/usr/lib/postgresql/9.5/bin
export PATH

Run su - postgres to access the commands:

$ postgres --single -D /full/path/to/datadir postgres
PostgreSQL stand-alone backend 9.5.7
backend>


问:
ggplot place facet between two rows of facets
I have 9 plots with 3 time series in each plot, one of these plots contains only one curve and it's the reference plot which I would like to place in between the two rows that contain the other 8 plots. Is there an easy way to do so?
I use facet_wrap(~density,nrow=2) but I get one row with 5 and another with 4 plots. I am sure other people had this problem, is there an easy way around to organize the position of this reference plot, or do I have to create two separate plots and overlay them? Otherwise I might have to move this reference plot in all the other plots but it seems redundant information.

This is my current result, but as you can see it's not very well laid out.

答:
If I understand the question correctly you could reformat your data with appropriate facetting variables to introduce a new row of reference panels

```<code>library(ggplot2)

d <- data.frame(x=rep(1:10, 8), y = rnorm(80),
                f=gl(8,10, ordered = TRUE))
d$f1 <- factor(d$f <= 4, labels=c(1,3))
d$f2 <- as.numeric(d$f) %% 4

d2 <- data.frame(x=1:10, y=0, f1 = 2)

ggplot(d, aes(x,y)) +
  geom_point(aes(colour=f)) +
  geom_point(data=d2, colour="black") +
  facet_grid(f1~f2)
</code>```

Body:
If I understand the question correctly you could reformat your data with appropriate facetting variables to introduce a new row of reference panels

library(ggplot2)

d <- data.frame(x=rep(1:10, 8), y = rnorm(80),
                f=gl(8,10, ordered = TRUE))
d$f1 <- factor(d$f <= 4, labels=c(1,3))
d$f2 <- as.numeric(d$f) %% 4

d2 <- data.frame(x=1:10, y=0, f1 = 2)

ggplot(d, aes(x,y)) +
  geom_point(aes(colour=f)) +
  geom_point(data=d2, colour="black") +
  facet_grid(f1~f2)


问:
Display Jquery chosen data from database to update [Codeigniter]
I have jQuery chosen named centro medicos in an insertion form, I can select all data, select some of the data. If I click select all here is the result:

Let's say that I select only 3 items and then I save.  Now I want to edit. When the edit page is loaded I want to have the 3 items that I selected loaded:

And if I click on select all (Selectionar todo) the rest of items are displayed.

1- Controller

```<code>public function edit_form()
{
    $edit_id= $this->uri->segment(3);
    $data['ITEM_EDIT'] = $this->model->get_title_by_id($edit_id);
    $data['ITEM_ALL']= $this->model->get_all_title();
    $this->load->view('view_edit_form', $data);
}
</code>```

2- View

```<code><select class="chosen-select"  multiple  name="item[]">
<?php
    foreach($ITEM_ALL as $item_all) {
        foreach($ITEM_EDIT as $item_edit) {
            if($title_edit->title== $title_all->title)
            {
                 echo '<option value="'.$item_all->title.'" class="'.$item_all->id.'" selected>'.$item_all->title.'</option>';
             }
             else
             {
                 echo '<option value="'.$item_all->title.'" class="'.$item_all->id.'" >'.$item_all->title.'</option>';
             }
        }
    }
?>
 </select>
</code>```

3- jQuery

```<code>$(".chosen-select").chosen({
    no_results_text: "Oops, nothing found : ",
})
</code>```

How can I achieve this?

答:
Thanks to every one that helped me with this issues.
The response of Darshan works in deed, but it's not regarding my case because the select should be from 2 tables in other to edit it.
when i click on edit I grab the edit id that is found in the second table.

table one: from it i grab all data to save in database

1- Table Centro_medico

```
id          name
1           hosptal a
2           hospital b
3           hospital c
4           hospital d
5           hospital e
```

After select one or more in this table, we save data in the second table:

2- table 2 (hospital)

```
id  id_lind  id_centro_medico
1   2        1
2   2        2
3   2        3

```

the id_link column is the id pass to url in the edit_form

1- controller

```<code>public function edit_form()
{
$edit_id= $this->uri->segment(3);

$data['ITEM_ALL']= $this->model->get_all_centro_medico();
$this->load->view('view_edit_form', $data);
}
</code>```

2- view edit form

```<code><div class="form-group">
<label class="control-label col-sm-4">Centro médico</label>
<div class="col-sm-4">
<button type="button" class="chosen-toggle select col-xs-6">Select all</button>
<button type="button" class="chosen-toggle deselect col-xs-6">Deselect all</button>

<select  class="form-control chosen-select" data-placeholder="Comienza a escribir un nombre para filtrar." multiple  name="seguro_medico[]" >

<?php
// I select id_centro_medico equal to edit_id and equal to id of each centro_medico row  ,
// and I compare them

            foreach($ITEM_ALL as $row)
            {

            $id_centro_medico=$this->db->select('id_lind')->where('id_lind',$edit_id )
             ->where('id_centro_medico',$row->id)
             ->get('hospital')->row('id_lind');

                    if($edit_id==$id_centro_medico){
                            $selected="selected";
                    } else {
                           $selected="";
                    }

            echo "<option value='$row->id_sm.' $selected>$row->title</option>";
            }
            ?>
            </select>
            </div>
            </div>
</code>```

At last i don't need to use :

```<code>$(function(){
$(".chosen-select").trigger("chosen:updated");
})
</code>```

Body:
I have jQuery chosen named centro medicos in an insertion form, I can select all data, select some of the data. If I click select all here is the result:

Let's say that I select only 3 items and then I save.  Now I want to edit. When the edit page is loaded I want to have the 3 items that I selected loaded:

And if I click on select all (Selectionar todo) the rest of items are displayed.

1- Controller

public function edit_form()
{
    $edit_id= $this->uri->segment(3);
    $data['ITEM_EDIT'] = $this->model->get_title_by_id($edit_id);
    $data['ITEM_ALL']= $this->model->get_all_title();
    $this->load->view('view_edit_form', $data);
}

2- View

<select class="chosen-select"  multiple  name="item[]">
<?php
    foreach($ITEM_ALL as $item_all) {
        foreach($ITEM_EDIT as $item_edit) {
            if($title_edit->title== $title_all->title)
            {
                 echo '<option value="'.$item_all->title.'" class="'.$item_all->id.'" selected>'.$item_all->title.'</option>';
             }
             else
             {
                 echo '<option value="'.$item_all->title.'" class="'.$item_all->id.'" >'.$item_all->title.'</option>';
             }
        }
    }
?>
 </select>

3- jQuery

$(".chosen-select").chosen({
    no_results_text: "Oops, nothing found : ",
})

How can I achieve this?

Body:
Thanks to every one that helped me with this issues.
The response of Darshan works in deed, but it's not regarding my case because the select should be from 2 tables in other to edit it.
when i click on edit I grab the edit id that is found in the second table.

table one: from it i grab all data to save in database

1- Table Centro_medico

id          name
1           hosptal a
2           hospital b
3           hospital c
4           hospital d
5           hospital e

After select one or more in this table, we save data in the second table:

2- table 2 (hospital)

id  id_lind  id_centro_medico
1   2        1
2   2        2
3   2        3

the id_link column is the id pass to url in the edit_form

1- controller

public function edit_form()
{
$edit_id= $this->uri->segment(3);

$data['ITEM_ALL']= $this->model->get_all_centro_medico();
$this->load->view('view_edit_form', $data);
}

2- view edit form

<div class="form-group">
<label class="control-label col-sm-4">Centro médico</label>
<div class="col-sm-4">
<button type="button" class="chosen-toggle select col-xs-6">Select all</button>
<button type="button" class="chosen-toggle deselect col-xs-6">Deselect all</button>

<select  class="form-control chosen-select" data-placeholder="Comienza a escribir un nombre para filtrar." multiple  name="seguro_medico[]" >

<?php
// I select id_centro_medico equal to edit_id and equal to id of each centro_medico row  ,
// and I compare them

            foreach($ITEM_ALL as $row)
            {

            $id_centro_medico=$this->db->select('id_lind')->where('id_lind',$edit_id )
             ->where('id_centro_medico',$row->id)
             ->get('hospital')->row('id_lind');

                    if($edit_id==$id_centro_medico){
                            $selected="selected";
                    } else {
                           $selected="";
                    }

            echo "<option value='$row->id_sm.' $selected>$row->title</option>";
            }
            ?>
            </select>
            </div>
            </div>

At last i don't need to use :

$(function(){
$(".chosen-select").trigger("chosen:updated");
})


问:
Count matches at the end of a string
I want to count the number of occurrences of a string at the end of the string.  I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.

terminal string to find: "-1"

```<code>e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0
</code>```

I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.

I tried:

```<code>var occurrences = string.match(/(-1)*$/).length;
</code>```

I have a JS Fiddle here: JS Fiddle

It returns "2", no matter what my string.

答:
Use String#match to find the chain of -1 that reaches the end, then split by -1, and get the length -1. When you split an a string of -1-1-1 you'll get an array with four items. Now we can extract the length, and reduce it by one.

function m(str) {
  return str.match(/(-1)*$/g)[0].split(-1).length - 1;
}

console.log(m('1')) // 0
console.log(m('1-1')) // 1
console.log(m('1-1-1')) // 2
console.log(m('1-2-1')) // 1
console.log(m('1-2-1-2-1')) // 1
console.log(m('2-1-1-1-1')) // 4
console.log(m('1-1-2')) // 0```

Title: Count matches at the end of a string

Body:
I want to count the number of occurrences of a string at the end of the string.  I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.

terminal string to find: "-1"

e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0

I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.

I tried:

var occurrences = string.match(/(-1)*$/).length;

I have a JS Fiddle here: JS Fiddle

It returns "2", no matter what my string.


问:
swift - is it possible to create a keypath to a method?
Is it possible to create a keypath referencing a method? all examples are paths to variables.

I'm trying this:

```<code>class MyClass {
    init() {
        let myKeypath = \MyClass.handleMainAction
        ...
    }
    func handleMainAction() {...}
}
</code>```

but it does not compile saying Key path cannot refer to instance method 'handleMainAction()

答:
KeyPaths are for properties.  However, you can do effectively the same thing.  Because functions are first class types in swift, you can create a reference to handleMainAction and pass it around:

```<code>//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport

class MyClass {
    var bar = 0

    private func handleMainAction() -> Int {
        bar = bar + 1
        return bar
    }

    func getMyMainAction() -> ()->Int {
        return self.handleMainAction
    }
}

class AnotherClass {
    func runSomeoneElsesBarFunc(passedFunction:() -> Int) {
        let result = passedFunction()
        print("What I got was \(result)")
    }
}

let myInst = MyClass()
let anotherInst = AnotherClass()
let barFunc = myInst.getMyMainAction()

anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
</code>```

This will work fine, and you can pass "barFunc" to any other class or method and it can be used.

Body:
Is it possible to create a keypath referencing a method? all examples are paths to variables.

I'm trying this:

class MyClass {
    init() {
        let myKeypath = \MyClass.handleMainAction
        ...
    }
    func handleMainAction() {...}
}

but it does not compile saying Key path cannot refer to instance method 'handleMainAction()

Body:
KeyPaths are for properties.  However, you can do effectively the same thing.  Because functions are first class types in swift, you can create a reference to handleMainAction and pass it around:

//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport

class MyClass {
    var bar = 0

    private func handleMainAction() -> Int {
        bar = bar + 1
        return bar
    }

    func getMyMainAction() -> ()->Int {
        return self.handleMainAction
    }
}

class AnotherClass {
    func runSomeoneElsesBarFunc(passedFunction:() -> Int) {
        let result = passedFunction()
        print("What I got was \(result)")
    }
}

let myInst = MyClass()
let anotherInst = AnotherClass()
let barFunc = myInst.getMyMainAction()

anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)

This will work fine, and you can pass "barFunc" to any other class or method and it can be used.


问:
How to check group membership for a process that is not "self"?
I'm trying to use this code to check security group membership for an arbitrary process that I have a handle for. But in my code below CheckTokenMembership fails with error code 1309, or ERROR_NO_IMPERSONATION_TOKEN. I'm not sure I understand how I can get that impersonation token...

So what am I doing wrong here?

```<code>void check_membership(HANDLE hProc)
{
    HANDLE hToken;
    if(OpenProcessToken(hProc, TOKEN_QUERY, &hToken))
    {
        check_group_membership(hToken, L"Local Group", DOMAIN_ALIAS_RID_USERS);
        check_group_membership(hToken, L"Admin Group", DOMAIN_ALIAS_RID_ADMINS);
        check_group_membership(hToken, L"Domain Admin Group", DOMAIN_GROUP_RID_ADMINS);
        check_group_membership(hToken, L"Schema Admin Group", DOMAIN_GROUP_RID_SCHEMA_ADMINS);
        check_group_membership(hToken, L"Enterprise Admin Group", DOMAIN_GROUP_RID_ENTERPRISE_ADMINS);

        CloseHandle(hToken);
    }
}

void check_group_membership(HANDLE hToken, LPCTSTR pStrName, DWORD nSubauthority)
{
    BOOL bIsMember;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;

    wprintf(L"Local %s: ", pStrName);

    PSID pSID = NULL;
    if(AllocateAndInitializeSid(&NtAuthority, 2,
        SECURITY_BUILTIN_DOMAIN_RID,
        nSubauthority,
        0, 0, 0, 0, 0, 0, &pSID))
    {
        bIsMember = FALSE;
        if(CheckTokenMembership(hToken, pSID, &bIsMember))
        {
            wprintf(L"%s", bIsMember ? L"Yes" : L"No");
        }
        else
        {
            wprintf(L"<CheckErr: (%d)>", GetLastError());
        }
    }
    else
    {
        wprintf(L"<SidErr: (%d)>", GetLastError());
    }

    wprintf(L"\n");

    if(pSID)
    {
        FreeSid(pSID) == NULL);
        pSID = NULL;
    }

}
</code>```

答:
MSDN does confirm that it is a requirement:

The token must be an impersonation token.

It also says for the NULL handle case:

CheckTokenMembership uses the impersonation token of the calling thread. If the thread is not impersonating, the function duplicates the thread's primary token to create an impersonation token.

You could try this:

```<code>HANDLE hImpToken;
if (DuplicateTokenEx(hToken, TOKEN_QUERY, NULL, SecurityImpersonation, TokenImpersonation, &hImpToken))
{
    CheckTokenMembership(hImpToken, ...);
    CloseHandle(hImpToken);
}
</code>```

Body:
I'm trying to use this code to check security group membership for an arbitrary process that I have a handle for. But in my code below CheckTokenMembership fails with error code 1309, or ERROR_NO_IMPERSONATION_TOKEN. I'm not sure I understand how I can get that impersonation token...

So what am I doing wrong here?

void check_membership(HANDLE hProc)
{
    HANDLE hToken;
    if(OpenProcessToken(hProc, TOKEN_QUERY, &hToken))
    {
        check_group_membership(hToken, L"Local Group", DOMAIN_ALIAS_RID_USERS);
        check_group_membership(hToken, L"Admin Group", DOMAIN_ALIAS_RID_ADMINS);
        check_group_membership(hToken, L"Domain Admin Group", DOMAIN_GROUP_RID_ADMINS);
        check_group_membership(hToken, L"Schema Admin Group", DOMAIN_GROUP_RID_SCHEMA_ADMINS);
        check_group_membership(hToken, L"Enterprise Admin Group", DOMAIN_GROUP_RID_ENTERPRISE_ADMINS);

        CloseHandle(hToken);
    }
}

void check_group_membership(HANDLE hToken, LPCTSTR pStrName, DWORD nSubauthority)
{
    BOOL bIsMember;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;

    wprintf(L"Local %s: ", pStrName);

    PSID pSID = NULL;
    if(AllocateAndInitializeSid(&NtAuthority, 2,
        SECURITY_BUILTIN_DOMAIN_RID,
        nSubauthority,
        0, 0, 0, 0, 0, 0, &pSID))
    {
        bIsMember = FALSE;
        if(CheckTokenMembership(hToken, pSID, &bIsMember))
        {
            wprintf(L"%s", bIsMember ? L"Yes" : L"No");
        }
        else
        {
            wprintf(L"<CheckErr: (%d)>", GetLastError());
        }
    }
    else
    {
        wprintf(L"<SidErr: (%d)>", GetLastError());
    }

    wprintf(L"\n");

    if(pSID)
    {
        FreeSid(pSID) == NULL);
        pSID = NULL;
    }

}

Body:
MSDN does confirm that it is a requirement:

The token must be an impersonation token.

It also says for the NULL handle case:

CheckTokenMembership uses the impersonation token of the calling thread. If the thread is not impersonating, the function duplicates the thread's primary token to create an impersonation token.

You could try this:

HANDLE hImpToken;
if (DuplicateTokenEx(hToken, TOKEN_QUERY, NULL, SecurityImpersonation, TokenImpersonation, &hImpToken))
{
    CheckTokenMembership(hImpToken, ...);
    CloseHandle(hImpToken);
}


问:
Change all links on a page to point to login with Spring MVC
This is more of a discussion, rather than a real question...

I'm building a site and I am struggling with how to force a user to login to the site to access certain areas and take certain actions. I'm using spring security and have it integrated fairly well, however, I also have some AJAX calls that need to be secured and when Spring Security intercepts my calls it attempts to send back the HTML for login page to my AJAX callback which doesn't do me any good.

In passed applications, when I was using Struts, I was able to override the html:link tag and check login in the tag and rewrite the href to point to my login page (instead of my ajax script), however, I'm using Spring MVC and I don't have that luxury (if you can call it one).

I'm playing with some ideas such as:

Iterating through all my links on the page and rewriting the href of the links that have a certain class if the user is not logged in

Create a custom tag from scratch

Ditch the fancy AJAX stuff

It looks like other sites, such as, DZONE and Digg do something similar; so I know it's possible.

I'm looking for any ideas at this point, just something fresh to try, other than the three options above. Of the three, I think I'm leaning more towards #1.

答:
If I understand your question correctly, you are asking how you can get around your secured AJAX requests returning redirects to your login page (or the login page itself) to your AJAX handler?

I would organise your application so that calls to secured AJAX request are only done from pages that are secured themselves. That way all requests that you initiate (from your own pages) are guaranteed to work and any requests that come from somewhere else (potentially malicious ones) from AJAX or normal page requests will be redirected to the login page.


问:
Laravel models to implement one to many and many to many in single query
i have this table structure, project has one to many relation with rewards , rewards and shipping has many to many relation with pivot table reward_ship.

```<code>projects       rewards         shipping       reward_ship
---------      --------        --------       ------------
id             id              id             id
title          amount          location       reward_id
amount         project_id      name           ship_id
</code>```

i am trying to extract one particular project details with all other associate tables data(rewards and shipping data using reward_ship table) in one query.

These is how i am trying

Projects Model

```<code>    class Rewards extends Model {
         public function projs(){
              return $this->hasMany('App\Rewards');
          }
         public function rewds(){
              return $this->belongsToMany('App\Shipping')
              ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
         public function shiplc(){
               return $this->belongsToMany('App\Rewards')
               ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
      }
class Rewards extends Model {
    public function proj() {
        return $this->belongsTo('App\Projects');
    }
}
</code>```

Controller api class

```<code>Route::get('projects/{id}', function($id) {
$p = Projects::find($id);
$getd = Rewards::with('proj')
    ->where('rewards.project_id', '=', $p->id)
    ->get();
 });
</code>```

it doesn't work.
i search and tried many related model base query in larvel.
i know my implementation are wrong. Please suggest me to work out.

答:
```<code>class Project extends Model
{
    public function rewds()
    {
        return $this->hasMany('App\Rewards');
    }

    public function shiplc()
    {
        return $this->hasManyThrough('App\Shipping', 'App\Rewards');
    }
}

class Rewards extends Model
{
    public function shiplc()
    {
        return $this->belongsToMany('App\Shipping');

    }

    public function projs()
    {
        return $this->belongsTo('App\Project');
    }

}

class Shipping extends Model
{
    public function shiplc()
    {
        return $this->belongsToMany('App\Shipping');

    }
}

Route::get('projects/{id}', function($id) {
    $p = Projects::with(['rewds', 'shiplc'])->find($id);
});
</code>```

Body:
i have this table structure, project has one to many relation with rewards , rewards and shipping has many to many relation with pivot table reward_ship.

projects       rewards         shipping       reward_ship
---------      --------        --------       ------------
id             id              id             id
title          amount          location       reward_id
amount         project_id      name           ship_id

i am trying to extract one particular project details with all other associate tables data(rewards and shipping data using reward_ship table) in one query.

These is how i am trying

Projects Model

    class Rewards extends Model {
         public function projs(){
              return $this->hasMany('App\Rewards');
          }
         public function rewds(){
              return $this->belongsToMany('App\Shipping')
              ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
         public function shiplc(){
               return $this->belongsToMany('App\Rewards')
               ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
      }
class Rewards extends Model {
    public function proj() {
        return $this->belongsTo('App\Projects');
    }
}

Controller api class

Route::get('projects/{id}', function($id) {
$p = Projects::find($id);
$getd = Rewards::with('proj')
    ->where('rewards.project_id', '=', $p->id)
    ->get();
 });

it doesn't work.
i search and tried many related model base query in larvel.
i know my implementation are wrong. Please suggest me to work out.