问:
How to write firestore database security rule while not use firebase authentication
I want to use the phone number and password authentication for the application. These type of authentication is not provided by firebase. So, normally create user collection and implement login signup flow.

Another thing is that I use phone number authentication for OTP send and verify. So user entry is available in the authentical list.

I get request.resource.data.userUid from request and check that this userUid exists in authentication list.

```<code>match /user/{docId} {
allow read, write: if exists(/databases/$(database)/documents/user/$(request.resource.data.userUid))
}
</code>```

Normally from any table we can check like this. But I not found any way to access authentication list.

Any way to write security rule as per my requirement or I need to change my authentication flow?

答:
If you're not using Firebase Authentication, then you can't use security rules to control access to specific users.  There is no other way to validate the identity of the individual making the request.  request.auth will always be null in this case.

In case you didn't know, Firebase Auth does provide phone number authentication.  You should be using this along with Cloud Firestore to implement security rules effectively.

Body:
I want to use the phone number and password authentication for the application. These type of authentication is not provided by firebase. So, normally create user collection and implement login signup flow.

Another thing is that I use phone number authentication for OTP send and verify. So user entry is available in the authentical list.

I get request.resource.data.userUid from request and check that this userUid exists in authentication list.

match /user/{docId} {
allow read, write: if exists(/databases/$(database)/documents/user/$(request.resource.data.userUid))
}

Normally from any table we can check like this. But I not found any way to access authentication list.

Any way to write security rule as per my requirement or I need to change my authentication flow?


来源: stackexchange

问:
Given several Option<'a> values, is there a well-known pattern for chaining several 'a -> 'b -> 'b functions?
I have a series of functions 'arg -> 'entity -> 'entity to update an immutable entity.

I have a series of corresponding 'arg option arguments where if the argument is Some, I should call the corresponding update function.

I have currently implemented it like this:

```<code>// General utility function
// ('a -> 'b -> 'b) -> 'a option -> 'b -> 'b
let ifSome f argOpt entity =
  match argOpt with
  | Some arg -> f arg entity
  | None -> entity

// Function that accepts several option parameters
// (callbackUrl and authHeader are wrapped in option)
let updateWebhook callbackUrl authHeader webhook =
   webhook
   |> ifSome Webhook.setCallbackUrl callbackUrl
   |> ifSome Webhook.setAuthHeader authHeader
</code>```

I like how simple it is, but as is often the case with my homegrown functional solutions (particularly when the generic function is more generic than suggested by the parameter names I came up with), I get the feeling that this is just a special case of a more general functional concept - that I could use some existing abstractions to perform the same task. I therefore wonder:

Is this a recognized functional pattern? If so, does it have a name, and can I read more about it somewhere?

If not, is there a (hopefully similarly simple) alternative that accomplishes the same using "well-known" functional abstractions/patterns?

答:
This is just Option.fold (or more precisely in this case Option.foldBack). Folds are more generally known as catamorphisms.

```<code>let updateWebhook callbackUrl authHeader webhook =
   webhook
   |> Option.foldBack Webhook.setCallbackUrl callbackUrl
   |> Option.foldBack Webhook.setAuthHeader authHeader
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a series of functions 'arg -> 'entity -> 'entity to update an immutable entity.

I have a series of corresponding 'arg option arguments where if the argument is Some, I should call the corresponding update function.

I have currently implemented it like this:

// General utility function
// ('a -> 'b -> 'b) -> 'a option -> 'b -> 'b
let ifSome f argOpt entity =
  match argOpt with
  | Some arg -> f arg entity
  | None -> entity

// Function that accepts several option parameters
// (callbackUrl and authHeader are wrapped in option)
let updateWebhook callbackUrl authHeader webhook =
   webhook
   |> ifSome Webhook.setCallbackUrl callbackUrl
   |> ifSome Webhook.setAuthHeader authHeader

I like how simple it is, but as is often the case with my homegrown functional solutions (particularly when the generic function is more generic than suggested by the parameter names I came up with), I get the feeling that this is just a special case of a more general functional concept - that I could use some existing abstractions to perform the same task. I therefore wonder:

Is this a recognized functional pattern? If so, does it have a name, and can I read more about it somewhere?

If not, is there a (hopefully similarly simple) alternative that accomplishes the same using "well-known" functional abstractions/patterns?

Body:
This is just Option.fold (or more precisely in this case Option.foldBack). Folds are more generally known as catamorphisms.

let updateWebhook callbackUrl authHeader webhook =
   webhook
   |> Option.foldBack Webhook.setCallbackUrl callbackUrl
   |> Option.foldBack Webhook.setAuthHeader authHeader


问:
IE8 CSS Hack - best method?
Can anyone recommend the best way to hack IE8 styling via CSS, I've recently been making IE8 render as IE7 for ease -  but wondered if it was best to add IE8 hacks?</p>

答:
You should reverse your method. First your site should look good in modern browsers (like Firefox, Chrome, Opera, IE 9), and then you can start worrying about the others.

As others suggested, conditional comments can be your friend.

First, you should develop your CSS to look fine in the modern browsers. Then check IE8, see what problems you get. If you need to, include an IE-specific stylesheet. After that, you can check in IE7 and then IE6 if you support it, and add further fixes.

An example:

```<code><link rel="stylesheet" href="normal.css" type="text/css" />
<!--[if lt IE 9]><link rel="stylesheet" type="text/css" href="ie8.css"><![endif]-->
<!--[if lt IE 8]><link rel="stylesheet" type="text/css" href="ie7.css"><![endif]-->
</code>```

In this case you include normal.css which is for modern browsers. You found some strange IE8 issues, so in ie8.css you fix the problems. You don't have to include all your selectors in this, only the ones that need a fix (the values will be overridden for IE 8 and lower). After that, if there are still some strange things in IE7, you can add your ie7.css and fix those, and so on.

Please refer to the links the others gave you to get more information on the usage of conditional comments.

Finally: making IE8 render as IE7 for ease is never a good idea, and should be avoided. IE7 is the far past (in the IT world, IE8 should be the far past either...), develop for the present and the future, and after that you can care about the people who are still stuck with old technology (based on your audience and business plan).

Title: IE8 CSS Hack - best method?

Body:
You should reverse your method. First your site should look good in modern browsers (like Firefox, Chrome, Opera, IE 9), and then you can start worrying about the others.

As others suggested, conditional comments can be your friend.

First, you should develop your CSS to look fine in the modern browsers. Then check IE8, see what problems you get. If you need to, include an IE-specific stylesheet. After that, you can check in IE7 and then IE6 if you support it, and add further fixes.

An example:

<link rel="stylesheet" href="normal.css" type="text/css" />
<!--[if lt IE 9]><link rel="stylesheet" type="text/css" href="ie8.css"><![endif]-->
<!--[if lt IE 8]><link rel="stylesheet" type="text/css" href="ie7.css"><![endif]-->

In this case you include normal.css which is for modern browsers. You found some strange IE8 issues, so in ie8.css you fix the problems. You don't have to include all your selectors in this, only the ones that need a fix (the values will be overridden for IE 8 and lower). After that, if there are still some strange things in IE7, you can add your ie7.css and fix those, and so on.

Please refer to the links the others gave you to get more information on the usage of conditional comments.

Finally: making IE8 render as IE7 for ease is never a good idea, and should be avoided. IE7 is the far past (in the IT world, IE8 should be the far past either...), develop for the present and the future, and after that you can care about the people who are still stuck with old technology (based on your audience and business plan).

ContentLicense: CC BY-SA 3.0


问:
ag-grid cellRendererFramework not work in angular
I'm trying to add a simple component in ag-grid table cell . I flow the instructions in aggrid website but it dos'nt render the component . here is my code :

```<code>  columnDefs = [
{ headerName: "Name", field: "name" ,width: 400},
{ headerName: "GoodsFinalCode", field: "goodsFinalCode" ,width:  200},
{ headerName: "operation", field: "operation" ,cellRendererFramework: OperationComponent, width: 450}
];

rowData  = [ {
      name : 'b',
      goodsFinalCode :6,
 }
 ]
</code>```

the gridoptiopns is :

```<code>  this.gridOptions = <GridOptions>{
  rowData: this.rowData,
  columnDefs: this.columnDefs,
  context: {
      componentParent: this
  },
  enableColResize: true
</code>```

};

and the componet is :

```<code>        import { Component } from '@angular/core';

        @Component({
        selector: 'app-operation',
        templateUrl: './operation.component.html',
        styleUrls: ['./operation.component.scss']
        })

     export class OperationComponent  {

     private params: any;

    agInit(params: any): void {
    this.params = params;
   }
   }
</code>```

in operation html I just have a button. but nothing appear in aggrid cell.

答:
The component you are using as the cell renderer should implement the ICellRendererAngularComp given from ag-grid.

operation.component.ts

```<code>import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';

@Component({
  selector: 'app-operation',
  templateUrl: './operation.component.html',
  styleUrls: ['./operation.component.css']
})
export class OperationComponent implements ICellRendererAngularComp {
  private params: any;

  agInit(params: any): void {
    this.params = params;
  }

  refresh(): boolean {
    return false;
  }

  constructor() { }

}
</code>```

Then you must tell aggrid to use this operation component as a custom component. It is done by providing them in the AgGridModule.

```<code>import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AgGridModule } from 'ag-grid-angular';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { OperationComponent } from './grid/options-cell-renderer/options-cell-renderer.component';

@NgModule({
  declarations: [
    AppComponent,
    OperationComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    CommonModule,
    NgbModule,
    HttpClientModule,
    AgGridModule.withComponents([
      OperationComponent
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
I'm trying to add a simple component in ag-grid table cell . I flow the instructions in aggrid website but it dos'nt render the component . here is my code :

  columnDefs = [
{ headerName: "Name", field: "name" ,width: 400},
{ headerName: "GoodsFinalCode", field: "goodsFinalCode" ,width:  200},
{ headerName: "operation", field: "operation" ,cellRendererFramework: OperationComponent, width: 450}
];

rowData  = [ {
      name : 'b',
      goodsFinalCode :6,
 }
 ]

the gridoptiopns is :

  this.gridOptions = <GridOptions>{
  rowData: this.rowData,
  columnDefs: this.columnDefs,
  context: {
      componentParent: this
  },
  enableColResize: true

};

and the componet is :

        import { Component } from '@angular/core';

        @Component({
        selector: 'app-operation',
        templateUrl: './operation.component.html',
        styleUrls: ['./operation.component.scss']
        })

     export class OperationComponent  {

     private params: any;

    agInit(params: any): void {
    this.params = params;
   }
   }

in operation html I just have a button. but nothing appear in aggrid cell.

Body:
The component you are using as the cell renderer should implement the ICellRendererAngularComp given from ag-grid.

operation.component.ts

import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';

@Component({
  selector: 'app-operation',
  templateUrl: './operation.component.html',
  styleUrls: ['./operation.component.css']
})
export class OperationComponent implements ICellRendererAngularComp {
  private params: any;

  agInit(params: any): void {
    this.params = params;
  }

  refresh(): boolean {
    return false;
  }

  constructor() { }

}

Then you must tell aggrid to use this operation component as a custom component. It is done by providing them in the AgGridModule.

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AgGridModule } from 'ag-grid-angular';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { OperationComponent } from './grid/options-cell-renderer/options-cell-renderer.component';

@NgModule({
  declarations: [
    AppComponent,
    OperationComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    CommonModule,
    NgbModule,
    HttpClientModule,
    AgGridModule.withComponents([
      OperationComponent
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Transfer value from separated components in Angular
I have 2 components. Component A and B. Component B has a value that I am trying to rereive in component A. Component B lies in a different folder to A. How can I send the value to A without using something like localStorage.

Here is my code for context.

Compononent B

```<code>@Input() offerExpiry: any;

  async ngOnInit() {
    this._loader.start();
    if (this._exploreService.offer) {
        ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      //value I need is 'this.offerExpiry'
      this.offerExpiry = offer.expiryDate;
    }
    this._loader.stop();
  }
</code>```

Compononent A

```<code>import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-offer-subheader',
  templateUrl: './offer-subheader.component.html',
  styleUrls: ['./offer-subheader.component.scss']
})
export class OfferSubheaderComponent {

  @Input() title: string;
  @Input() active: string;
  @Output() back = new EventEmitter();
  @Output() offerExpiry: any;

  onBack() {
    this.back.emit();
  }

}
</code>```

I am trying to use Input, Output but am not having any success

答:
You can solve it in 2 ways:

You need create more one Parent component or using your app
component, component B has @Output() and component A @Input(). You
subscribe to component B @Output changes and set value to Parent
component, and pass it on input of your component A.

Create a service like this:

export class ExchangeService {
      private value$: BehaviorSubject = new BehaviorSubject(1);

```<code>  get value() {
    return this.value$.asObservable();
  }

  updateValue(value: number) {
    this.value$.next(value);
  }
}
</code>```

And inject it in both your components and enjoy your data managing)

Body:
I have 2 components. Component A and B. Component B has a value that I am trying to rereive in component A. Component B lies in a different folder to A. How can I send the value to A without using something like localStorage.

Here is my code for context.

Compononent B

@Input() offerExpiry: any;

  async ngOnInit() {
    this._loader.start();
    if (this._exploreService.offer) {
        ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      //value I need is 'this.offerExpiry'
      this.offerExpiry = offer.expiryDate;
    }
    this._loader.stop();
  }

Compononent A

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-offer-subheader',
  templateUrl: './offer-subheader.component.html',
  styleUrls: ['./offer-subheader.component.scss']
})
export class OfferSubheaderComponent {

  @Input() title: string;
  @Input() active: string;
  @Output() back = new EventEmitter();
  @Output() offerExpiry: any;

  onBack() {
    this.back.emit();
  }

}

I am trying to use Input, Output but am not having any success

Body:
You can solve it in 2 ways:

You need create more one Parent component or using your app
component, component B has @Output() and component A @Input(). You
subscribe to component B @Output changes and set value to Parent
component, and pass it on input of your component A.

Create a service like this:

export class ExchangeService {
      private value$: BehaviorSubject = new BehaviorSubject(1);

  get value() {
    return this.value$.asObservable();
  }

  updateValue(value: number) {
    this.value$.next(value);
  }
}

And inject it in both your components and enjoy your data managing)


问:
return last word in a file that starts with capital letter
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "
</code>```

but this isn't working.

I also tried this:

```<code>    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "
</code>```

Any help?

答:
```<code>def find_last_capitalised(file_name):
with open(file_name) as wordfile:
    text_str = wordfile.read()
    word_list = text_str.split(" ")
    upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for word in reversed(word_list):
        if upper.rfind(word[0]) >= 0:
        return word
    return " "
</code>```

Please try with the above code ... If its not working let me know here.

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?

Body:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
    text_str = wordfile.read()
    word_list = text_str.split(" ")
    upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for word in reversed(word_list):
        if upper.rfind(word[0]) >= 0:
        return word
    return " "

Please try with the above code ... If its not working let me know here.


问:
How to get the IP Address for Azure DevOps Hosted Agents to add to the white list
Is there a way to the IP address range for the hosted machine running?

This is related to the Release Pipeline -> Hosted agent.

Issue: Getting access denied on connection, as the connection is getting refused via Firewall. Need to whitelist the IP address range for this request coming from release pipeline on DevOps.

答: Check out this add on for Azure DevOps (https://marketplace.visualstudio.com/items?itemName=MartijnQuekel.AzureAppServiceIPRestrictions). It allows you to alter your App Service IP restrictions during the build pipeline.</p>


问:
Rewriting java if statements in clojure syntax
I have a set of recursive if statements written in Java and I tried taking it to clojure syntax but got the ArrayOutOfBound error. The functions accepts row = 0, col = 0 and a multidimensional array of characters.

This is the Java Code:

```<code>public static boolean solveMaze(int r, int c, char[][] maze) {

    //check for boundaries
    if(r < 0 || c < 0 || r >= maze.length || c >= maze[0].length)
        return false;
    //base case, did i reach the finish?
    if(maze[r][c] == '@')
        return true;
    //check if I'm at a valid point
    if(maze[r][c] != '-')
    //I have hit a wall, not a valid solution
        return false;
    //must be on a path, may be the right path
    //leave a bread crumb
    maze[r][c] = '!';
    //check above
    if(solveMaze(r-1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check below
    if(solveMaze(r+1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check left
    if(solveMaze(r,c-1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check right
    if(solveMaze(r,c+1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //if I reach this point...
    return false;
}
</code>```

This is my code in clojure that provides the Index out of bound error:

```<code>    (defn solveMaze [r c m]
    (def tt true)
    ;(def che false)

    ;check to verify boundaries
    (if (or (or (or (< r 0) (< c 0)) (>= r (count m))) (>= c (count (str (m 0)))))
        false
        true
    )
    ;Check to know if the @ symbol has been found
    (if (= (get-in m[r c]) "@")
        true
        false
    )
    ;Checking if current index is a valid one
    (if (not= (get-in m[r c]) "-")
        ;Wall hit
        false
        true
    )
    ;found a path, leave a breadcrumb
    (def temp_map (assoc-in m[r c] "!"))
    ;Check North
    (if (= (solveMaze (dec r) c m) true)
        (def temp_map (assoc-in m [r c] "+"))
        true
        ;false
    )
    ;Check South
    (if (= (solveMaze (inc r) c m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check East
    (if (= (solveMaze r (dec c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check West
    (if (= (solveMaze r (inc c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;If code gets here
    (= tt false)
</code>```

)

Please is there something I am doing wrongly??? I have tried several if constructs using clojure but it doesn't work.

答:
You need to read up on the basics of Clojure:

Brave Clojure (online & book)

Getting Clojure book

Clojure CheatSheet book

Body:
I have a set of recursive if statements written in Java and I tried taking it to clojure syntax but got the ArrayOutOfBound error. The functions accepts row = 0, col = 0 and a multidimensional array of characters.

This is the Java Code:

public static boolean solveMaze(int r, int c, char[][] maze) {

    //check for boundaries
    if(r < 0 || c < 0 || r >= maze.length || c >= maze[0].length)
        return false;
    //base case, did i reach the finish?
    if(maze[r][c] == '@')
        return true;
    //check if I'm at a valid point
    if(maze[r][c] != '-')
    //I have hit a wall, not a valid solution
        return false;
    //must be on a path, may be the right path
    //leave a bread crumb
    maze[r][c] = '!';
    //check above
    if(solveMaze(r-1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check below
    if(solveMaze(r+1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check left
    if(solveMaze(r,c-1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check right
    if(solveMaze(r,c+1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //if I reach this point...
    return false;
}

This is my code in clojure that provides the Index out of bound error:

    (defn solveMaze [r c m]
    (def tt true)
    ;(def che false)

    ;check to verify boundaries
    (if (or (or (or (< r 0) (< c 0)) (>= r (count m))) (>= c (count (str (m 0)))))
        false
        true
    )
    ;Check to know if the @ symbol has been found
    (if (= (get-in m[r c]) "@")
        true
        false
    )
    ;Checking if current index is a valid one
    (if (not= (get-in m[r c]) "-")
        ;Wall hit
        false
        true
    )
    ;found a path, leave a breadcrumb
    (def temp_map (assoc-in m[r c] "!"))
    ;Check North
    (if (= (solveMaze (dec r) c m) true)
        (def temp_map (assoc-in m [r c] "+"))
        true
        ;false
    )
    ;Check South
    (if (= (solveMaze (inc r) c m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check East
    (if (= (solveMaze r (dec c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check West
    (if (= (solveMaze r (inc c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;If code gets here
    (= tt false)

)

Please is there something I am doing wrongly??? I have tried several if constructs using clojure but it doesn't work.


问:
Map array values to collection of items
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

```<code>$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];
</code>```

The collection :

```<code> $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);
</code>```

The end result :

```<code>$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];
</code>```

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

答:
Use intersectByKeys to filter your baseMap keys with $items values.

```<code>$result = $items->map(function($item,$key) use ($baseMap){
    return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});

dd($result);
</code>```

Update:

In a pure collection way,

```<code>$baseMapCollect = collect($baseMap);

$result = $items->map(function($item,$key) use ($baseMapCollect){
    return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});

dd($result);
</code>```

Title: Map array values to collection of items

Body:
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];

The collection :

 $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);

The end result :

$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

Body:
Use intersectByKeys to filter your baseMap keys with $items values.

$result = $items->map(function($item,$key) use ($baseMap){
    return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});

dd($result);

Update:

In a pure collection way,

$baseMapCollect = collect($baseMap);

$result = $items->map(function($item,$key) use ($baseMapCollect){
    return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});

dd($result);


问:
django complex postgres query parsing
The user in my frontend can submit an arbitrary nested query string on the id of my model like so

querystring="(driver = 1 AND routes = 3) OR ( driver = 2 AND weather = 1 )"
```

<p>I want to use djangos complex Q function to query this string in the backend, meaning I need to turn <em>querystring</em> into something like </p>

<pre class="lang-py prettyprint-override"><code>criterion = \
(Q(detail__drivers=1) & Q(routes =3) ) | (Q(detail__driver=2) & Q(detail__weather=1) )
</code>```

in order to be able to filter using

```<code>self.queryset.filter(criterion)
</code>```

But how can I automatically translate the string into the criterion while maintaining the parentheses structure?

答:
Try this one:</p>

```<code>self.queryset.filter(Q(detail__drivers=1, routes =3) |(Q(detail__driver=2, detail__weather=1))
</code>```

Title: django complex postgres query parsing

Body:
The user in my frontend can submit an arbitrary nested query string on the id of my model like so

querystring="(driver = 1 AND routes = 3) OR ( driver = 2 AND weather = 1 )"

I want to use djangos complex Q function to query this string in the backend, meaning I need to turn querystring into something like

criterion = \
(Q(detail__drivers=1) & Q(routes =3) ) | (Q(detail__driver=2) & Q(detail__weather=1) )

in order to be able to filter using

self.queryset.filter(criterion)

But how can I automatically translate the string into the criterion while maintaining the parentheses structure?

Body:
Try this one:

self.queryset.filter(Q(detail__drivers=1, routes =3) |(Q(detail__driver=2, detail__weather=1))


问:
URL Encoding is breaking routing in ExtJS
If a user copies a url from my website like:

www.mysite.com/#tag/Sometagtext%20(Sometagtext2)|card/somecardname/21

and posts it on another website, that other website encodes the string to:

www.mysite.com/#tag/Sometext%20%28Sometext2%29%7Ccard/somecardname/21

When this new URL is used, the encoding is not being handled properly by ExtJS and the website is breaking.

I checked the tag value in onBeforeTagChange within MainController.js (see code) and it includes the card:

sometagtext%20%28Sometagtext2%29%7Ccard/somecardname/21

sometagtext (Sometagtext2)|card/somecardname/21 )

So, at the very least, the encoding of the multiple route delimiter from | to %7C is breaking the site since it can't parse the tags from the cards.

Where and how would I go about updating the router so that it decodes the URL before parsing it?

I'm using ExtJS 6.0.2.437

Here is my code:

```<code>Ext.define('APP.view.main.MainController', {
    extend: 'Ext.app.ViewController',

    alias: 'controller.main',

    routes: {
        'card/:card/:collection_id': {
            action: 'cardChange',
            before: 'beforeCardChange',
            conditions: {
                ':collection_id': '([0-9]+)'
            }
        },
        'card/:card': {
            action: 'cardChange',
            before: 'beforeCardChangeBase'

        },
        'tag/:tag': {
            action: 'onTagChange',
            before: 'onBeforeTagChange',
            conditions: {
                ':tag': '([%a-zA-Z0-9\.\\-\\_\\s,\(\)\/]+)'
            }
        }
    },
    onTagChange: function (tag) {

    },
    onBeforeTagChange: function (tag, action) {
        console.log(tag);
        tag = decodeURI(tag);
        console.log(tag);
    },
    /*  ...
        ...
        ...
    */
});
</code>```

答: use decodeURI() before callback

Body:
If a user copies a url from my website like:

www.mysite.com/#tag/Sometagtext%20(Sometagtext2)|card/somecardname/21

and posts it on another website, that other website encodes the string to:

www.mysite.com/#tag/Sometext%20%28Sometext2%29%7Ccard/somecardname/21

When this new URL is used, the encoding is not being handled properly by ExtJS and the website is breaking.

I checked the tag value in onBeforeTagChange within MainController.js (see code) and it includes the card:

sometagtext%20%28Sometagtext2%29%7Ccard/somecardname/21

sometagtext (Sometagtext2)|card/somecardname/21 )

So, at the very least, the encoding of the multiple route delimiter from | to %7C is breaking the site since it can't parse the tags from the cards.

Where and how would I go about updating the router so that it decodes the URL before parsing it?

I'm using ExtJS 6.0.2.437

Here is my code:

Ext.define('APP.view.main.MainController', {
    extend: 'Ext.app.ViewController',

    alias: 'controller.main',

    routes: {
        'card/:card/:collection_id': {
            action: 'cardChange',
            before: 'beforeCardChange',
            conditions: {
                ':collection_id': '([0-9]+)'
            }
        },
        'card/:card': {
            action: 'cardChange',
            before: 'beforeCardChangeBase'

        },
        'tag/:tag': {
            action: 'onTagChange',
            before: 'onBeforeTagChange',
            conditions: {
                ':tag': '([%a-zA-Z0-9\.\\-\\_\\s,\(\)\/]+)'
            }
        }
    },
    onTagChange: function (tag) {

    },
    onBeforeTagChange: function (tag, action) {
        console.log(tag);
        tag = decodeURI(tag);
        console.log(tag);
    },
    /*  ...
        ...
        ...
    */
});

Body: use decodeURI() before callback


问:
Is Geomesa indexes are reliable and remain in sync with main table?
To create indexes, Geomesa creates multiple tables in HBase. I have a few questions:

What Geomesa does to ensure these tables are in sync?

What will be the impact on Geomesa query, if the index tables are not in sync?

What happens (with write calls) if Geomesa is not able to write one of the index tables?

Synchronization between tables are the best effort or Geomesa ensure the availability of data with eventual consistency?

I am planning to use Geomesa with Hbase (backed by S3) combination to store my geospatial data; the data size can grow up to Terabytes to Petabytes.

I am investigating how reliable Geomesa is in terms of synchronization between the primary and index table?

HBase Tables:

catalog1

catalog1_node_id_v4 (Main Table)

catalog1_node_z2_geom_v5  (Index Table)

catalog1_node_z3_geom_lastUpdateTime_v6  (Index Table)

catalog1_node_attr_identifier_geom_lastUpdateTime_v8   (Index Table)

Geomesa Schema

geomesa-hbase describe-schema -c catalog1 -f node

INFO  Describing attributes of feature 'node'

key            | String

 namespace      | String

 identifier     | String  (Attribute indexed)

 versionId      | String

 nodeId         | String

 latitude       | Integer
 longitude      | Integer
 lastUpdateTime | Date    (Spatio-temporally indexed)

 tags           | Map

 geom           | Point   (Spatio-temporally indexed) (Spatially indexed)

User data:
  geomesa.index.dtg | lastUpdateTime

  geomesa.indices   | z3:6:3:geom:lastUpdateTime,z2:5:3:geom,id:4:3:,attr:8:3:identifier:geom:lastUpdateTime

答:
GeoMesa does not do anything to sync indices - generally this should be taken care of in your ingest pipeline.

If you have a reliable feature ID tied to a given input feature, then you can write that feature multiple times without causing duplicates. During ingest, if a batch of features fails due to a transient issue, then you can just re-write them to ensure that the indices are correct.

For HBase, when you call flush or close on a feature writer, the pending mutations will be sent to the cluster. Once that method returns successfully, then the data has been persisted to HBase. If an exception is thrown, you should re-try the failed features.  If there are subsequent HBase failures, you may need to recover write-ahead logs (WALs) as per standard HBase operation.

A feature may also fail to be written due to validation (e.g. a null geometry). In this case, you would not want to re-try the feature as it will never ingest successfully. If you are using the GeoMesa converter framework, you can pre-validate features to ensure that they will ingest ok.

If you do not have an ingest pipeline already, you may want to check out geomesa-nifi, which will let you convert and validate input data, and re-try failures automatically through Nifi flows.


问:
How can I create a cylinder linking two points with Python withour using blender's bpy?
I want to position a cylinder such that the center of one end is at (x0, y0, z0) and the center of the other end is at (x1, y1, z1) using the pure Python API.

I want to attain this using Python OpenGL or any other GL libs but not blender lib

My Problem

I searched in stackoverflow and found this question

https://blender.stackexchange.com/questions/5898/how-can-i-create-a-cylinder-linking-two-points-with-python

```<code>But it is using blender and I don't want it
</code>```

I need to run the python script from command line or pycharm ide

So bpy module can't work outside blender

I want a function like this format

```<code>cylinder_between(x1, y1, z1, x2, y2, z2, rad):
</code>```

The function have to display a cylinder

Please guide me

2) also suggest how to clear the screen fully after drawing the
  cylinder

答:
If you want to use modern OpenGL then you've to generate a Vertex Array Object and to write a Shader.

A solution with less lines of code is to use Legacy OpenGL and either gluCylinder or glutSolidCylinder.

With this (deprecated) tool set a cylinder with few lines of code can be drawn e.g.:

from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import math

def cross(a, b):
    return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]

def cylinder_between(x1, y1, z1, x2, y2, z2, rad):
    v = [x2-x1, y2-y1, z2-z1]
    height = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
    axis = (1, 0, 0) if math.hypot(v[0], v[1]) < 0.001 else cross(v, (0, 0, 1))
    angle = -math.atan2(math.hypot(v[0], v[1]), v[2])*180/math.pi

    glPushMatrix()
    glTranslate(x1, y1, z1)
    glRotate(angle, *axis)
    glutSolidCylinder(rad, height, 32, 16)
    glPopMatrix()

def draw():

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, wnd_w/wnd_h, 0.1, 10)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    gluLookAt(0, -2, 0, 0, 0, 0, 0, 0, 1)

    glClearColor(0.5, 0.5, 0.5, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # glEnable(GL_DEPTH_TEST)
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # causes wire frame
    glColor(1, 1, 0.5)
    cylinder_between(0.2, 0.4, -0.5, -0.2, -0.4, 0.5, 0.3)

    glutSwapBuffers()
    glutPostRedisplay()

wnd_w, wnd_h = 300, 300
glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(wnd_w, wnd_h)
glutInitWindowPosition(50, 50)
glutCreateWindow("cylinder")
glutDisplayFunc(draw)
glutMainLoop()
```

See also Immediate mode and legacy OpenGL

Is there any way to implement manually do pan , rotate , tilt ,move the viewport like we do in 3D modeling software using mouse (that alt+mmb )

See:

How to implement camera pan like in 3dsMax?

Proper way to handle camera rotations

How to implement zoom towards mouse like in 3dsMax?

Body:
I want to position a cylinder such that the center of one end is at (x0, y0, z0) and the center of the other end is at (x1, y1, z1) using the pure Python API.

I want to attain this using Python OpenGL or any other GL libs but not blender lib

My Problem

I searched in stackoverflow and found this question

https://blender.stackexchange.com/questions/5898/how-can-i-create-a-cylinder-linking-two-points-with-python

But it is using blender and I don't want it

I need to run the python script from command line or pycharm ide

So bpy module can't work outside blender

I want a function like this format

cylinder_between(x1, y1, z1, x2, y2, z2, rad):

The function have to display a cylinder

Please guide me

2) also suggest how to clear the screen fully after drawing the
  cylinder

Body:
If you want to use modern OpenGL then you've to generate a Vertex Array Object and to write a Shader.

A solution with less lines of code is to use Legacy OpenGL and either gluCylinder or glutSolidCylinder.

With this (deprecated) tool set a cylinder with few lines of code can be drawn e.g.:

from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import math

def cross(a, b):
    return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]

def cylinder_between(x1, y1, z1, x2, y2, z2, rad):
    v = [x2-x1, y2-y1, z2-z1]
    height = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
    axis = (1, 0, 0) if math.hypot(v[0], v[1]) < 0.001 else cross(v, (0, 0, 1))
    angle = -math.atan2(math.hypot(v[0], v[1]), v[2])*180/math.pi

    glPushMatrix()
    glTranslate(x1, y1, z1)
    glRotate(angle, *axis)
    glutSolidCylinder(rad, height, 32, 16)
    glPopMatrix()

def draw():

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, wnd_w/wnd_h, 0.1, 10)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    gluLookAt(0, -2, 0, 0, 0, 0, 0, 0, 1)

    glClearColor(0.5, 0.5, 0.5, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # glEnable(GL_DEPTH_TEST)
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # causes wire frame
    glColor(1, 1, 0.5)
    cylinder_between(0.2, 0.4, -0.5, -0.2, -0.4, 0.5, 0.3)

    glutSwapBuffers()
    glutPostRedisplay()

wnd_w, wnd_h = 300, 300
glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(wnd_w, wnd_h)
glutInitWindowPosition(50, 50)
glutCreateWindow("cylinder")
glutDisplayFunc(draw)
glutMainLoop()

See also Immediate mode and legacy OpenGL

Is there any way to implement manually do pan , rotate , tilt ,move the viewport like we do in 3D modeling software using mouse (that alt+mmb )

See:

How to implement camera pan like in 3dsMax?

Proper way to handle camera rotations

How to implement zoom towards mouse like in 3dsMax?


问:
How do I translate this maximization problem inside an equation to R?
fellow programmers. I'm studying a book on numerical solutions for economics (Judd 1998). I'm trying to reproduce a problem from that same book in R so I can use the optim package to see if I can get similar results.

The problem established by the author is this one: and his results were these.

I have tried to transcribe this problem to R, which resulted in this code chunk:

DisutilityJudd <- function(L){
  if(L == 0){
    return(0)
  }else{
    return(0.1)
  }
}

AgentUtilityJudd <- function(w, L){
  (-exp(-2*w) + 1) - DisutilityJudd(L)
}

reservation.utility.judd <- AgentUtilityJudd(1, 1)

MaxEffortUtility <- function(w1, w2, L = 1){
  0.8 * AgentUtilityJudd(w1, L) + 0.2 * AgentUtilityJudd(w2, L)
}

LeastEffortUtility <- function(w1, w2, L = 0){
  0.4 * AgentUtilityJudd(w1, L) + 0.6 * AgentUtilityJudd(w2, L)
}

UtilityDifferenceJudd <- function(w1, w2){
  MaxEffortUtility(w1, w2) - LeastEffortUtility(w1, w2)
}

PenaltyFunctionJudd <- function(w1, w2, P = 100000){
  if(length(w1) == 2){
    y <- -1 *  (0.8 * (2 - w1[1]) - 0.2 * w1[2] - P *
                  (pmax(0, -MaxEffortUtility(w1[1], w1[1]) - reservation.utility.judd))^2 -
                  P * (pmax(0, -UtilityDifferenceJudd(w1[1], w1[1])))^2)
  }else{
    y <- -1 * (0.8 * (2 - w1) - 0.2 * w2 - P *
                 (pmax(0, -MaxEffortUtility(w1, w2) - reservation.utility.judd))^2 -
                 P * (pmax(0, -UtilityDifferenceJudd(w1, w2)))^2)
  }
  return(y)
}
```

<p>There were no errors, but the results generated by my code were nowhere near to what I was expecting: </p>

```optim(c(1.1, 0.5), PenaltyFunctionJudd)
$par
[1]  1.343909e+49 -2.370681e+51

$value
[1] -4.633849e+50

$counts
function gradient
     501       NA

$convergence
[1] 1

$message
NULL
```

Perhaps there is a problem to my penalty function. I'm assuming that it is due to the pmax function. Could somebody help me identify it? Thank you, I appreciate your attention.

Edit: a typo.

答:
I believe you meant w1[2] in when if(length(w1) == 2) is true.

I have modified your code, without touching how you define the previous function. It is not clear if it the result expected : what does IV(-1) mean, is it the result minus 1 ? a power if 10 ?

```<code>PenaltyFunctionJudd <- function(w1, w2, P = 1e5){

        if(length(w1) > 1){
                w2 <- w1[2]
                w1 <- w1[1]
        }
        # cat("length is 2 \n")

        y <- 0.8 * (2 - w1) - 0.2 * w2 - P *
                ( pmax(0, -MaxEffortUtility(w1, w2) - reservation.utility.judd) )^2 -
                P * ( pmax(0, -UtilityDifferenceJudd(w1, w2)) )^2

        # cat("pmax1 :", pmax(0, -MaxEffortUtility(w1, w2) - reservation.utility.judd), "\n")
        # cat("pmax2 :", pmax(0, -UtilityDifferenceJudd(w1, w2)), "\n")

        return(y)
}

optim(c(1.1, 0.5), PenaltyFunctionJudd, control = list(fnscale = -1) )
optim(c(11, 5), PenaltyFunctionJudd, method = "BFGS", control = list(fnscale = -1, maxit = 100) )
</code>```

You can use cat or print to check your values (here I noticed some Inf and 0 the leaded me to notice code error).

Friendly warning : provided you defined correctly the previous function, there is lot of instability in optimisation (problem badly set ? More penalty needed ?). Indeed when running twice or more the algorithm parameters fluctuate a lot...

Body:
fellow programmers. I'm studying a book on numerical solutions for economics (Judd 1998). I'm trying to reproduce a problem from that same book in R so I can use the optim package to see if I can get similar results.

The problem established by the author is this one: and his results were these.

I have tried to transcribe this problem to R, which resulted in this code chunk:

DisutilityJudd <- function(L){
  if(L == 0){
    return(0)
  }else{
    return(0.1)
  }
}

AgentUtilityJudd <- function(w, L){
  (-exp(-2*w) + 1) - DisutilityJudd(L)
}

reservation.utility.judd <- AgentUtilityJudd(1, 1)

MaxEffortUtility <- function(w1, w2, L = 1){
  0.8 * AgentUtilityJudd(w1, L) + 0.2 * AgentUtilityJudd(w2, L)
}

LeastEffortUtility <- function(w1, w2, L = 0){
  0.4 * AgentUtilityJudd(w1, L) + 0.6 * AgentUtilityJudd(w2, L)
}

UtilityDifferenceJudd <- function(w1, w2){
  MaxEffortUtility(w1, w2) - LeastEffortUtility(w1, w2)
}

PenaltyFunctionJudd <- function(w1, w2, P = 100000){
  if(length(w1) == 2){
    y <- -1 *  (0.8 * (2 - w1[1]) - 0.2 * w1[2] - P *
                  (pmax(0, -MaxEffortUtility(w1[1], w1[1]) - reservation.utility.judd))^2 -
                  P * (pmax(0, -UtilityDifferenceJudd(w1[1], w1[1])))^2)
  }else{
    y <- -1 * (0.8 * (2 - w1) - 0.2 * w2 - P *
                 (pmax(0, -MaxEffortUtility(w1, w2) - reservation.utility.judd))^2 -
                 P * (pmax(0, -UtilityDifferenceJudd(w1, w2)))^2)
  }
  return(y)
}

There were no errors, but the results generated by my code were nowhere near to what I was expecting:

optim(c(1.1, 0.5), PenaltyFunctionJudd)
$par
[1]  1.343909e+49 -2.370681e+51

$value
[1] -4.633849e+50

$counts
function gradient
     501       NA

$convergence
[1] 1

$message
NULL

Perhaps there is a problem to my penalty function. I'm assuming that it is due to the pmax function. Could somebody help me identify it? Thank you, I appreciate your attention.

Edit: a typo.

Body:
I believe you meant w1[2] in when if(length(w1) == 2) is true.

I have modified your code, without touching how you define the previous function. It is not clear if it the result expected : what does IV(-1) mean, is it the result minus 1 ? a power if 10 ?

PenaltyFunctionJudd <- function(w1, w2, P = 1e5){

        if(length(w1) > 1){
                w2 <- w1[2]
                w1 <- w1[1]
        }
        # cat("length is 2 \n")

        y <- 0.8 * (2 - w1) - 0.2 * w2 - P *
                ( pmax(0, -MaxEffortUtility(w1, w2) - reservation.utility.judd) )^2 -
                P * ( pmax(0, -UtilityDifferenceJudd(w1, w2)) )^2

        # cat("pmax1 :", pmax(0, -MaxEffortUtility(w1, w2) - reservation.utility.judd), "\n")
        # cat("pmax2 :", pmax(0, -UtilityDifferenceJudd(w1, w2)), "\n")

        return(y)
}

optim(c(1.1, 0.5), PenaltyFunctionJudd, control = list(fnscale = -1) )
optim(c(11, 5), PenaltyFunctionJudd, method = "BFGS", control = list(fnscale = -1, maxit = 100) )

You can use cat or print to check your values (here I noticed some Inf and 0 the leaded me to notice code error).

Friendly warning : provided you defined correctly the previous function, there is lot of instability in optimisation (problem badly set ? More penalty needed ?). Indeed when running twice or more the algorithm parameters fluctuate a lot...


问:
Zero an array in C code

Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

```<code>arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;
</code>```

This is the long way... I need it the short way.

答: int arr[20] = {0} would be easiest if it only needs to be done once.

Title: Zero an array in C code

Body:
Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;

This is the long way... I need it the short way.


问:
Add a volume to Docker, but exclude a sub-folder
Supposed I have a Docker container and a folder on my host /hostFolder. Now if I want to add this folder to the Docker container as a volume, then I can do this either by using ADD in the Dockerfile or mounting it as a volume.

So far, so good.

Now /hostFolder contains a sub-folder, /hostFolder/subFolder.

I want to mount /hostFolder into the Docker container (whether as read-write or read-only does not matter, works both for me), but I do NOT want to have it included /hostFolder/subFolder. I want to exclude this, and I also want the Docker container be able to make changes to this sub-folder, without the consequence of having it changed on the host as well.

Is this possible? If so, how?

答:
for the people who also had the issue that the node_modules folder would still overwrite from your local system and the other way around

```<code>volumes:
  node_modules:
services:
  server:
    volumes:
      - .:/app
      - node_modules:/app/node_modules/

</code>```

This is the solution, With the trailing / after the node_modules being the fix.

Body:
for the people who also had the issue that the node_modules folder would still overwrite from your local system and the other way around

volumes:
  node_modules:
services:
  server:
    volumes:
      - .:/app
      - node_modules:/app/node_modules/

This is the solution, With the trailing / after the node_modules being the fix.


问:
Getting keyboard size from userInfo in Swift
I have been trying to add some code to move my view up when the keyboard appears, however, I am having issues trying to translate the Objective-C examples into Swift. I have made some progress, but I am stuck on one particular line.

These are the two tutorials/questions I have been following:

How to move content of UIViewController upwards as Keypad appears using Swift
http://www.ioscreator.com/tutorials/move-view-when-keyboard-appears

Here is the code I currently have:

```<code>override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
    UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    let frame = self.budgetEntryView.frame
    frame.origin.y = frame.origin.y - keyboardSize
    self.budgetEntryView.frame = frame
}

func keyboardWillHide(notification: NSNotification) {
    //
}
</code>```

At the moment, I am getting an error on this line:

```<code>var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
</code>```

If someone could let me know what this line of code should be, I should manage to figure out the rest myself.

答:
in Swift 4.2 you can use UIResponder.keyboardFrameEndUserInfoKey

guard let userInfo = notification.userInfo , let keyboardFrame:CGRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect  else { return  }```
</code>```

Body:
I have been trying to add some code to move my view up when the keyboard appears, however, I am having issues trying to translate the Objective-C examples into Swift. I have made some progress, but I am stuck on one particular line.

These are the two tutorials/questions I have been following:

How to move content of UIViewController upwards as Keypad appears using Swift
http://www.ioscreator.com/tutorials/move-view-when-keyboard-appears

Here is the code I currently have:

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
    UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    let frame = self.budgetEntryView.frame
    frame.origin.y = frame.origin.y - keyboardSize
    self.budgetEntryView.frame = frame
}

func keyboardWillHide(notification: NSNotification) {
    //
}

At the moment, I am getting an error on this line:

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))

If someone could let me know what this line of code should be, I should manage to figure out the rest myself.


问:
Pandas time re-sampling categorical data from a column with calculations from another numerical column
I have a data-frame with a categorical column and a numerical , the index set to time data

df = pd.DataFrame({
        'date': [
            '2013-03-01 ', '2013-03-02 ',
            '2013-03-01 ', '2013-03-02',
            '2013-03-01 ', '2013-03-02 '
        ],
        'Kind': [
            'A', 'B', 'A', 'B', 'B', 'B'
        ],
        'Values': [1, 1.5, 2, 3, 5, 3]
    })

df['date'] =  pd.to_datetime(df['date'])
df = df.set_index('date')

```

<p>the above code gives:</p>

<pre class="lang-py prettyprint-override"><code>        Kind    Values
date
2013-03-01  A   1.0
2013-03-02  B   1.5
2013-03-01  A   2.0
2013-03-02  B   3.0
2013-03-01  B   5.0
2013-03-02  A   3.0
</code>```

My aim is to achieve the below data-frame:

         A_count   B_count  A_Val max   B_Val max
date
2013-03-01   2         1        2             5
2013-03-02   0         3        0             3
```

<p>Which also has the time as index . Here, I note that If we use </p>

<pre class="lang-py prettyprint-override"><code>data = pd.DataFrame(data.resample('D')['Pack'].value_counts())
</code>```

we get :

    Kind
date    Kind
2013-03-01  A   2
            B   1
2013-03-02  B   3

```

答:
Use DataFrame.pivot_table with flattening MultiIndex in columns in list comprehension:

```<code>df = pd.DataFrame({
        'date': [
            '2013-03-01 ', '2013-03-02 ',
            '2013-03-01 ', '2013-03-02',
            '2013-03-01 ', '2013-03-02 '
        ],
        'Kind': [
            'A', 'B', 'A', 'B', 'B', 'B'
        ],
        'Values': [1, 1.5, 2, 3, 5, 3]
    })

df['date'] =  pd.to_datetime(df['date'])

#is possible omit
#df = df.set_index('date')

df = df.pivot_table(index='date', columns='Kind', values='Values', aggfunc=['count','max'])
df.columns = [f'{b}_{a}' for a, b in df.columns]
print (df)
            A_count  B_count  A_max  B_max
date
2013-03-01      2.0      1.0    2.0    5.0
2013-03-02      NaN      3.0    NaN    3.0
</code>```

Another solution with Grouper for resample by days:

```<code>df = df.set_index('date')

df = df.groupby([pd.Grouper(freq='d'), 'Kind'])['Values'].agg(['count','max']).unstack()
df.columns = [f'{b}_{a}' for a, b in df.columns]
</code>```

Body:
I have a data-frame with a categorical column and a numerical , the index set to time data

df = pd.DataFrame({
        'date': [
            '2013-03-01 ', '2013-03-02 ',
            '2013-03-01 ', '2013-03-02',
            '2013-03-01 ', '2013-03-02 '
        ],
        'Kind': [
            'A', 'B', 'A', 'B', 'B', 'B'
        ],
        'Values': [1, 1.5, 2, 3, 5, 3]
    })

df['date'] =  pd.to_datetime(df['date'])
df = df.set_index('date')

the above code gives:

        Kind    Values
date
2013-03-01  A   1.0
2013-03-02  B   1.5
2013-03-01  A   2.0
2013-03-02  B   3.0
2013-03-01  B   5.0
2013-03-02  A   3.0

My aim is to achieve the below data-frame:

         A_count   B_count  A_Val max   B_Val max
date
2013-03-01   2         1        2             5
2013-03-02   0         3        0             3

Which also has the time as index . Here, I note that If we use

data = pd.DataFrame(data.resample('D')['Pack'].value_counts())

we get :

    Kind
date    Kind
2013-03-01  A   2
            B   1
2013-03-02  B   3

Body:
Use DataFrame.pivot_table with flattening MultiIndex in columns in list comprehension:

df = pd.DataFrame({
        'date': [
            '2013-03-01 ', '2013-03-02 ',
            '2013-03-01 ', '2013-03-02',
            '2013-03-01 ', '2013-03-02 '
        ],
        'Kind': [
            'A', 'B', 'A', 'B', 'B', 'B'
        ],
        'Values': [1, 1.5, 2, 3, 5, 3]
    })

df['date'] =  pd.to_datetime(df['date'])

#is possible omit
#df = df.set_index('date')

df = df.pivot_table(index='date', columns='Kind', values='Values', aggfunc=['count','max'])
df.columns = [f'{b}_{a}' for a, b in df.columns]
print (df)
            A_count  B_count  A_max  B_max
date
2013-03-01      2.0      1.0    2.0    5.0
2013-03-02      NaN      3.0    NaN    3.0

Another solution with Grouper for resample by days:

df = df.set_index('date')

df = df.groupby([pd.Grouper(freq='d'), 'Kind'])['Values'].agg(['count','max']).unstack()
df.columns = [f'{b}_{a}' for a, b in df.columns]


问:
Is there an "easy way" of adding custom UI to a Qt application when using QGraphicsView?
I'm using QGraphicsView to show randomly generated polygons in a QGraphicsScene and it's all working fine and dandy, but now I want to add custom UI styling to my application and it's proving to be quite annoying to do everything by hand, while there are so many wonderful options out there like QtQuick. It is possible at all to use QtQuick or something like it together with a graphicsView?

Quick note:
I'm new to Qt so I might be missing something obvious here!

EDIT:

Added an image for clarification, I just want to modify the sliders and buttons to have a custom texture!

答:
Use the QQuickWidget class to embed a QML view in a Qt widgets.

For example:

```<code>// main.qml
Item {
    id: main
    visible: true
    width: 200

    Column {
        ComboBox {
            model: ["Option 1", "Option 2", "Option 3"]
        }

        Slider {
        }
        Slider {
        }
        Slider {
        }
    }
}
</code>```

```<code>// main.cpp
#include <QQuickWidget>

int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    QQuickWidget *view = new QQuickWidget;
    view->setSource(QUrl(QStringLiteral("qrc:/main.qml")));

    QWidget* widget = new QWidget();
    QHBoxLayout* layout = new QHBoxLayout(widget);
    layout->addWidget(view);
    layout->addWidget(new QLabel("A classic widget"));

    widget->show();
    return app.exec();
}
</code>```

Body:
Use the QQuickWidget class to embed a QML view in a Qt widgets.

For example:

// main.qml
Item {
    id: main
    visible: true
    width: 200

    Column {
        ComboBox {
            model: ["Option 1", "Option 2", "Option 3"]
        }

        Slider {
        }
        Slider {
        }
        Slider {
        }
    }
}

// main.cpp
#include <QQuickWidget>

int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    QQuickWidget *view = new QQuickWidget;
    view->setSource(QUrl(QStringLiteral("qrc:/main.qml")));

    QWidget* widget = new QWidget();
    QHBoxLayout* layout = new QHBoxLayout(widget);
    layout->addWidget(view);
    layout->addWidget(new QLabel("A classic widget"));

    widget->show();
    return app.exec();
}


问:
Error adding a new sheet to a XLSM Macro Enabled Excel File
I want to add a new sheet in a Macro Enabled Excel File using VBA.

It doesn't matter the method that I use:

Sheets.add

Copying and pasting a sheet to create a new one

The new sheet is created (or copied) but the macro stops immediately, without any message error, and the rest of the code is not executed.

I converted the file to XLSX and when I run the code, the sheet is created and the code execution continues perfectly.

That's why I think that it is related to the Macro Enabled Excel type of file.

UPDATE:

I tested the code in another PC and Excel installation and the new sheet is created and the code goes on.

The only difference between the two computers is the Excel 2016 version:

Standard in one and Professional in the other.

答: I was experiencing the same issue, on a Windows 7 computer with Excel version 16.0.10730.20264 32-bit, the code ran fine without issue. However, on a Windows 10 computer with the same Excel install version, the macro would immediately stop execution following the Sheets.Add or Worksheets.Add line. I found that this was only happening where I was attempting to add a sheet to a workbook that contained VBA code. The issue is caused by the macro security settings on the computer. If you set Automation Security to Low before opening the workbook, you should no longer get the error: Application.AutomationSecurity = msoAutomationSecurityLow</p>


问:
ASP.net page without a code behind
I have an ASP.Net page with a C# code behind.

However, I've been asked to not use a code behind - so that it will be easier to deploy in SharePoint.

Is there a way to include the C# code in the ASP.Net page, without using a separate code behind file?

答:
By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

```<code><script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>
</code>```

OwnerDisplayName: Sophia

ContentLicense: CC BY-SA 2.5

Title: ASP.net page without a code behind

Body:
By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>

OwnerDisplayName: Rex M


问:
Android: How to create EAP wifi configuration programmatically?
I know how to create Open/WEP/PSK/PSK2 configuration programmatically.

ex.

```<code>WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "ssid";
conf.preSharedKey = "\"password\"";
conf.status = WifiConfiguration.Status.ENABLED;

conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

int res = wifi.addNetwork(conf);
boolean b = wifi.enableNetwork(res, true);
</code>```

But how do I create one for '802.1x EAP'?
Looking into the source code at:
..\packages\apps\Settings\src\com\android\settings\wifi\WifiDialog.java

```<code>case AccessPoint.SECURITY_EAP:
                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
                config.eap.setValue((String) mEapMethod.getSelectedItem());

                config.phase2.setValue((mPhase2.getSelectedItemPosition() == 0) ? "" :
                        "auth=" + mPhase2.getSelectedItem());
                config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" :
                        KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
                        (String) mEapCaCert.getSelectedItem());
                config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
                        KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
                        (String) mEapUserCert.getSelectedItem());
                config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
                        KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
                        (String) mEapUserCert.getSelectedItem());
                config.identity.setValue((mEapIdentity.length() == 0) ? "" :
                        mEapIdentity.getText().toString());
                config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" :
                        mEapAnonymous.getText().toString());
                if (mPassword.length() != 0) {
                    config.password.setValue(mPassword.getText().toString());
                }
</code>```

Seems to do the work but 'config.eap' is not accessable from my application.

Is there a way to configure EAP types or is it not possible?

答: Java Reflection API can be used to create IEEE802.x network with certificate. You can directily create IEEE802.x network connection is earlier version (like 1.6). In latest android the "EnterpriseField" (a inner class) is not directily accessible through program.</p>

Body:
I know how to create Open/WEP/PSK/PSK2 configuration programmatically.

ex.

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "ssid";
conf.preSharedKey = "\"password\"";
conf.status = WifiConfiguration.Status.ENABLED;

conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

int res = wifi.addNetwork(conf);
boolean b = wifi.enableNetwork(res, true);

But how do I create one for '802.1x EAP'?
Looking into the source code at:
..\packages\apps\Settings\src\com\android\settings\wifi\WifiDialog.java

case AccessPoint.SECURITY_EAP:
                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
                config.eap.setValue((String) mEapMethod.getSelectedItem());

                config.phase2.setValue((mPhase2.getSelectedItemPosition() == 0) ? "" :
                        "auth=" + mPhase2.getSelectedItem());
                config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" :
                        KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
                        (String) mEapCaCert.getSelectedItem());
                config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
                        KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
                        (String) mEapUserCert.getSelectedItem());
                config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
                        KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
                        (String) mEapUserCert.getSelectedItem());
                config.identity.setValue((mEapIdentity.length() == 0) ? "" :
                        mEapIdentity.getText().toString());
                config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" :
                        mEapAnonymous.getText().toString());
                if (mPassword.length() != 0) {
                    config.password.setValue(mPassword.getText().toString());
                }

Seems to do the work but 'config.eap' is not accessable from my application.

Is there a way to configure EAP types or is it not possible?


问:
Decompiling .dart.snapshot into Dart source code
According to dart-lang/sdk:

Starting in 1.21, the Dart VM also supports application snapshots, which include all the parsed classes and compiled code generated during a training run of a program.

```<code>    $ dart --snapshot=hello.dart.snapshot --snapshot-kind=app-jit hello.dart arguments-for-training
    Hello, world!
    $ dart hello.dart.snapshot arguments-for-use
    Hello, world!
</code>```

Now,how can i decompile this hello.dart.snapshot file to hello.dart?

In android Apk that written by java language we can decompile apk and get jar file from class.dex using dex2jar tools, but when application developed by flutter framework(written with dart)how can decompile this application and get application dart classes?

This image show snapshot files that generated in apk assets file.

答:
In release mode, Flutter compiles the Dart code to machine code, currently only ARMv7 (this procedure is called AOT - Ahead-Of-Time compilation). Unlike native Android apps, in which the Java is compiled to byte-code named Smali, which can be (pretty easily) decompiled to Java back again.

Most of the machine code is compiled to the file "isolate_snapshot_instr", which is written in a special format, and the flutter engine (flutterlib.so, also found inside the app), loads it into the app memory in run time. Therefore, you have 2 reasonable options:

Reading the app code at runtime (the .text segment). You can use
frida dump for that, and extract the compiled Dart code that
you need

Pacthing/Using the Flutter engine in order to deserialize the machine code

If you have ipa (IOS app), that could be easier, because all of the code is found in App.Framework.

Body:
According to dart-lang/sdk:

Starting in 1.21, the Dart VM also supports application snapshots, which include all the parsed classes and compiled code generated during a training run of a program.

    $ dart --snapshot=hello.dart.snapshot --snapshot-kind=app-jit hello.dart arguments-for-training
    Hello, world!
    $ dart hello.dart.snapshot arguments-for-use
    Hello, world!

Now,how can i decompile this hello.dart.snapshot file to hello.dart?

In android Apk that written by java language we can decompile apk and get jar file from class.dex using dex2jar tools, but when application developed by flutter framework(written with dart)how can decompile this application and get application dart classes?

This image show snapshot files that generated in apk assets file.


问:
Override class variable declared in the superclass's extension in Swift
Is it a bug of Swift 5.0.1 or Xcode?

This is in the playground with Xcode 10.2.1.

The codes are:

extension UIColor {
    @objc class var myGolden: UIColor {
        return self.init(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.900)
    }
}
print(UIColor.myGolden)

class MyUIColor: UIColor {
    override class var myGolden: UIColor {
        return super.init(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.750)
    }
}
print(MyUIColor.myGolden)
```

<p>The playground does not indicate any error for the class <code>MyUIColor</code></p>

<p>The output is:</p>

```UIExtendedSRGBColorSpace 1 0.894 0.541 0.9
```

libc++abi.dylib: terminating with uncaught exception of type NSException

and the runtime error says:

error: Execution was interrupted, reason: signal SIGABRT. The process
  has been left at the point where it was interrupted, use "thread
  return -x" to return to the state before expression evaluation.

答:
Changing the self.init and super.init calls to UIColor.init fixes the issue. You should only call self.init and super.init from convenience initialisers or subclass initialisers respectively, when creating an instance of your class in a computed property or any other functions, you should be calling the init methods using the type name rather than self or super.

```<code>extension UIColor {
    @objc class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.9)
    }
}
print(UIColor.myGolden)

class MyUIColor: UIColor {
    override class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.75)
    }
}
print(MyUIColor.myGolden)
</code>```

Body:
Is it a bug of Swift 5.0.1 or Xcode?

This is in the playground with Xcode 10.2.1.

The codes are:

extension UIColor {
    @objc class var myGolden: UIColor {
        return self.init(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.900)
    }
}
print(UIColor.myGolden)

class MyUIColor: UIColor {
    override class var myGolden: UIColor {
        return super.init(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.750)
    }
}
print(MyUIColor.myGolden)

The playground does not indicate any error for the class MyUIColor

The output is:

UIExtendedSRGBColorSpace 1 0.894 0.541 0.9

libc++abi.dylib: terminating with uncaught exception of type NSException

and the runtime error says:

error: Execution was interrupted, reason: signal SIGABRT. The process
  has been left at the point where it was interrupted, use "thread
  return -x" to return to the state before expression evaluation.

Body:
Changing the self.init and super.init calls to UIColor.init fixes the issue. You should only call self.init and super.init from convenience initialisers or subclass initialisers respectively, when creating an instance of your class in a computed property or any other functions, you should be calling the init methods using the type name rather than self or super.

extension UIColor {
    @objc class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.9)
    }
}
print(UIColor.myGolden)

class MyUIColor: UIColor {
    override class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.75)
    }
}
print(MyUIColor.myGolden)


问:
How do I design the following using pure CSS and HTML and Bootstrap (with check icon)?
I would like to design the following design using pure CSS, HTML and Bootstrap.

The content inside the green circle is supposed to be a check mark sign (I couldn't achieve it in Paint though)

Also note the text inside the large circle.I want it to be exactly in the center.

答:
.circle {
  border-radius: 50%;
  border: 4px solid #CCCCCC;
  display: flex;
  width: 140px;
  height: 140px;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  position: relative;
}

.circle:before {
  content: '';
  position: absolute;
  height: 40px;
  width: 40px;
  background-color: green;
  border-radius: 50%;
  bottom: 0;
  left: -10px;
  border: 5px solid #FFF;
}

.circle:after {
  content: '✔';
  position: absolute;
  color: #FFFFFF;
  bottom: 13px;
  left: 6px;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">
  <span>Name</span>
  <span>54</span>
  <span>some text</span>
</div></code>```

Check out the fiddle

Body:
.circle {
  border-radius: 50%;
  border: 4px solid #CCCCCC;
  display: flex;
  width: 140px;
  height: 140px;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  position: relative;
}

.circle:before {
  content: '';
  position: absolute;
  height: 40px;
  width: 40px;
  background-color: green;
  border-radius: 50%;
  bottom: 0;
  left: -10px;
  border: 5px solid #FFF;
}

.circle:after {
  content: '✔';
  position: absolute;
  color: #FFFFFF;
  bottom: 13px;
  left: 6px;
  font-size: 20px;
}

<div class="circle">
  <span>Name</span>
  <span>54</span>
  <span>some text</span>
</div>

Check out the fiddle


问:
Find absolute max value in Javascript array
I am looking for a nice way to find the maximum ABSOLUTE value of an array.

My array is i.e.

```<code>var array = [10,20,40,-30,-20,50,-60];
</code>```

Then:

```<code>Math.max.apply(null,array);
</code>```

Will result in '50'. But, actually, I want it to return '60'.

The option is to create a second array using Math.abs, but actually I am wondering if the apply function can be combined, so it is one elegant solution.

答:
How this

```<code>var array = [10,20,40,-30,-20,50,-60];
return Math.max(...array.map(a => Math.abs(a)))
</code>```

Body:
I am looking for a nice way to find the maximum ABSOLUTE value of an array.

My array is i.e.

var array = [10,20,40,-30,-20,50,-60];

Then:

Math.max.apply(null,array);

Will result in '50'. But, actually, I want it to return '60'.

The option is to create a second array using Math.abs, but actually I am wondering if the apply function can be combined, so it is one elegant solution.

Body:
How this

var array = [10,20,40,-30,-20,50,-60];
return Math.max(...array.map(a => Math.abs(a)))


问:
ListBox showing one property in different rows
I am using the following code for binding ListBox to a list i.e. List and set the binding Path=Name. But the list box shows just the one name with letter divided in rows. Like if a Name is JOHN, the list box row 1 shows "J", row 2 shows "O", row 3 shows "H", row 4 shows "N". Here's the code.

Xaml

```<code><ListBox Height="Auto" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Stretch" Margin="0,80,0,0" Name="ledgerListView" VerticalAlignment="Stretch" Width="200" KeyDown="ledgerListView_KeyDown" MouseDoubleClick="ledgerListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" />
</code>```

Code-Behind

```<code>List<Ledgers> ledgers = new List<Ledgers>();
        ledgers = DAL_Ledgers.LoadLedgers();
        this.DataContext = ledgers;
</code>```

答:
It looks like you're binding to the wrong thing... Does it work if you use:</p>

```<code><ListBox ItemsSource="{Binding}" ...>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <sdk:Label Content="{Binding Path=Name}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
</code>```

Body:
I am using the following code for binding ListBox to a list i.e. List and set the binding Path=Name. But the list box shows just the one name with letter divided in rows. Like if a Name is JOHN, the list box row 1 shows "J", row 2 shows "O", row 3 shows "H", row 4 shows "N". Here's the code.

Xaml

<ListBox Height="Auto" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Stretch" Margin="0,80,0,0" Name="ledgerListView" VerticalAlignment="Stretch" Width="200" KeyDown="ledgerListView_KeyDown" MouseDoubleClick="ledgerListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" />

Code-Behind

List<Ledgers> ledgers = new List<Ledgers>();
        ledgers = DAL_Ledgers.LoadLedgers();
        this.DataContext = ledgers;

Body:
It looks like you're binding to the wrong thing... Does it work if you use:

<ListBox ItemsSource="{Binding}" ...>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <sdk:Label Content="{Binding Path=Name}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>


问:
How to input values into already defined arrays?
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

```<code>int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }
</code>```

答:
You need to have a dynamic array for odd and even.
Moreover you made a mistake, if the modulo equals zero, the number is even and not odd. And you want to add input[n] and not n.

I think you should use STL containers instead of raw arrays, it will make it easier.

You can do as follows:

```<code>std::array<int, 10> input {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // fill the array with anything you want

std::vector<int> odd, even;

for(unsigned int n = 0; n < input.size(); ++n)
{
    (input[n]%2) ? (odd.push_back(input[n])) : (even.push_back(input[n]));
}
</code>```

You can replace the ternary conditional operator condition ? action_if_true : action_if_false by:

```<code>if(input[n]%2)
    odd.push_back(input[n]);
else
    even.push_back(input[n]);
</code>```

I hope it can help.

Body:
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }

Body:
You need to have a dynamic array for odd and even.
Moreover you made a mistake, if the modulo equals zero, the number is even and not odd. And you want to add input[n] and not n.

I think you should use STL containers instead of raw arrays, it will make it easier.

You can do as follows:

std::array<int, 10> input {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // fill the array with anything you want

std::vector<int> odd, even;

for(unsigned int n = 0; n < input.size(); ++n)
{
    (input[n]%2) ? (odd.push_back(input[n])) : (even.push_back(input[n]));
}

You can replace the ternary conditional operator condition ? action_if_true : action_if_false by:

if(input[n]%2)
    odd.push_back(input[n]);
else
    even.push_back(input[n]);

I hope it can help.


问:
Angular 8 using Ivy module.ngfactory cannot find
I have a snippet:

```<code>import { platformBrowser }    from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
enableProdMode();

import '../../../src/bundle';

import {ModuleNgFactory} from './module.ngfactory';

platformBrowser().bootstrapModuleFactory(ModuleNgFactory);
</code>```

As soon, I enable ivy, i face this error:

```<code>Running "cory-build-aot" task

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
Hash: d7163c5eb0d56ede4ba6
Version: webpack 4.32.2
Time: 24870ms
Built at: 05/29/2019 2:43:19 PM
 4 assets
Entrypoint polyfills = polyfills.d7163c5eb0d56ede4ba6.js sourcemaps/polyfills.d7163c5eb0d56ede4ba6.js.map
Entrypoint bundle = bundle.d7163c5eb0d56ede4ba6.js sourcemaps/bundle.d7163c5eb0d56ede4ba6.js.map
[0] ./test/angular-webpack/angular/polyfills.ts 0 bytes {1} [built]
[1] ./test/angular-webpack/angular/bundle.aot.ts 0 bytes {0} [built]

ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [0] ./node_modules/html-webpack-plugin/lib/loader.js!./test/angular-webpack/index.html 261 bytes {0} [built]
Warning: Command failed: ./node_modules/.bin/webpack-cli --color --cache --production --config /home/patrikx3/Projects/patrikx3/corifeus/corifeus-web/node_modules/corifeus-builder-angular/src/webpack.test.config.js

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
 Use --force to continue.

Aborted due to warnings.

Execution Time (2019-05-29 14:42:53 UTC+2)
cory-build-aot  25.8s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100%
Total 25.9s

patrikx3@workstation:~/Projects/patrikx3/corifeus/corifeus-web$
</code>```

What the error is:
ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

I try to enable ivy, by adding angularCompilerOptions section to enableIvy to be true, and that is when I get this error.

答:
Angular ivy no longer has any ngfactories.

instead of having to store metadata about the components in a separate file, the info is now stored as static fields on the component itself.

You should therefor refactor your code to not use ngfactory dependant thing such as importing ./module.ngfactory

Body:
I have a snippet:

import { platformBrowser }    from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
enableProdMode();

import '../../../src/bundle';

import {ModuleNgFactory} from './module.ngfactory';

platformBrowser().bootstrapModuleFactory(ModuleNgFactory);

As soon, I enable ivy, i face this error:

Running "cory-build-aot" task

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
Hash: d7163c5eb0d56ede4ba6
Version: webpack 4.32.2
Time: 24870ms
Built at: 05/29/2019 2:43:19 PM
 4 assets
Entrypoint polyfills = polyfills.d7163c5eb0d56ede4ba6.js sourcemaps/polyfills.d7163c5eb0d56ede4ba6.js.map
Entrypoint bundle = bundle.d7163c5eb0d56ede4ba6.js sourcemaps/bundle.d7163c5eb0d56ede4ba6.js.map
[0] ./test/angular-webpack/angular/polyfills.ts 0 bytes {1} [built]
[1] ./test/angular-webpack/angular/bundle.aot.ts 0 bytes {0} [built]

ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [0] ./node_modules/html-webpack-plugin/lib/loader.js!./test/angular-webpack/index.html 261 bytes {0} [built]
Warning: Command failed: ./node_modules/.bin/webpack-cli --color --cache --production --config /home/patrikx3/Projects/patrikx3/corifeus/corifeus-web/node_modules/corifeus-builder-angular/src/webpack.test.config.js

Compiling @angular/core : module as esm5

Compiling @angular/common : module as esm5

Compiling @angular/platform-browser : module as esm5

Compiling @angular/common/http : module as esm5

Compiling @angular/router : module as esm5

Compiling @angular/forms : module as esm5
 Use --force to continue.

Aborted due to warnings.

Execution Time (2019-05-29 14:42:53 UTC+2)
cory-build-aot  25.8s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100%
Total 25.9s

patrikx3@workstation:~/Projects/patrikx3/corifeus/corifeus-web$

What the error is:
ERROR in test/angular-webpack/angular/bundle.aot.ts(7,31): error TS2307: Cannot find module './module.ngfactory'.

I try to enable ivy, by adding angularCompilerOptions section to enableIvy to be true, and that is when I get this error.


问:
Why is a 'undefined' in this code?

var a = 10;

function Obj() {
  console.log(a);
  let a = 10;
}

Obj()```

on calling function Obj value of a is printed as undefined

答:
var a = 10;

function Obj() {
  console.log(a);
  let a = 10;
}

Obj()```

Function is also an object and to its properties, 1st the a:undefined the you perform a read of undefined(read about hoisting in javascript!).

Title: Why is a 'undefined' in this code?

Body:
var a = 10;

function Obj() {
  console.log(a);
  let a = 10;
}

Obj()

on calling function Obj value of a is printed as undefined

Body:
var a = 10;

function Obj() {
  console.log(a);
  let a = 10;
}

Obj()

Function is also an object and to its properties, 1st the a:undefined the you perform a read of undefined(read about hoisting in javascript!).


问:
Error while trying to set config in tigrc
I've below line in my tigrc file

```<code>set commit-title-graph = no
</code>```

I'm getting this error when I run any tig command, and I'm not able to fine what it the issue.

```<code>tig warning: ~/.tigrc:1: Unknown option name: commit-title-graph
tig warning: Errors while loading /Users/johndoe/.tigrc.
</code>```

答:
According to man tigrc, commit-title is one of options in View Settings, not a variable. So the use case is like this:

```<code>set main-view = \
    date:relative \
    author:abbreviated \
    id \
    commit-title:graph=v2,refs=true
</code>```

Body:
I've below line in my tigrc file

set commit-title-graph = no

I'm getting this error when I run any tig command, and I'm not able to fine what it the issue.

tig warning: ~/.tigrc:1: Unknown option name: commit-title-graph
tig warning: Errors while loading /Users/johndoe/.tigrc.

Body:
According to man tigrc, commit-title is one of options in View Settings, not a variable. So the use case is like this:

set main-view = \
    date:relative \
    author:abbreviated \
    id \
    commit-title:graph=v2,refs=true


答:
The problem isn't the class variable override, is instead the improper use of self.init and super.init. You should change the code as follows:

```<code>extension UIColor {
    @objc class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.900)
    }
}
print(UIColor.myGolden)

class MyUIColor: UIColor {
    override class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.750)
    }
}
print(MyUIColor.myGolden)
</code>```

Title: Override class variable declared in the superclass's extension in Swift

Body:
The problem isn't the class variable override, is instead the improper use of self.init and super.init. You should change the code as follows:

extension UIColor {
    @objc class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.900)
    }
}
print(UIColor.myGolden)

class MyUIColor: UIColor {
    override class var myGolden: UIColor {
        return UIColor(red: 1.000, green: 0.894, blue: 0.541, alpha: 0.750)
    }
}
print(MyUIColor.myGolden)


问:
Design considerations for realtime OPC system
We are in the process of redesigning a disjointed realtime OPC system which has proven to be cumbersome. Our technology stack is C#, .NET 4 and SQL Server 2008 R2, hosted on 32 bit Windows Server 2003. Physical archtecture currently dictates that all tiers are to be hosted on a single server, although with sufficient motivation (read: ROI) this could be increased to 2.

The basic existing architecture is:

External OPC devices call our webservice to populate SQL with realtime data, approxomately 300 events per second. We have no control over volume or batch processing here, although in the rewrite I would like to implement batching in the web service to spare SQL from 300 insert statements per second.

SQL is used as a central resource for various components (about 9 in total, all to be redesigned) that perform tasks ranging from alarms to reporting. This is currently the biggest problem with the existing design, in that there is no single BLL or even DAL through which all these components consume/manipulate data or govern behavior.

Components range from Windows Services to Web Services to Windows Applications. The biggest consumer of CPU time and SQL connections is a Windows Forms application that monitors all realtime data and raises alarms as required. It also does realtime trend graphs, which is quite expensive to run.

For the rewrite there is a strong push towards WPF with which, apart from the learning curve, I have no problem. My question is more concerned with the underlying architecture:

I am currently doing some research on how to implement a single DAL and BLL. For the DAL I am leaning towards EF or nHibernate, with Linq-to-SQL also a possibility.

For the BLL I only have experience in CSLA.NET, and I fear this may be a bit over the top for a system in which speed and resource consumption is crucial.

Does anybody have any experience with a similiar system, and are willing to share a few lessons or design guidelines?

答:
I have some exposure to acquiring data from OPC servers, though the applications I implemented I believe were not as large scale as yours. For my application I had a publish - subscribe architecture based messaging layer, my suggestion based on my experience then would be

1) For your real time data acquisition you would need something based on a publish - subscribe mechanism, Biz talk server is the microsoft answer to ESB. So I would look at this.

2) Does your windows forms application need to look at the database directly ? I mean can it look at an intermediate that can say look at the db for historical purposes or subscribe to the real time feed if all it cares is real time information


问:
Run migrations using db.create_all()
I needed to write my own Trigger to be able to update some search vectors in my Postgres database and alembic/ Sqlalchemy weren't able to autogenerate these.

For that I added my custom SQL into a migrations file. Using my dev machine everything works fine. But I noticed that the trigger is created when running my tests.

For testing I use purest and tox. My conftest.py creates the database like so:

```<code>@pytest.fixture
def db(app):
    _db.app = app

    with app.app_context():
        _db.create_all()

    Role.insert_roles()  # insert roles

    yield _db  # teardown

    _db.session.close()
    _db.drop_all()
</code>```

But this script only creates the raw tables. What should I change, so that my custom SQL will be executed every time a new database is created?

Thank you

答: I found a solution. I added the Trigger DDL like it was suggested in this question: SQLAlchemy declarative: defining triggers and indexes (Postgres 9)</p>

Title: Run migrations using db.create_all()

Body:
I needed to write my own Trigger to be able to update some search vectors in my Postgres database and alembic/ Sqlalchemy weren't able to autogenerate these.

For that I added my custom SQL into a migrations file. Using my dev machine everything works fine. But I noticed that the trigger is created when running my tests.

For testing I use purest and tox. My conftest.py creates the database like so:

@pytest.fixture
def db(app):
    _db.app = app

    with app.app_context():
        _db.create_all()

    Role.insert_roles()  # insert roles

    yield _db  # teardown

    _db.session.close()
    _db.drop_all()

But this script only creates the raw tables. What should I change, so that my custom SQL will be executed every time a new database is created?

Thank you