问:
SetBackgroundColor for even items in RecyclerView
I want to setBackgroundColor for even items in my RecyclerView. I tried something like that in theAdapter class:

```<code>  override fun onBindViewHolder(holder: ServersViewHolder, position: Int) {
        val server: Server = list[position]

        if (position % 2 == 0){
            holder.mConstraintLayout.setBackgroundColor(R.color.colorRed)
        }

        holder.bind(server)
    }
</code>```

But it doesn't work fine. Could you help me?

EDIT

```<code>class ServerLisAdapter: RecyclerView.Adapter<ServersViewHolder>() {

    private var list = emptyList<Server>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ServersViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_server_list, parent, false)
        return ServersViewHolder(view)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: ServersViewHolder, position: Int) {
        val server: Server = list[position]

        if (position % 2 == 0){
            holder.mConstraintLayout.setBackgroundColor(R.color.colorRed)
        }

        holder.bind(server)
    }

    fun setList(serverList: List<Server>) {
        list = serverList
        notifyDataSetChanged()
    }
}
</code>```

答:
Try this simple solution.

this will help you to help to keep the instance while scrolling about the position

Just declare a variable in your modal class like this

```<code>data class Server (
    var isNumberEven: Boolean,
    //other params
)
</code>```

now just use this loop before you set adapter

```<code>for(i in 0 until list!!.size){
            if ((i % 2) == 0) {
                // number is even
                list!![i].isNumberEven=true
            }

            else {
                // number is odd
                list!![i].isNumberEven=false
            }
        }
</code>```

Now in your adapter use like this and set color

```<code>override fun onBindViewHolder(holder: ServersViewHolder, position: Int) {
    val server: Server = list[position]

    if (list[position].isNumberEven){
        holder.mConstraintLayout.setBackgroundColor(R.color.colorRed)
    } else {
        holder.mConstraintLayout.setBackgroundColor(R.color.otherColor)
    }

    holder.bind(server)
}
</code>```

Body:
I want to setBackgroundColor for even items in my RecyclerView. I tried something like that in theAdapter class:

  override fun onBindViewHolder(holder: ServersViewHolder, position: Int) {
        val server: Server = list[position]

        if (position % 2 == 0){
            holder.mConstraintLayout.setBackgroundColor(R.color.colorRed)
        }

        holder.bind(server)
    }

But it doesn't work fine. Could you help me?

EDIT

class ServerLisAdapter: RecyclerView.Adapter<ServersViewHolder>() {

    private var list = emptyList<Server>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ServersViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_server_list, parent, false)
        return ServersViewHolder(view)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: ServersViewHolder, position: Int) {
        val server: Server = list[position]

        if (position % 2 == 0){
            holder.mConstraintLayout.setBackgroundColor(R.color.colorRed)
        }

        holder.bind(server)
    }

    fun setList(serverList: List<Server>) {
        list = serverList
        notifyDataSetChanged()
    }
}

Body:
Try this simple solution.

this will help you to help to keep the instance while scrolling about the position

Just declare a variable in your modal class like this

data class Server (
    var isNumberEven: Boolean,
    //other params
)

now just use this loop before you set adapter

for(i in 0 until list!!.size){
            if ((i % 2) == 0) {
                // number is even
                list!![i].isNumberEven=true
            }

            else {
                // number is odd
                list!![i].isNumberEven=false
            }
        }

Now in your adapter use like this and set color

override fun onBindViewHolder(holder: ServersViewHolder, position: Int) {
    val server: Server = list[position]

    if (list[position].isNumberEven){
        holder.mConstraintLayout.setBackgroundColor(R.color.colorRed)
    } else {
        holder.mConstraintLayout.setBackgroundColor(R.color.otherColor)
    }

    holder.bind(server)
}


来源: stackexchange

问:
ngFor not displaying data from Observable Event Source
In my Angular6 application I have a problem with displaying data with async ngfor. I am expecting some Server Sent Events from backend (just object with answer string field). While console.log shows that answer list from service contains answers, ngfor displays nothing.

Here is my component:

```<code>import { Component } from '@angular/core';
import { Answer } from './answer';
import { AnswerReactiveService } from './answer-reactive.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-answers',
  templateUrl: './answers.component.html',
  providers: [AnswerReactiveService],
  styleUrls: ['./answers.component.css']
})
export class AnswersComponent {
  answers: Observable<Answer[]>;

  constructor(private answerReactiveService: AnswerReactiveService) {
  }

  requestAnswerStream(): void {
    this.answers = this.answerReactiveService.getAnswerStream();
  }

}
</code>```

Here is the service:

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

import { Answer } from './answer';

import { Observable } from 'rxjs';

@Injectable()
export class AnswerReactiveService {

  private answers: Answer[] = [];
  private url: string = 'http://localhost:8080/events/1';

  getAnswerStream(): Observable<Array<Answer>> {
    return Observable.create((observer) => {
      let url = this.url;
      let eventSource = new EventSource(url);
      eventSource.onmessage = (event) => {
        console.log('Received event: ', event);
        const json = JSON.parse(event.data);
        console.log(json);
        this.answers.push(new Answer(json['answer']));
        console.log(this.answers);
        observer.next(this.answers);
      };
      eventSource.onerror = (error) => {
        if (eventSource.readyState === 0) {
          console.log('The stream has been closed by the server.');
          eventSource.close();
          observer.complete();
        } else {
          observer.error('EventSource error: ' + error);
        }
      };
    });
  }
}
</code>```

And HTML:

```<code><div class="row">
  <div class="col-md-8">
    <p>
      <button (click)="requestAnswerStream()">Gimmie answers</button>
    </p>
    <ul>
      <li *ngFor="let answer of answers | async">{{answer.answer}}</li>
    </ul>
  </div>
</div>
</code>```

答:
Try using - addEventListener

An example of which works for me:

```<code>@Injectable()
export class EmployeeService {

  public employeesBehavior: BehaviorSubject<Employee>;
  public employeesObservable: Observable<Employee>;

  private URL = 'http://localhost:8080';

  constructor() {
    this.employeesBehavior = new BehaviorSubject(null);
    this.employeesObservable = this.employeesBehavior.asObservable();
  }

  public stream() {
    const streamURL = this.URL + '/stream';
    const eventSource = new EventSource(streamURL);

    eventSource.addEventListener('employees', (event: any) => {
      const employee = JSON.parse(event.data) as Employee;
      this.employeesBehavior.next(employee);
    });
  }
}
</code>```

Сomponent

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  public employees: Employee[] = [];

  constructor(
    public employeeService: EmployeeService
  ) {

  }

  ngOnInit(): void {
    this.employeeService.stream();

    this.employeeService.employeesObservable.subscribe(e => {
      if (e != null) {
        this.employees.push(e);
      }
    });
  }
}
</code>```

Template

```<code><div *ngFor="let employee of employees">
     {{employee.name}}
</div>
</code>```

Server (Spring Boot)

```<code>@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Employee>> stream() {
        return employeeService.stream().delayElements(Duration.ofSeconds(1)).map(e ->
            ServerSentEvent.<Employee>builder()
                .id(String.valueOf(e.getId()))
                .event("employees")
                .data(e)
                .build()
        );
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my Angular6 application I have a problem with displaying data with async ngfor. I am expecting some Server Sent Events from backend (just object with answer string field). While console.log shows that answer list from service contains answers, ngfor displays nothing.

Here is my component:

import { Component } from '@angular/core';
import { Answer } from './answer';
import { AnswerReactiveService } from './answer-reactive.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-answers',
  templateUrl: './answers.component.html',
  providers: [AnswerReactiveService],
  styleUrls: ['./answers.component.css']
})
export class AnswersComponent {
  answers: Observable<Answer[]>;

  constructor(private answerReactiveService: AnswerReactiveService) {
  }

  requestAnswerStream(): void {
    this.answers = this.answerReactiveService.getAnswerStream();
  }

}

Here is the service:

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

import { Answer } from './answer';

import { Observable } from 'rxjs';

@Injectable()
export class AnswerReactiveService {

  private answers: Answer[] = [];
  private url: string = 'http://localhost:8080/events/1';

  getAnswerStream(): Observable<Array<Answer>> {
    return Observable.create((observer) => {
      let url = this.url;
      let eventSource = new EventSource(url);
      eventSource.onmessage = (event) => {
        console.log('Received event: ', event);
        const json = JSON.parse(event.data);
        console.log(json);
        this.answers.push(new Answer(json['answer']));
        console.log(this.answers);
        observer.next(this.answers);
      };
      eventSource.onerror = (error) => {
        if (eventSource.readyState === 0) {
          console.log('The stream has been closed by the server.');
          eventSource.close();
          observer.complete();
        } else {
          observer.error('EventSource error: ' + error);
        }
      };
    });
  }
}

And HTML:

      <button (click)="requestAnswerStream()">Gimmie answers</button>

{{answer.answer}}

Body:
Try using - addEventListener

An example of which works for me:

@Injectable()
export class EmployeeService {

  public employeesBehavior: BehaviorSubject<Employee>;
  public employeesObservable: Observable<Employee>;

  private URL = 'http://localhost:8080';

  constructor() {
    this.employeesBehavior = new BehaviorSubject(null);
    this.employeesObservable = this.employeesBehavior.asObservable();
  }

  public stream() {
    const streamURL = this.URL + '/stream';
    const eventSource = new EventSource(streamURL);

    eventSource.addEventListener('employees', (event: any) => {
      const employee = JSON.parse(event.data) as Employee;
      this.employeesBehavior.next(employee);
    });
  }
}

Сomponent

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  public employees: Employee[] = [];

  constructor(
    public employeeService: EmployeeService
  ) {

  }

  ngOnInit(): void {
    this.employeeService.stream();

    this.employeeService.employeesObservable.subscribe(e => {
      if (e != null) {
        this.employees.push(e);
      }
    });
  }
}

Template

<div *ngFor="let employee of employees">
     {{employee.name}}
</div>

Server (Spring Boot)

@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Employee>> stream() {
        return employeeService.stream().delayElements(Duration.ofSeconds(1)).map(e ->
            ServerSentEvent.<Employee>builder()
                .id(String.valueOf(e.getId()))
                .event("employees")
                .data(e)
                .build()
        );
    }


问:
JavaScript - Force select element to dropdown?
How can I force the select element to dropdown using Javascript? Is it possible?

```<code><select id="MiamiPlayers">
    <option value="0">Bosh</option>
    <option value="1">Wade</option>
    <option value="2">LeBron</option>
</select>

<input type="button" onclick="Show()" />

<script type="text/javascript">
    function Show()
    {
        //force the select to dropdown...
    }
</script>
</code>```

Thanks in advance!

答:
```<code>var select = document.getElementById(id);
select.size = select.options.length;
</code>```

<p>where id is the id of the your select box... </p>

Body:
How can I force the select element to dropdown using Javascript? Is it possible?

<select id="MiamiPlayers">
    <option value="0">Bosh</option>
    <option value="1">Wade</option>
    <option value="2">LeBron</option>
</select>

<input type="button" onclick="Show()" />

Thanks in advance!

Body:
var select = document.getElementById(id);
select.size = select.options.length;

where id is the id of the your select box...

ContentLicense: CC BY-SA 3.0


问:
Fix coin change brute force solution
I am starting to write and understand coin change problem and couldn't get intuition so I have started to write a brute force solution. I want to understand the brute force solution before moving to memoization.

```<code>coins = [2, 3, 7]
change = 12

def coin_change(c):
    print(c)
    if c <= 0:
        return 0
    else:
        for i in coins:
            if c - i >= 0:
                coin_change(c - i)

coin_change(change)
</code>```

It prints out couple of changes left but I don't know how to store each path in an array.

I also want to understand how recursion can be used to track path. I can think of adding an extra argument in coin_change but maybe there is an alternate way.

I am confused about its complexity. It has a number of coins call at every step but many online resources mention it's 2n.

Edit: Please note that the coin supply is unlimited, The answer is 4

```<code>[2, 2, 2, 2, 2, 2]
[3, 3, 3, 3]
[2, 2, 2, 3, 3]
[2, 3, 7]
</code>```

答:
Here is an example to get all paths for the coins. In general, when you write a recursive function, you want to 1) have a condition that exits the recursion, and 2) write how to extend the previous recursive step.

```<code>coins  = [2, 3, 7]
change = 12

def coin_change_paths(paths):
    if all(sum(path)>=change for path in paths):
        return paths
    new_paths = []
    for path in paths:
        if sum(path)<change:
            new_paths.extend(path+[c] for c in coins)
        else:
            new_paths.append(path)
    return coin_change_paths(new_paths)

paths = coin_change_paths([[2],[3],[7]])
</code>```

This doesn't account for duplication. To do that you should sort and then dedup:

```<code>paths = [sorted(p) for p in paths]
temp = []
for p in paths:
    if p not in temp:
        temp.append(p)
paths = temp
</code>```

You still have to check which ones are valid.

```<code>paths = [p for p in paths if sum(p)==change]
print(paths)
</code>```

Try to see if you can combine these together and simplify the code.

Title: Fix coin change brute force solution

Body:
I am starting to write and understand coin change problem and couldn't get intuition so I have started to write a brute force solution. I want to understand the brute force solution before moving to memoization.

coins = [2, 3, 7]
change = 12

def coin_change(c):
    print(c)
    if c <= 0:
        return 0
    else:
        for i in coins:
            if c - i >= 0:
                coin_change(c - i)

coin_change(change)

It prints out couple of changes left but I don't know how to store each path in an array.

I also want to understand how recursion can be used to track path. I can think of adding an extra argument in coin_change but maybe there is an alternate way.

I am confused about its complexity. It has a number of coins call at every step but many online resources mention it's 2n.

Edit: Please note that the coin supply is unlimited, The answer is 4

[2, 2, 2, 2, 2, 2]
[3, 3, 3, 3]
[2, 2, 2, 3, 3]
[2, 3, 7]

Body:
Here is an example to get all paths for the coins. In general, when you write a recursive function, you want to 1) have a condition that exits the recursion, and 2) write how to extend the previous recursive step.

coins  = [2, 3, 7]
change = 12

def coin_change_paths(paths):
    if all(sum(path)>=change for path in paths):
        return paths
    new_paths = []
    for path in paths:
        if sum(path)<change:
            new_paths.extend(path+[c] for c in coins)
        else:
            new_paths.append(path)
    return coin_change_paths(new_paths)

paths = coin_change_paths([[2],[3],[7]])

This doesn't account for duplication. To do that you should sort and then dedup:

paths = [sorted(p) for p in paths]
temp = []
for p in paths:
    if p not in temp:
        temp.append(p)
paths = temp

You still have to check which ones are valid.

paths = [p for p in paths if sum(p)==change]
print(paths)

Try to see if you can combine these together and simplify the code.


问:
Angular routing not working when deployed statically with Node
I am building my angular project and inserting the build output into a public folder in the root of my node project.

In my app.js file, I have the following code:

```<code>...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
     res.send(path.join(__dirname, 'public/index.html'));
});
</code>```

When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.

However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.

How can this be solved?

答:
The problem was in the .send() method...
I replaced this:

```<code>app.get('*', (req, res) => {
 res.send(path.join(__dirname, 'public/index.html'));
});
</code>```

with this:

```<code>app.get('*', (req, res) => {
 res.sendFile(path.join(__dirname, 'public/index.html'));
});
</code>```

and it worked.
Sorry guys for making you loose time. You helped me research different things though!

Body:
I am building my angular project and inserting the build output into a public folder in the root of my node project.

In my app.js file, I have the following code:

...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
     res.send(path.join(__dirname, 'public/index.html'));
});

When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.

However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.

How can this be solved?

Body:
The problem was in the .send() method...
I replaced this:

app.get('*', (req, res) => {
 res.send(path.join(__dirname, 'public/index.html'));
});

with this:

app.get('*', (req, res) => {
 res.sendFile(path.join(__dirname, 'public/index.html'));
});

and it worked.
Sorry guys for making you loose time. You helped me research different things though!


问:
Using C++ objects from C
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

```<code>class MyData {
  ...
};
</code>```

From C:

```<code>struct MyData {
  ...
};
</code>```

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

答:
The classic approach is that your C++ code exposes flat C functions for accessing instances of your class.  And marks these functions as extern "C".

Example mydata.h

```<code>#ifndef HEADER_H
#define HEADER_H

#ifdef __cplusplus

class MyData
{
public:
    MyData();
    void SetX(int val);
    int GetX();
private:
    int _x;
};

#endif

typedef void* MYDATA;

#ifdef __cplusplus
extern "C" {
#endif
    MYDATA MyData_new();
    void MyData_delete(MYDATA md);
    void MyData_SetX(MYDATA md, int x);
    int MyData_GetX(MYDATA md);

#ifdef __cplusplus
}
#endif

#endif
</code>```

Then in mydata.cpp

```<code>#include "mydata.h"

MyData::MyData() : _x(0)
{
}

int MyData::GetX()
{
    return _x;
}

void MyData::SetX(int val)
{
    _x = val;
}

extern "C"  MYDATA MyData_new()
{
    return new MyData();
}

extern "C" void MyData_Delete(MYDATA foo)
{
    auto pFoo = reinterpret_cast<MyData*>(foo);
    delete pFoo;
}

extern "C" void MyData_SetX(MYDATA foo, int x)
{
    auto pFoo = reinterpret_cast<MyData*>(foo);
    pFoo->SetX(x);
}

extern "C" int MyData_GetX(MYDATA foo)
{
    auto pFoo = reinterpret_cast<MyData*>(foo);
    return pFoo->GetX();
}
</code>```

Title: Using C++ objects from C

Body:
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

class MyData {
  ...
};

From C:

struct MyData {
  ...
};

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

Body:
The classic approach is that your C++ code exposes flat C functions for accessing instances of your class.  And marks these functions as extern "C".

Example mydata.h

#ifndef HEADER_H
#define HEADER_H

#ifdef __cplusplus

class MyData
{
public:
    MyData();
    void SetX(int val);
    int GetX();
private:
    int _x;
};

#endif

typedef void* MYDATA;

#ifdef __cplusplus
extern "C" {
#endif
    MYDATA MyData_new();
    void MyData_delete(MYDATA md);
    void MyData_SetX(MYDATA md, int x);
    int MyData_GetX(MYDATA md);

#ifdef __cplusplus
}
#endif

#endif

Then in mydata.cpp

#include "mydata.h"

MyData::MyData() : _x(0)
{
}

int MyData::GetX()
{
    return _x;
}

void MyData::SetX(int val)
{
    _x = val;
}

extern "C"  MYDATA MyData_new()
{
    return new MyData();
}

extern "C" void MyData_Delete(MYDATA foo)
{
    auto pFoo = reinterpret_cast<MyData*>(foo);
    delete pFoo;
}

extern "C" void MyData_SetX(MYDATA foo, int x)
{
    auto pFoo = reinterpret_cast<MyData*>(foo);
    pFoo->SetX(x);
}

extern "C" int MyData_GetX(MYDATA foo)
{
    auto pFoo = reinterpret_cast<MyData*>(foo);
    return pFoo->GetX();
}


问:
Open a link from popup pdf in a new browser window
I am openning one popup window using window.open .Now that popup contains a pdf.If there is any link in that pdf (like www.google.com) clicking the link is openning the site inside the popup only.How to make this link open in a new browser window ? I have created the pdf using corda.</p>

答:
Are you asking for opening a new window when the user click on a link?

if so here is how:

```<code><a href='link.pdf' target='_blank'>Read Me</a>
</code>```

See the list of values the Target Attribute can take :)

Body:
Are you asking for opening a new window when the user click on a link?

if so here is how:

<a href='link.pdf' target='_blank'>Read Me</a>

See the list of values the Target Attribute can take :)


问:
Get a document with a specific _id with mongo-delphi-driver
I have to perform a query on mongodb, i would like select only a document has a particular _id (type ObjectId).

I use "Strict mode" sintax and in particular the operator $oid for compare _id with a string.

But it doesn't work!, I don't now if it is a bug (a bag of mongo-c-driver/mongo-delphi-driver) or if I write wrong code for make a query on ObjectId field.

Below a simple snippet of code, the document with that _id exists but the bson document is nil

```<code>  var
    b : TBson;
  begin
    b := mongo.findOne(ns,(BSON(['_id','{','$oid','58c6b6af9b2dcd04ae46844d','}'])));
    if b = nil then
      ShowMessage('No match')
    else
      ShowRecord(b);
  end
</code>```

https://docs.mongodb.com/manual/reference/mongodb-extended-json/

I also try with this two methods...

```<code>var
  bb : TBsonBuffer;
  query, b : TBson;
  cursor : TMongoCursor;
begin
  bb := TbsonBuffer.Create();
  bb.startObject('_id');
  bb.append('$oid', PAnsiChar('"58c6b6af9b2dcd04ae46844d"'));
  bb.finishObject();

  query := bb.finish();
  b := mongo.findOne(ns, query);
  if b = nil then
    ShowMessage('No match')
  else
    ShowRecord(b);
end
</code>```

and

```<code>var
  bb : TBsonBuffer;
  query, b : TBson;
  id : TBsonOID;
begin
  id := TBsonOID.Create('58c6b6af9b2dcd04ae46844d');
  bb := TbsonBuffer.Create();
  bb.startObject('_id');
  bb.append('$oid', id);
  bb.finishObject();

  query := bb.finish();
  b := mongo.findOne(ns, query);
  if b = nil then
    ShowMessage('No match')
  else
    ShowRecord(b);
end;
</code>```

答:
```<code>procedure TForm2.Button1Click(Sender: TObject);
var oCrs  : IMongoCursor;
    Aux   : String;
begin
   oCrs := FMongoConn['DataBase']['collections'].Find()
    .Match
      .BeginObject('_id')
        .Add('$eq', TJsonOid.Create('5eab21d55c61623e44004b21'))
      .EndObject
    .&End;

  While (oCrs.Next) do
    begin
      Aux := Aux + oCrs.Doc.AsJSON;
    end;

  if Trim(Aux) = '' then
    Memo1.Text := '0'
  else
    Memo1.Text := Aux;
end;
</code>```

Body:
I have to perform a query on mongodb, i would like select only a document has a particular _id (type ObjectId).

I use "Strict mode" sintax and in particular the operator $oid for compare _id with a string.

But it doesn't work!, I don't now if it is a bug (a bag of mongo-c-driver/mongo-delphi-driver) or if I write wrong code for make a query on ObjectId field.

Below a simple snippet of code, the document with that _id exists but the bson document is nil

  var
    b : TBson;
  begin
    b := mongo.findOne(ns,(BSON(['_id','{','$oid','58c6b6af9b2dcd04ae46844d','}'])));
    if b = nil then
      ShowMessage('No match')
    else
      ShowRecord(b);
  end

https://docs.mongodb.com/manual/reference/mongodb-extended-json/

I also try with this two methods...

var
  bb : TBsonBuffer;
  query, b : TBson;
  cursor : TMongoCursor;
begin
  bb := TbsonBuffer.Create();
  bb.startObject('_id');
  bb.append('$oid', PAnsiChar('"58c6b6af9b2dcd04ae46844d"'));
  bb.finishObject();

  query := bb.finish();
  b := mongo.findOne(ns, query);
  if b = nil then
    ShowMessage('No match')
  else
    ShowRecord(b);
end

and

var
  bb : TBsonBuffer;
  query, b : TBson;
  id : TBsonOID;
begin
  id := TBsonOID.Create('58c6b6af9b2dcd04ae46844d');
  bb := TbsonBuffer.Create();
  bb.startObject('_id');
  bb.append('$oid', id);
  bb.finishObject();

  query := bb.finish();
  b := mongo.findOne(ns, query);
  if b = nil then
    ShowMessage('No match')
  else
    ShowRecord(b);
end;


问:
LiveData does not update
```<code>class RequestViewModel(private val repository: RequestRepository) : ViewModel() {

// request currency type
private val currencySearchType = MutableLiveData<String>()

val requests: LiveData<PagedList<Request>> = repository.getRequests(currencySearchType.value!!)

fun updateSearchType(type: String) {
    currencySearchType.postValue(type)
}}
</code>```

above is the code in my viewModel.

```<code>private fun initAdapter() {
        recyclerView.adapter = adapter
        viewModel.requests.observe(viewLifecycleOwner, Observer {
            adapter.submitList(it)
        })
}
</code>```

and this is the code in fragment. So basically, what i'm doing is I observe "requests" in viewModel, and in fragment, I will also call updateSearchType to update the currencySearchType. I was hoping that once  currencySearchType changed, then the viewmodel.requests will change too. But it turns out the requests never gotta called again. Does anyone know where it went wrong? Appreciate for the help!

答:
Changing the value of currencySearchType does not triggers live data you just using it as function parameter. You have to use Transformation for this.

https://developer.android.com/reference/android/arch/lifecycle/Transformations

```<code>class RequestViewModel(private val repository: RequestRepository) : ViewModel() {

// request currency type
lateinit var currencySearchType:String

val requests: LiveData<PagedList<Request>> = Transformations.switchMap(currencySearchType) { repository.getRequests(it) }

fun updateSearchType(type: String) {
    currencySearchType = type
}}
</code>```

Title: LiveData does not update

Body:
class RequestViewModel(private val repository: RequestRepository) : ViewModel() {

// request currency type
private val currencySearchType = MutableLiveData<String>()

val requests: LiveData<PagedList<Request>> = repository.getRequests(currencySearchType.value!!)

fun updateSearchType(type: String) {
    currencySearchType.postValue(type)
}}

above is the code in my viewModel.

private fun initAdapter() {
        recyclerView.adapter = adapter
        viewModel.requests.observe(viewLifecycleOwner, Observer {
            adapter.submitList(it)
        })
}

and this is the code in fragment. So basically, what i'm doing is I observe "requests" in viewModel, and in fragment, I will also call updateSearchType to update the currencySearchType. I was hoping that once  currencySearchType changed, then the viewmodel.requests will change too. But it turns out the requests never gotta called again. Does anyone know where it went wrong? Appreciate for the help!

Body:
Changing the value of currencySearchType does not triggers live data you just using it as function parameter. You have to use Transformation for this.

https://developer.android.com/reference/android/arch/lifecycle/Transformations

class RequestViewModel(private val repository: RequestRepository) : ViewModel() {

// request currency type
lateinit var currencySearchType:String

val requests: LiveData<PagedList<Request>> = Transformations.switchMap(currencySearchType) { repository.getRequests(it) }

fun updateSearchType(type: String) {
    currencySearchType = type
}}


问:
Grab the last octet in an IP address using Python
I am writing a Python script that will take an IP address in CIDR format (ie. 1.1.1.0/32 or 10.0.0.1/24) and split the IP into three parts: the first three octets (1.1.1), the last octet (0) and the Subnet mask (32). The IP will be of variable length so I don't know if I can use some sort of string character counter.

Any ideas?

Thanks

Body:
ipstring="192.168.1.1/12"
s=re.split(r"\b(\d{1,3}\.\d{1,3}\.\d{1,3})\.(\d{1,3})\/(\d+)\b",ipstring)
print s
['', '192.168.1', '1', '12', '']
print s[1]
192.168.1
print s[2]
1
print s[3]
12
>>>


问:
Oracle: Move column to new table, eliminate non-unique rows remaining in original table while maintaining foreign relationship between two tables
I have a table like the following:

Table 1: Person_Favorite_Food

```<code>id name   address          favorite_food
------------------------------------------
1  Dave   123 Cherry Ln    Pizza
2  Dave   123 Cherry Ln    Cheeseburger
3  Dave   456 Peachtree St Ice cream
4  Cindy  789 Grove Rd     Pizza
</code>```

id - primary key

unique key constraint on the following columns: name, address and food

Since each person can have more than one favorite food item I'd like to split Table 1 into two tables like the following:

Table 2: Person

```<code>id name   address
--------------------------
1  Dave   123 Cherry Ln
3  Dave   456 Peachtree St
4  Cindy  789 Grove Rd
</code>```

Table 3: Person_Favorite_Food

```<code>person_id  favorite_food
-----------------
1          Pizza
1          Cheeseburger
3          Ice cream
4          Pizza
</code>```

How would I go about doing this in Oracle?

Note: In the original table Rows 1 and 2 represent favorite food for the same person so the favorite food entries in the Person_Favorite_Food table will need to have the same identifier for both of those entries although the identifiers are different in the initial table.

答:
Use simple aggregation to create table person:

```<code>create table person as
select min(id) id, name, address
  from person_favorite_food
  group by name, address;
</code>```

Use the same query in merge to change id for some rows:

```<code>merge into person_favorite_food a
using (select min(id) id, name, address from person_favorite_food group by name, address) b
on (a.name = b.name and a.address = b.address)
when matched then update set a.id = b.id;
</code>```

Drop unwanted columns:

```<code>alter table person_favorite_food drop (name, address);
</code>```

Done. Demo in dbfiddle.

Body:
I have a table like the following:

Table 1: Person_Favorite_Food

id name   address          favorite_food
------------------------------------------
1  Dave   123 Cherry Ln    Pizza
2  Dave   123 Cherry Ln    Cheeseburger
3  Dave   456 Peachtree St Ice cream
4  Cindy  789 Grove Rd     Pizza

id - primary key

unique key constraint on the following columns: name, address and food

Since each person can have more than one favorite food item I'd like to split Table 1 into two tables like the following:

Table 2: Person

id name   address
--------------------------
1  Dave   123 Cherry Ln
3  Dave   456 Peachtree St
4  Cindy  789 Grove Rd

Table 3: Person_Favorite_Food

person_id  favorite_food
-----------------
1          Pizza
1          Cheeseburger
3          Ice cream
4          Pizza

How would I go about doing this in Oracle?

Note: In the original table Rows 1 and 2 represent favorite food for the same person so the favorite food entries in the Person_Favorite_Food table will need to have the same identifier for both of those entries although the identifiers are different in the initial table.

Body:
Use simple aggregation to create table person:

create table person as
select min(id) id, name, address
  from person_favorite_food
  group by name, address;

Use the same query in merge to change id for some rows:

merge into person_favorite_food a
using (select min(id) id, name, address from person_favorite_food group by name, address) b
on (a.name = b.name and a.address = b.address)
when matched then update set a.id = b.id;

Drop unwanted columns:

alter table person_favorite_food drop (name, address);

Done. Demo in dbfiddle.


问:
How to avoid if statements which returns value based on the input in java 8
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

```<code>RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}
</code>```

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

答:
You can get enum using roleId

```<code>RoleEnum role =
        EnumSet.allOf(RoleEnum.class).stream().filter(r -> r.getId() == roleId).findFirst().orElseThrow();
</code>```

Then use switch-case to get result no conversion needed.

```<code>RoleEnum result;
switch (role) {
  case USER :
    result = RoleEnum.USER_VALIDATION;
    break;
  case ADMIN :
    result = RoleEnum.ADMIN_VALIDATION;
    break;
  case MGR :
    result = RoleEnum.MGR_VALIDATION;
    break;
  default:
    result = null;
 }
</code>```

Body:
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

Body:
You can get enum using roleId

RoleEnum role =
        EnumSet.allOf(RoleEnum.class).stream().filter(r -> r.getId() == roleId).findFirst().orElseThrow();

Then use switch-case to get result no conversion needed.

RoleEnum result;
switch (role) {
  case USER :
    result = RoleEnum.USER_VALIDATION;
    break;
  case ADMIN :
    result = RoleEnum.ADMIN_VALIDATION;
    break;
  case MGR :
    result = RoleEnum.MGR_VALIDATION;
    break;
  default:
    result = null;
 }


问:
Strange behaviour of lambda function inside parallel block in openmp c++
I've started to learn OpenMP for couple of days. I have come across this error that I can't resolve.
I've defined a lambda function f which captures local variable s. Now, If I change the variable s (a private variable to each thread) inside the parallel for loop then the function f doesn't reflect the change in its output and gives always 0. I can understand that I'm doing some error in scoping but unable to find the error.

```<code>#include <iostream>
#include <omp.h>

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

    using namespace std;
    double s;
    auto f =[&]{return s;};

#pragma omp parallel for private(s)
        for(int i = 0; i < 4 ; i++)
    {
        s = 5+i;
        double a1 = f();
#pragma omp critical
        cout << a1 << endl;
    }

    return 0;
}
</code>```

And if I define the lambda inside the parallel for loop, it actually works and returns the proper value of s and not 0, i.e.

```<code>#pragma omp parallel for private(s)
            for(int i = 0; i < 4 ; i++)
        {
            s = 5+i;
            double a1 = [&]{return s;}();
    #pragma omp critical
            cout << a1 << endl;
        }
</code>```

My guess is that the lambda function and the captured variable needs to be in the same scope.
How to fix this if the lambda function is defined outside the parallel block?

答:
I have seen this quite a lot recently that people are using the capture as a way to "work on" some data. Although you can do this, capturing is more generally used to access specific instances of objects (a bit like binding).

I think it is "better" (perhaps more generic), if you can pass your data as a parameter, or if you want to share the data you can pass-by-reference:

So instead of:

```<code>auto f =[&]{return s;};
</code>```

You can do:

```<code>auto f =[](double dbl){return dbl;}; // by copy
auto f =[](double &dbl){return dbl;}; // or by ref
</code>```

And then use like:

```<code>s = 5+i;
double a1 = f(s); // Here pass "s" into the lambda
</code>```

So, I am not saying don't use the capture, sometimes this is good, but it just looks like you are better off here using a parameter.

Body:
I've started to learn OpenMP for couple of days. I have come across this error that I can't resolve.
I've defined a lambda function f which captures local variable s. Now, If I change the variable s (a private variable to each thread) inside the parallel for loop then the function f doesn't reflect the change in its output and gives always 0. I can understand that I'm doing some error in scoping but unable to find the error.

#include <iostream>
#include <omp.h>

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

    using namespace std;
    double s;
    auto f =[&]{return s;};

#pragma omp parallel for private(s)
        for(int i = 0; i < 4 ; i++)
    {
        s = 5+i;
        double a1 = f();
#pragma omp critical
        cout << a1 << endl;
    }

    return 0;
}

And if I define the lambda inside the parallel for loop, it actually works and returns the proper value of s and not 0, i.e.

#pragma omp parallel for private(s)
            for(int i = 0; i < 4 ; i++)
        {
            s = 5+i;
            double a1 = [&]{return s;}();
    #pragma omp critical
            cout << a1 << endl;
        }

My guess is that the lambda function and the captured variable needs to be in the same scope.
How to fix this if the lambda function is defined outside the parallel block?

Body:
I have seen this quite a lot recently that people are using the capture as a way to "work on" some data. Although you can do this, capturing is more generally used to access specific instances of objects (a bit like binding).

I think it is "better" (perhaps more generic), if you can pass your data as a parameter, or if you want to share the data you can pass-by-reference:

So instead of:

auto f =[&]{return s;};

You can do:

auto f =[](double dbl){return dbl;}; // by copy
auto f =[](double &dbl){return dbl;}; // or by ref

And then use like:

s = 5+i;
double a1 = f(s); // Here pass "s" into the lambda

So, I am not saying don't use the capture, sometimes this is good, but it just looks like you are better off here using a parameter.


问:
Retrieve variable from another in ansible
I would like to retrieve the variable from another variable that just been set.

```<code>- set_fact:
    app_env: "{{ app_env | default('prod') }}"
    app_url: "{{ app_global_var_urls[ {{ app_env }} }}"

- name: "Check facts"
  debug:
    msg: "{{ app_env }} {{ app_url }}"
</code>```

I tried out  below methods

{{ app_global_var_urls[ {{ app_env }} }}

{{ app_global_var_urls.app_env }} }}

{{ app_global_var_urls.[ {{ app_env }} ]}}

Is that possible to retrieve from another variable while setting ?

答:
You've got two problems.

First, you never nest Jinja template markers ({{...}}). If you're already inside a Jinja template context, just refer to variables by name.

Second, the variable you create using set_fact aren't available until after the set_fact tasks has finished running. In other words, within a set_fact task you can't refer to variables that you're creating as part of that task.

You'll need to rewrite your playbook to use two separate set_fact tasks:

```<code>- set_fact:
    app_env: "{{ app_env | default('prod') }}"

- set_fact:
    app_url: "{{ app_global_var_urls[ app_env ] }}"
</code>```

Or do something like this:

```<code>- set_fact:
    app_env: "{{ app_env | default('prod') }}"
    app_url: "{{ app_global_var_urls[app_env | default('prod')] }}"
</code>```

Body:
I would like to retrieve the variable from another variable that just been set.

- set_fact:
    app_env: "{{ app_env | default('prod') }}"
    app_url: "{{ app_global_var_urls[ {{ app_env }} }}"

- name: "Check facts"
  debug:
    msg: "{{ app_env }} {{ app_url }}"

I tried out  below methods

{{ app_global_var_urls[ {{ app_env }} }}

{{ app_global_var_urls.app_env }} }}

{{ app_global_var_urls.[ {{ app_env }} ]}}

Is that possible to retrieve from another variable while setting ?

Body:
You've got two problems.

First, you never nest Jinja template markers ({{...}}). If you're already inside a Jinja template context, just refer to variables by name.

Second, the variable you create using set_fact aren't available until after the set_fact tasks has finished running. In other words, within a set_fact task you can't refer to variables that you're creating as part of that task.

You'll need to rewrite your playbook to use two separate set_fact tasks:

- set_fact:
    app_env: "{{ app_env | default('prod') }}"

- set_fact:
    app_url: "{{ app_global_var_urls[ app_env ] }}"

Or do something like this:

- set_fact:
    app_env: "{{ app_env | default('prod') }}"
    app_url: "{{ app_global_var_urls[app_env | default('prod')] }}"


问:
Why does this example TCP Server throw exceptions if it's not closed?
This is written in Groovy by the way

I haven't messed with my TCP Server script in awhile and decided that I want it to stay open and continue listening even after it is used rather than only be good for one use. However, when I do this, it throws an exception and then closes the script anyways.

My example script is as follows:

TCP Server

```<code>def server = new ServerSocket(2000)

println("Waiting for connection")

    server.accept() { socket ->
        socket.withStreams { input, output ->

        w = new BufferedWriter(new OutputStreamWriter(output))
        String message = "Connection was successful"

            r = new BufferedReader(new InputStreamReader(input))

        while(true) {
        if(message !=null) {
            sendMessage(message)
            message = null
        }

        String a = r.readLine()

        if(a.equals("name"))
            message = "Bob"
        else if(a.equals("date"))
            message = new Date()
        else if(a.equals("ip"))
            message = InetAddress.getLocalHost().getHostAddress()
        else if(a.equals("quit")) {
            server.close()
            return
        } else
            message = "$a command unknown"
        }
        }
    }

def sendMessage(String msg) {
    println("Sending: >" + msg + "<")
    w.writeLine(msg)
    w.flush();
}
</code>```

The issue comes in the client. If I use the quit command, then it closes the server once the other commands are done. However if I remove quit from the commands then the server attempts to stay open, throws an exception, and then closes the server anyways.

TCP Client

```<code>def commands
def answers
def requestSocket
def r
def w

String host = "filipekdt7"
commands = ["name",
        "date",
        "ip",
        "quit"]   //If I take out "quit" then the exceptions get thrown, but I want to leave my server script running

answers = [commands.size]

requestSocket = new Socket(host, 2000)

r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()))
w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()))

String message = r.readLine()
println "Server >" + message

for(int n = 0; n < commands.size; n++) {
    sendMessage(commands[n],w)
    answers[n] = r.readLine()
}

w.flush()
w.close()

public String sendMessage(def msg, def w) {
    w.write(msg+"\r\n")
    w.flush()
    println "Client>" + msg
}
</code>```

Does anyone know a way to keep the server script running? I think I'm just over looking something simple.

答:
Try modifying your server code as:

```<code>def server = new ServerSocket(2000)
println("Waiting for connection")

while (true) {
    server.accept() { socket ->
        socket.withStreams { input, output ->
            def w = new BufferedWriter(new OutputStreamWriter(output))
            String message = "Connection was successful"
            def r = new BufferedReader(new InputStreamReader(input))

            while (true) {
                if (message !=null) {
                    sendMessage(message, w)
                    message = null
                }

                String a = r.readLine()
                if (a == null) {
                    socket.close()
                    println "Client disconnected"
                    return
                } else if (a.equals("name")) {
                    message = "Bob"
                } else if (a.equals("date")) {
                    message = new Date()
                } else if (a.equals("ip")) {
                    message = InetAddress.getLocalHost().getHostAddress()
                } else if (a.equals("quit")) {
                    server.close()
                    return
                } else {
                    message = "$a command unknown"
                }
            }
        }
    }
}

def sendMessage(msg, writer) {
    println("Sending: >" + msg + "<")
    writer.writeLine(msg.toString())
    writer.flush();
}
</code>```

Notice how the ServerSocket repeatedly accepts connections in a while loop. This keeps the server script running.

You were getting the exception earlier because you were attempting to send a message to a client that had disconnected from the server. To fix that you should verify that the command read from the client is valid (i.e. a != null), before attempting to send a response back.

Body:
This is written in Groovy by the way

I haven't messed with my TCP Server script in awhile and decided that I want it to stay open and continue listening even after it is used rather than only be good for one use. However, when I do this, it throws an exception and then closes the script anyways.

My example script is as follows:

TCP Server

def server = new ServerSocket(2000)

println("Waiting for connection")

    server.accept() { socket ->
        socket.withStreams { input, output ->

        w = new BufferedWriter(new OutputStreamWriter(output))
        String message = "Connection was successful"

            r = new BufferedReader(new InputStreamReader(input))

        while(true) {
        if(message !=null) {
            sendMessage(message)
            message = null
        }

        String a = r.readLine()

        if(a.equals("name"))
            message = "Bob"
        else if(a.equals("date"))
            message = new Date()
        else if(a.equals("ip"))
            message = InetAddress.getLocalHost().getHostAddress()
        else if(a.equals("quit")) {
            server.close()
            return
        } else
            message = "$a command unknown"
        }
        }
    }

def sendMessage(String msg) {
    println("Sending: >" + msg + "<")
    w.writeLine(msg)
    w.flush();
}

The issue comes in the client. If I use the quit command, then it closes the server once the other commands are done. However if I remove quit from the commands then the server attempts to stay open, throws an exception, and then closes the server anyways.

TCP Client

def commands
def answers
def requestSocket
def r
def w

String host = "filipekdt7"
commands = ["name",
        "date",
        "ip",
        "quit"]   //If I take out "quit" then the exceptions get thrown, but I want to leave my server script running

answers = [commands.size]

requestSocket = new Socket(host, 2000)

r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()))
w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()))

String message = r.readLine()
println "Server >" + message

for(int n = 0; n < commands.size; n++) {
    sendMessage(commands[n],w)
    answers[n] = r.readLine()
}

w.flush()
w.close()

public String sendMessage(def msg, def w) {
    w.write(msg+"\r\n")
    w.flush()
    println "Client>" + msg
}

Does anyone know a way to keep the server script running? I think I'm just over looking something simple.

Body:
Try modifying your server code as:

def server = new ServerSocket(2000)
println("Waiting for connection")

while (true) {
    server.accept() { socket ->
        socket.withStreams { input, output ->
            def w = new BufferedWriter(new OutputStreamWriter(output))
            String message = "Connection was successful"
            def r = new BufferedReader(new InputStreamReader(input))

            while (true) {
                if (message !=null) {
                    sendMessage(message, w)
                    message = null
                }

                String a = r.readLine()
                if (a == null) {
                    socket.close()
                    println "Client disconnected"
                    return
                } else if (a.equals("name")) {
                    message = "Bob"
                } else if (a.equals("date")) {
                    message = new Date()
                } else if (a.equals("ip")) {
                    message = InetAddress.getLocalHost().getHostAddress()
                } else if (a.equals("quit")) {
                    server.close()
                    return
                } else {
                    message = "$a command unknown"
                }
            }
        }
    }
}

def sendMessage(msg, writer) {
    println("Sending: >" + msg + "<")
    writer.writeLine(msg.toString())
    writer.flush();
}

Notice how the ServerSocket repeatedly accepts connections in a while loop. This keeps the server script running.

You were getting the exception earlier because you were attempting to send a message to a client that had disconnected from the server. To fix that you should verify that the command read from the client is valid (i.e. a != null), before attempting to send a response back.


问:
autoconf: best practice for including `libftdi` in `configure.ac`
Hello everybody out there using GNU autoconf,

What is the best practice to look for libftdi and including it with autoconf for compiling a C program using it?

The following snippet from a configure.ac file works, but I'm not sure, whether it is best practice:

```<code>PKG_CHECK_MODULES([LIBFTDI], [libftdi])
#AC_CHECK_LIB([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_SEARCH_LIBS([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_CHECK_HEADERS([ftdi.h],[],[echo "error: missing libftdi header files" && exit 1])
LIBS="-lftdi $LIBS $LDFLAGS" # works, but is this the best way?
</code>```

I'm building the program with autoconf (GNU Autoconf) 2.69 and compiling it with gcc version 7.5.0 on Ubuntu 18.04.

答:
Why your other attempts failed

Library tests

Your commented-out AC_CHECK_LIB and AC_SEARCH_LIBS examples do not demonstrate correct usage.  Usage details are presented in the manual, but to sum up:

the arguments to AC_CHECK_LIB are

The simple name of the library, i.e. ftdi

The name of a characteristic function provided by the library

(optional) Code for configure to execute in the event that the library is found.  Default is to prepend a link option to $LIBS and define a HAVE_LIB* preprocessor macro.

(optional) Code for configure to execute in the event that the library is not found

(optional) Additional library link options (not already in $LIBS) that are needed to link a program that uses the library being checked

the arguments to AC_SEARCH_LIBS are

The name of the function to search for

A list of one or more library names to search

(optional) Code for configure to execute in the event that the library is found, in addition to prepending a link option to $LIBS (but not defining any preprocessor macro)

(optional) Code for configure to execute in the event that the library is not found

(optional) Additional library link options (not already in $LIBS that are needed to link a program that uses the library being checked

Neither your AC_CHECK_LIB example nor your AC_SEARCH_LIBS example properly designates an existing libftdi function to check for. Moreover, the third argument in each case is unlikely to be valid shell / Autoconf code, so in the event that the library were found, configure would probably crash.  Better might be:

```<code>AC_CHECK_LIB([ftdi], [ftdi_init])
</code>```

or

```<code>AC_SEARCH_LIBS([ftdi_init], [ftdi])
</code>```

Depending on what exactly you want to do, on details of libftdi, and on the configure.ac context, you might need to provide appropriate values for some or all of the optional arguments.

The main reasons for a library check to fail despite the library in fact being installed are

the library being installed in a location that is not in the default search path

the library having link dependencies on other libraries, and those have not (yet) been accounted for at the time of the check

The former is analogous to header installation location considerations discussed in the next section.  The latter can be addressed by adding explicit extra link flags via the fifth argument to AC_CHECK_LIB or AC_SEARCH_LIBS, but is more often addressed semi-automatically by performing AC_CHECK_LIB or AC_SEARCH_LIBS tests in reverse prerequisite order, so that the value of LIBS is built up with an appropriately-ordered list of link flags, ready at each point to support the next check, and ultimately appropriate for supporting the overall compilation.

Note also that libftdi provides both C and C++ interfaces.  In ftdi_init, I have been careful to choose a function that has C linkage, so as to avoid C++ name-mangling issues (see How to test a C++ library usability in configure.in?).  You may also need to ensure that the tests are run with the C compiler (see Language Choice in the Autoconf manual).

Header test

Your AC_CHECK_HEADERS usage, on the other hand, does not appear to be inherently wrong.  If the resulting configure script does not detect ftdi.h, then that implies that the header isn't in the compiler's default header search path.  That might happen, for example, if it is installed in a subdirectory, such as /usr/include/ftdi.  This would be a matter of both ftdi and system installation convention.

If it is ftdi convention for the headers to be installed in a subdirectory, then your source files should specify that in their #include directives:

```<code>#include <ftdi/ftdi.h>
</code>```

If your source files in fact do that, then that should also be what you tell Autoconf to look for:

```<code>AC_CHECK_HEADERS([ftdi/ftdi.h])
</code>```

Regardless of whether a subdirectory prefix is expected or used, it is good practice to accommodate the possibility of headers and / or libraries being installed in a non-standard location.  Although one can always do that by specifying appropriate flags in the CPPFLAGS variable in configure's environment, I prefer and recommend using AC_ARG_WITH to designate a --with argument or AC_ARG_VAR to designate an environment variable that configure will consult for the purpose.  For example,

```<code>AC_ARG_WITH([ftdi-includedir],
  [AS_HELP_STRING([--with-ftdiincludedir=dir],
    [specifies a custom directory for the libftdi header files])],
  [CPPFLAGS="$CPPFLAGS -I$withval"]
)
</code>```

Exposing an argument or environment variable for the specific purpose highlights (in the output of ./configure --help) the fact that this is a knob that the user might need to adjust.  Additionally, receiving the include directory via a for-purpose vector is sometimes useful for limiting in which compilations the designated include directory is made available.

On PKG_CHECK_MODULES

The Autotools objective and philosophy is to support the widest possible array of build machines and environments by minimizing external dependencies and writing the most portable configuration and build code possible.  To this end, the Autotools are designed so that they themselves are not required to build projects on supported systems.  Rather, Autoconf produces configure as a stand-alone, highly portable shell script, and Automake produces configurable templates for highly portable makefiles.  These are intended to be included in source packages, to be used as-is on each build system.  Making your configure script dependent on pkg-config being installed on every system where your project is to be built, as using PKG_CHECK_MODULES does, conflicts with those objectives.

How significant an issue that may be is a subject of some dispute.  Where it is available, pkg-config can be very useful, especially for components that require complex build flags.  PKG_CHECK_MODULES is thus very convenient for both package maintainer and package builder on those systems where it is present or readily available, for those components that provide pkg-config metadata.

But pkg-config is not necessarily available for every system targeted by your software.  It cannot reasonably be assumed present or obtainable even on systems for which it is nominally available.  And even on systems that have it, pkg-config metadata for the libraries of interest are not necessarily installed with the libraries.

As such, I urge you to avoid using PKG_CHECK_MODULES in your Autoconf projects. You need to know how to do without it in any case, because it is not an option for some libraries.  Where appropriate, provide hooks by which the builder can supply appropriate flags, and let them choose whether to use pkg-config in conjunction with those.  Decoupling configure from pkg-config in this way makes a bit more work for you, and in some cases for builders, but it is more flexible.

Your PKG_CHECK_MODULES example

Your example invocation appears ok in itself, supposing that "libftdi" is the appropriate pkg-config module name (you have to know the appropriate name):

```<code>PKG_CHECK_MODULES([LIBFTDI], [libftdi])
</code>```

But although that may yield a configure script that runs successfully, it does not, in itself, do much for you.  In particular, it verifies that pkg-config metadata for the named module is present, but

it does not verify the presence or test the use of the library or header

although it does set some output variables containing compile and link flags, you do not appear to be using those

specifically, if you're going to rely on pkg-config, then you should use the link flags it reports to you instead of hardcoding -lftdi, and that alone.

Furthermore, it is more typical to use the output variables created by PKG_CHECK_MODULES in your makefile than to use them to update $LIBS or other general variables inside configure.  If you do use them in configure, however, then it is essential to understand that LIBS and LDFLAGS have different roles with little overlap.  It is generally inappropriate, not to mention unnecessary, to include the LDFLAGS in LIBS.  If you want to update LIBS inside configure, then this would be the way to do it:

```<code>LIBS="$LIBFTDI_LIBS $LIBS"
</code>```

And if you're going to do that, then you probably should do the same with the compiler flags reported by pkg-config, if any:

```<code>CFLAGS="$CFLAGS $LIBFTDI_CFLAGS"
</code>```

Body:
Hello everybody out there using GNU autoconf,

What is the best practice to look for libftdi and including it with autoconf for compiling a C program using it?

The following snippet from a configure.ac file works, but I'm not sure, whether it is best practice:

PKG_CHECK_MODULES([LIBFTDI], [libftdi])
#AC_CHECK_LIB([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_SEARCH_LIBS([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_CHECK_HEADERS([ftdi.h],[],[echo "error: missing libftdi header files" && exit 1])
LIBS="-lftdi $LIBS $LDFLAGS" # works, but is this the best way?

I'm building the program with autoconf (GNU Autoconf) 2.69 and compiling it with gcc version 7.5.0 on Ubuntu 18.04.

Body:
Why your other attempts failed

Library tests

Your commented-out AC_CHECK_LIB and AC_SEARCH_LIBS examples do not demonstrate correct usage.  Usage details are presented in the manual, but to sum up:

the arguments to AC_CHECK_LIB are

The simple name of the library, i.e. ftdi

The name of a characteristic function provided by the library

(optional) Code for configure to execute in the event that the library is found.  Default is to prepend a link option to $LIBS and define a HAVE_LIB* preprocessor macro.

(optional) Code for configure to execute in the event that the library is not found

(optional) Additional library link options (not already in $LIBS) that are needed to link a program that uses the library being checked

the arguments to AC_SEARCH_LIBS are

The name of the function to search for

A list of one or more library names to search

(optional) Code for configure to execute in the event that the library is found, in addition to prepending a link option to $LIBS (but not defining any preprocessor macro)

(optional) Code for configure to execute in the event that the library is not found

(optional) Additional library link options (not already in $LIBS that are needed to link a program that uses the library being checked

Neither your AC_CHECK_LIB example nor your AC_SEARCH_LIBS example properly designates an existing libftdi function to check for. Moreover, the third argument in each case is unlikely to be valid shell / Autoconf code, so in the event that the library were found, configure would probably crash.  Better might be:

AC_CHECK_LIB([ftdi], [ftdi_init])

or

AC_SEARCH_LIBS([ftdi_init], [ftdi])

Depending on what exactly you want to do, on details of libftdi, and on the configure.ac context, you might need to provide appropriate values for some or all of the optional arguments.

The main reasons for a library check to fail despite the library in fact being installed are

the library being installed in a location that is not in the default search path

the library having link dependencies on other libraries, and those have not (yet) been accounted for at the time of the check

The former is analogous to header installation location considerations discussed in the next section.  The latter can be addressed by adding explicit extra link flags via the fifth argument to AC_CHECK_LIB or AC_SEARCH_LIBS, but is more often addressed semi-automatically by performing AC_CHECK_LIB or AC_SEARCH_LIBS tests in reverse prerequisite order, so that the value of LIBS is built up with an appropriately-ordered list of link flags, ready at each point to support the next check, and ultimately appropriate for supporting the overall compilation.

Note also that libftdi provides both C and C++ interfaces.  In ftdi_init, I have been careful to choose a function that has C linkage, so as to avoid C++ name-mangling issues (see How to test a C++ library usability in configure.in?).  You may also need to ensure that the tests are run with the C compiler (see Language Choice in the Autoconf manual).

Header test

Your AC_CHECK_HEADERS usage, on the other hand, does not appear to be inherently wrong.  If the resulting configure script does not detect ftdi.h, then that implies that the header isn't in the compiler's default header search path.  That might happen, for example, if it is installed in a subdirectory, such as /usr/include/ftdi.  This would be a matter of both ftdi and system installation convention.

If it is ftdi convention for the headers to be installed in a subdirectory, then your source files should specify that in their #include directives:

#include <ftdi/ftdi.h>

If your source files in fact do that, then that should also be what you tell Autoconf to look for:

AC_CHECK_HEADERS([ftdi/ftdi.h])

Regardless of whether a subdirectory prefix is expected or used, it is good practice to accommodate the possibility of headers and / or libraries being installed in a non-standard location.  Although one can always do that by specifying appropriate flags in the CPPFLAGS variable in configure's environment, I prefer and recommend using AC_ARG_WITH to designate a --with argument or AC_ARG_VAR to designate an environment variable that configure will consult for the purpose.  For example,

AC_ARG_WITH([ftdi-includedir],
  [AS_HELP_STRING([--with-ftdiincludedir=dir],
    [specifies a custom directory for the libftdi header files])],
  [CPPFLAGS="$CPPFLAGS -I$withval"]
)

Exposing an argument or environment variable for the specific purpose highlights (in the output of ./configure --help) the fact that this is a knob that the user might need to adjust.  Additionally, receiving the include directory via a for-purpose vector is sometimes useful for limiting in which compilations the designated include directory is made available.

On PKG_CHECK_MODULES

The Autotools objective and philosophy is to support the widest possible array of build machines and environments by minimizing external dependencies and writing the most portable configuration and build code possible.  To this end, the Autotools are designed so that they themselves are not required to build projects on supported systems.  Rather, Autoconf produces configure as a stand-alone, highly portable shell script, and Automake produces configurable templates for highly portable makefiles.  These are intended to be included in source packages, to be used as-is on each build system.  Making your configure script dependent on pkg-config being installed on every system where your project is to be built, as using PKG_CHECK_MODULES does, conflicts with those objectives.

How significant an issue that may be is a subject of some dispute.  Where it is available, pkg-config can be very useful, especially for components that require complex build flags.  PKG_CHECK_MODULES is thus very convenient for both package maintainer and package builder on those systems where it is present or readily available, for those components that provide pkg-config metadata.

But pkg-config is not necessarily available for every system targeted by your software.  It cannot reasonably be assumed present or obtainable even on systems for which it is nominally available.  And even on systems that have it, pkg-config metadata for the libraries of interest are not necessarily installed with the libraries.

As such, I urge you to avoid using PKG_CHECK_MODULES in your Autoconf projects. You need to know how to do without it in any case, because it is not an option for some libraries.  Where appropriate, provide hooks by which the builder can supply appropriate flags, and let them choose whether to use pkg-config in conjunction with those.  Decoupling configure from pkg-config in this way makes a bit more work for you, and in some cases for builders, but it is more flexible.

Your PKG_CHECK_MODULES example

Your example invocation appears ok in itself, supposing that "libftdi" is the appropriate pkg-config module name (you have to know the appropriate name):

PKG_CHECK_MODULES([LIBFTDI], [libftdi])

But although that may yield a configure script that runs successfully, it does not, in itself, do much for you.  In particular, it verifies that pkg-config metadata for the named module is present, but

it does not verify the presence or test the use of the library or header

although it does set some output variables containing compile and link flags, you do not appear to be using those

specifically, if you're going to rely on pkg-config, then you should use the link flags it reports to you instead of hardcoding -lftdi, and that alone.

Furthermore, it is more typical to use the output variables created by PKG_CHECK_MODULES in your makefile than to use them to update $LIBS or other general variables inside configure.  If you do use them in configure, however, then it is essential to understand that LIBS and LDFLAGS have different roles with little overlap.  It is generally inappropriate, not to mention unnecessary, to include the LDFLAGS in LIBS.  If you want to update LIBS inside configure, then this would be the way to do it:

LIBS="$LIBFTDI_LIBS $LIBS"

And if you're going to do that, then you probably should do the same with the compiler flags reported by pkg-config, if any:

CFLAGS="$CFLAGS $LIBFTDI_CFLAGS"


问:
Time complexity (Pythagorean Triples)
I have written two different algorithms to calculate Pythagorean Triples:

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

class Untitled {
  public static void main(String[] args) {

    int n = 20;

    System.out.println("--------------------");
    algorithmOne(n);
    System.out.println("--------------------\n");
    algorithmTwo(n);
    System.out.println("--------------------");
  }

  public static void algorithmOne(int n){

    long startTime = System.nanoTime();

    for (int i = 1 ; i <= n ; i++) {
      for (int j = 1 ; j <= n ; j++) {
        for (int k = 1; k <= n ; k++) {
          if (Math.pow(i,2) + Math.pow(j,2) == Math.pow(k,2)) {
            System.out.println(i + "," + j + "," + k);
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");
  }

  public static void algorithmTwo(int n){

    long startTime = System.nanoTime();

    ArrayList<Integer> squares = new ArrayList<>();

    // O(n)
    for(int i = 1 ; ; i++) {
      if ((int)Math.sqrt(i) > n) {
        break;
      }
      if (Math.sqrt(i) == (int)Math.sqrt(i)) {
        squares.add(i);
      }
    }

    // O(n^3)
    for (int i = 0 ; i < squares.size() ; i++) {
      for (int j = 0 ; j < squares.size() ; j++) {
        for (int k = 0 ; k < squares.size() ; k++) {
          if (squares.get(i) + squares.get(j) == squares.get(k)) {
            System.out.println((int)Math.sqrt(squares.get(i)) + "," + (int)Math.sqrt(squares.get(j)) + "," + (int)Math.sqrt(squares.get(k)));
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");

  }
}
</code>```

I believe both algorithms are O(n^3), however when I calculate the time they take to run, the second algorithm is a lot faster. using n=20, algorithm1 takes about 60 milliseconds and algorithms takes about 5 milliseconds. How can these two algorithms have the same time complexity, but one runs faster than the other? I understand that the second algorithm doesn't have to iterate over as many numbers in the triple for loop, but shouldn't that mean that the time complexity would be less?

答:
You have to understand complexity first.

Lets take an example.

Suppose you have a bag that can contain 5 kg apple but doesn't matter how many(in number) apples are there. It will contain 5 kg but it can be 20 apple or it can be 5 apple.

So, when we talk about time-complexity then you talk about the amount (in kg) not the number of apple(it can be memory-complexity).

That means when you are talking about big-Oh then you have to know what it means.
by O(n3) means it takes at most that amount. So, it can compute every steps but at most n3 or it can skip some steps but still it will take at most n3. I think, now it is clear to you why I am using at most.

Your second algorithm is skipping some steps but your first algorithm is not. So you second algorithm runs a little bit faster but in big-Oh sense it can take at most that amount (O(n3)) and still size of the lists matters.

Additional info:

```<code>That is called Pythagorean triple. O(|result|) solution exists.
You can look it up on Wikipedia.
Also learn Stern-Brocot tree that is the essential part to write the most optimal case.
To learn the theory, search rational points on circle.
Not an easy topic but helps if you know a little geometry.
</code>```

Title: Time complexity (Pythagorean Triples)

Body:
I have written two different algorithms to calculate Pythagorean Triples:

import java.util.*;

class Untitled {
  public static void main(String[] args) {

    int n = 20;

    System.out.println("--------------------");
    algorithmOne(n);
    System.out.println("--------------------\n");
    algorithmTwo(n);
    System.out.println("--------------------");
  }

  public static void algorithmOne(int n){

    long startTime = System.nanoTime();

    for (int i = 1 ; i <= n ; i++) {
      for (int j = 1 ; j <= n ; j++) {
        for (int k = 1; k <= n ; k++) {
          if (Math.pow(i,2) + Math.pow(j,2) == Math.pow(k,2)) {
            System.out.println(i + "," + j + "," + k);
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");
  }

  public static void algorithmTwo(int n){

    long startTime = System.nanoTime();

    ArrayList<Integer> squares = new ArrayList<>();

    // O(n)
    for(int i = 1 ; ; i++) {
      if ((int)Math.sqrt(i) > n) {
        break;
      }
      if (Math.sqrt(i) == (int)Math.sqrt(i)) {
        squares.add(i);
      }
    }

    // O(n^3)
    for (int i = 0 ; i < squares.size() ; i++) {
      for (int j = 0 ; j < squares.size() ; j++) {
        for (int k = 0 ; k < squares.size() ; k++) {
          if (squares.get(i) + squares.get(j) == squares.get(k)) {
            System.out.println((int)Math.sqrt(squares.get(i)) + "," + (int)Math.sqrt(squares.get(j)) + "," + (int)Math.sqrt(squares.get(k)));
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");

  }
}

I believe both algorithms are O(n^3), however when I calculate the time they take to run, the second algorithm is a lot faster. using n=20, algorithm1 takes about 60 milliseconds and algorithms takes about 5 milliseconds. How can these two algorithms have the same time complexity, but one runs faster than the other? I understand that the second algorithm doesn't have to iterate over as many numbers in the triple for loop, but shouldn't that mean that the time complexity would be less?

Body:
You have to understand complexity first.

Lets take an example.

Suppose you have a bag that can contain 5 kg apple but doesn't matter how many(in number) apples are there. It will contain 5 kg but it can be 20 apple or it can be 5 apple.

So, when we talk about time-complexity then you talk about the amount (in kg) not the number of apple(it can be memory-complexity).

That means when you are talking about big-Oh then you have to know what it means.
by O(n3) means it takes at most that amount. So, it can compute every steps but at most n3 or it can skip some steps but still it will take at most n3. I think, now it is clear to you why I am using at most.

Your second algorithm is skipping some steps but your first algorithm is not. So you second algorithm runs a little bit faster but in big-Oh sense it can take at most that amount (O(n3)) and still size of the lists matters.

Additional info:

That is called Pythagorean triple. O(|result|) solution exists.
You can look it up on Wikipedia.
Also learn Stern-Brocot tree that is the essential part to write the most optimal case.
To learn the theory, search rational points on circle.
Not an easy topic but helps if you know a little geometry.


问:
How to write text on image from form input in Laravel using intervention
I want to create image with text using Intervention from input form,how Do I do that here is my controller</p>

```<code>public function store(Request $request)

        if($request->hasFile('content'))
        {
          $filenameWithExt = $request->file('content')->getClientOriginalName();
          $filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
          $extension = $request->file('content')->getClientOriginalExtension();
          $fileNameToStore = $filename.'_'.time().'.'.$extension;
          $path = $request->file('content')->storeAs('public/content',$fileNameToStore);
        }
        else
        {
            $fileNameToStore = 'No Image,Music and Video selected please! check and try again.';
        }

        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->subcategory_id = implode(',',$request->input('subcategory_id') );
        $post->user_id = auth()->user()->id;
        $post->content = $fileNameToStore;
        $post->save();

    }
</code>```

答:
```<code>$image = Input::file('image');

// Define File Name and Path
$filename  = time() . '.' . $image->getClientOriginalExtension();
$path = ('image/path/' . $filename);

// create Image from Input
$img = Image::make($image->getRealPath());

// write text
$img->text('The quick brown fox jumps over the lazy dog.');

// write text at position x , y
$img->text('The quick brown fox jumps over the lazy dog.', 120, 100);

// use callback to define details
$img->text('foo', 0, 0, function($font) {
    $font->file('foo/bar.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

// draw transparent text
$img->text('foo', 0, 0, function($font) {
    $font->color(array(255, 255, 255, 0.5));
});

// Save Image to Path

$img->save($path);
</code>```

Body:
I want to create image with text using Intervention from input form,how Do I do that here is my controller

public function store(Request $request)

        if($request->hasFile('content'))
        {
          $filenameWithExt = $request->file('content')->getClientOriginalName();
          $filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
          $extension = $request->file('content')->getClientOriginalExtension();
          $fileNameToStore = $filename.'_'.time().'.'.$extension;
          $path = $request->file('content')->storeAs('public/content',$fileNameToStore);
        }
        else
        {
            $fileNameToStore = 'No Image,Music and Video selected please! check and try again.';
        }

        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->subcategory_id = implode(',',$request->input('subcategory_id') );
        $post->user_id = auth()->user()->id;
        $post->content = $fileNameToStore;
        $post->save();

    }


问:
Program is not asking 3 questions and uses my answer to the first question for the other two
I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third. </p>

```<code>#include <iostream>
using namespace std;
int main()
{

    char first_name;
    cout << "Please enter a name: ";
    cin >> first_name;
    cout << first_name << endl;

    char second_name;
    cout << "Please enter a name: ";
    cin >> second_name;
    cout << second_name << endl;

    char third_name;
    cout << "Please enter a name: ";
    cin >> third_name;
    cout << third_name << endl;

    return 0;
}
</code>```

答:
You tried to hold a lot of chars (one word) in one char who can hold only one char.

```<code>#include <iostream>
#include <string> // We need a string, container to hold a chars. Something like array of chars but have a few difference.

using namespace std; // You should avoid using this but in that short code this doesn't matter

int main()
{
    // You don't need separate container for this code
    // Then we create one container to holds all of inputs
    string input;

    cout << "Please enter a name: ";
    cin >> input; // Put input from user in our input(string)
    cout << input << endl; // Print input

    // Next code is the same as above
    cout << "Please enter a name: ";
    cin >> input;
    cout << input << endl;

    cout << "Please enter a name: ";
    cin >> input;
    cout << input << endl;

    return 0;
}
</code>```

I special avoided a few elements like using function because this must be simple as possible.

Body:
I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third.

#include <iostream>
using namespace std;
int main()
{

    char first_name;
    cout << "Please enter a name: ";
    cin >> first_name;
    cout << first_name << endl;

    char second_name;
    cout << "Please enter a name: ";
    cin >> second_name;
    cout << second_name << endl;

    char third_name;
    cout << "Please enter a name: ";
    cin >> third_name;
    cout << third_name << endl;

    return 0;
}

Body:
You tried to hold a lot of chars (one word) in one char who can hold only one char.

#include <iostream>
#include <string> // We need a string, container to hold a chars. Something like array of chars but have a few difference.

using namespace std; // You should avoid using this but in that short code this doesn't matter

int main()
{
    // You don't need separate container for this code
    // Then we create one container to holds all of inputs
    string input;

    cout << "Please enter a name: ";
    cin >> input; // Put input from user in our input(string)
    cout << input << endl; // Print input

    // Next code is the same as above
    cout << "Please enter a name: ";
    cin >> input;
    cout << input << endl;

    cout << "Please enter a name: ";
    cin >> input;
    cout << input << endl;

    return 0;
}

I special avoided a few elements like using function because this must be simple as possible.


问:
How to inject React Component inside WebView (react-native-webview)?
Is there a way to pass in a web React component to WebView directly? Something like this-</p>

```<code>import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView>
</code>```

答:
if you want to load HTML directly, you can use the html property in WebView’s source property, as shown below:

```<code><WebView
  originWhitelist={['*']}
  source={{ html: '<h1>Hello world</h1>' }}
/>
</code>```

for more details of react-native-web-view you can learn from here

https://blog.logrocket.com/the-complete-guide-to-react-native-webview/

https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md

Body:
Is there a way to pass in a web React component to WebView directly? Something like this-

import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView>

Body:
if you want to load HTML directly, you can use the html property in WebView’s source property, as shown below:

<WebView
  originWhitelist={['*']}
  source={{ html: '<h1>Hello world</h1>' }}
/>

for more details of react-native-web-view you can learn from here

https://blog.logrocket.com/the-complete-guide-to-react-native-webview/

https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md


问:
Django-rest-framework will not send user registration activation email

My DRF app using rest-auth and allauth wont send new user email activation mail despite these settings.

All I get is a console log that an email was sent after registration but nothing hits a user email.Please advise.

Also, I use gmail and I have enabled unsecured-apps in my gmail account to send emails.

settings.py

```<code>EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = get_secret('EMAIL_ADDRESS')
EMAIL_HOST_PASSWORD = get_secret('EMAIL_PASSWORD')
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_AUTHENTICATION_METHOD = 'username'

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'coin_app.apps.CoinAppConfig',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'allauth.socialaccount',
]
</code>```

My dev-environment

```<code>Django==3.0.3
django-allauth==0.41.0
django-cors-headers==3.2.1
django-rest-auth==0.9.5
djangorestframework==3.11.0
djangorestframework-jwt==1.11.0
</code>```

答:
I noticed that your EMAIL_BACKEND is set to testing mode for console not smtp. You must change it as follows:</p>

```<code>EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
</code>```

Body:
My DRF app using rest-auth and allauth wont send new user email activation mail despite these settings.

All I get is a console log that an email was sent after registration but nothing hits a user email.Please advise.

Also, I use gmail and I have enabled unsecured-apps in my gmail account to send emails.

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = get_secret('EMAIL_ADDRESS')
EMAIL_HOST_PASSWORD = get_secret('EMAIL_PASSWORD')
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_AUTHENTICATION_METHOD = 'username'

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'coin_app.apps.CoinAppConfig',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'allauth.socialaccount',
]

My dev-environment

Django==3.0.3
django-allauth==0.41.0
django-cors-headers==3.2.1
django-rest-auth==0.9.5
djangorestframework==3.11.0
djangorestframework-jwt==1.11.0

Body:
I noticed that your EMAIL_BACKEND is set to testing mode for console not smtp. You must change it as follows:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'


问:
Change kubernetes stroge class mounted value from another pod
I want to publish sonarqube with kubernetes. I did successfully with official packages. But i want to use some plugins old version and some custom plugins. In local with docker-compose files, i created a fly-away container that fills the plugins directory(/opt/sonarqube/extensions/plugins) with plugins. And use that volume with sonarqube container. As a conclusion : Sonarqube extensions volume directory is created (or filled) from different container(do the job and die).

I want to use the same path with kubernetes but couldn't do that. My flyaway container didn't fill the path.

My kubernetes deployments files:

1-) sonar-pvc-extensions.yml

```<code>kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: claim-sonar-extensions
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi
</code>```

2-) sonarqube-deployment.yml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube
  template:
    metadata:
      name: sonarqube
      labels:
        name: sonarqube
    spec:
      containers:
        - image: sonarqube:7.9.1-community
          name: sonarqube
          env:
            - name: SONARQUBE_JDBC_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-pwd
                  key: password
            - name: SONARQUBE_JDBC_URL
              value: jdbc:postgresql://sonar-postgres:5432/sonar
          ports:
            - containerPort: 9000
              name: sonarqube
          volumeMounts:
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
          resources:
            requests:
              memory: 2000Mi
            limits:
              memory: 2000Mi
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
      initContainers:
        - name: sysctl
          image: busybox
          imagePullPolicy: IfNotPresent
          command: ['sysctl', '-w', 'vm.max_map_count=262144']
          securityContext:
            privileged: true
</code>```

3-)Sample plugins Dockerfile

```<code>FROM alpine:3.4

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

ENV PLUGINS_DIR /opt/sonarqube/extensions/plugins

WORKDIR $PLUGINS_DIR
RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
RUN wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar
RUN wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
ENV JAVASCRIPT_VERSION 2.20.0.4207

VOLUME $PLUGINS_DIR

CMD ls -asl $PLUGINS_DIR
</code>```

I tried that approach with sonar-plugin-deployment.yml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube-plugin
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube-plugin
  template:
    metadata:
      name: sonarqube-plugin
      labels:
        name: sonarqube-plugin
    spec:
      containers:
        - image: my-kubernetes-registry/plugins
          name: sonarqube-plugins
          volumeMounts:
            # This name must match the volumes.name below.
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
</code>```

But didn't successed. And break something. This time my plugins directory became empty:

```<code>sonarqube@sonarqube-85b98d9845-l2sql:/opt/sonarqube/extensions/plugins$ ls -al
total 24
drwxr-xr-x 3 root      root       4096 May 30 16:19 .
drwxr-xr-x 1 sonarqube sonarqube  4096 May 30 16:39 ..
drwx------ 2 root      root      16384 May 30 16:19 lost+found
</code>```

I am not using persistent volume. PVC is looking to stroge class. So i cant use accessModes as ReadWriteMany.

As a results: I want to change a stroge path with a fly-away container and use that path inside an app.

I am noob to kubernetes if you suggest a different approach i will be apreciated.

答: Are you sure, you want to use the same directory for container volume mounts and to store the plugins. I believe this is causing a conflict. Can you try changing the volume mount directory (in deployment container spec)?</p>

Body:
I want to publish sonarqube with kubernetes. I did successfully with official packages. But i want to use some plugins old version and some custom plugins. In local with docker-compose files, i created a fly-away container that fills the plugins directory(/opt/sonarqube/extensions/plugins) with plugins. And use that volume with sonarqube container. As a conclusion : Sonarqube extensions volume directory is created (or filled) from different container(do the job and die).

I want to use the same path with kubernetes but couldn't do that. My flyaway container didn't fill the path.

My kubernetes deployments files:

1-) sonar-pvc-extensions.yml

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: claim-sonar-extensions
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi

2-) sonarqube-deployment.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube
  template:
    metadata:
      name: sonarqube
      labels:
        name: sonarqube
    spec:
      containers:
        - image: sonarqube:7.9.1-community
          name: sonarqube
          env:
            - name: SONARQUBE_JDBC_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-pwd
                  key: password
            - name: SONARQUBE_JDBC_URL
              value: jdbc:postgresql://sonar-postgres:5432/sonar
          ports:
            - containerPort: 9000
              name: sonarqube
          volumeMounts:
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
          resources:
            requests:
              memory: 2000Mi
            limits:
              memory: 2000Mi
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
      initContainers:
        - name: sysctl
          image: busybox
          imagePullPolicy: IfNotPresent
          command: ['sysctl', '-w', 'vm.max_map_count=262144']
          securityContext:
            privileged: true

3-)Sample plugins Dockerfile

FROM alpine:3.4

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

ENV PLUGINS_DIR /opt/sonarqube/extensions/plugins

WORKDIR $PLUGINS_DIR
RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
RUN wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar
RUN wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
ENV JAVASCRIPT_VERSION 2.20.0.4207

VOLUME $PLUGINS_DIR

CMD ls -asl $PLUGINS_DIR

I tried that approach with sonar-plugin-deployment.yml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube-plugin
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube-plugin
  template:
    metadata:
      name: sonarqube-plugin
      labels:
        name: sonarqube-plugin
    spec:
      containers:
        - image: my-kubernetes-registry/plugins
          name: sonarqube-plugins
          volumeMounts:
            # This name must match the volumes.name below.
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions

But didn't successed. And break something. This time my plugins directory became empty:

sonarqube@sonarqube-85b98d9845-l2sql:/opt/sonarqube/extensions/plugins$ ls -al
total 24
drwxr-xr-x 3 root      root       4096 May 30 16:19 .
drwxr-xr-x 1 sonarqube sonarqube  4096 May 30 16:39 ..
drwx------ 2 root      root      16384 May 30 16:19 lost+found

I am not using persistent volume. PVC is looking to stroge class. So i cant use accessModes as ReadWriteMany.

As a results: I want to change a stroge path with a fly-away container and use that path inside an app.

I am noob to kubernetes if you suggest a different approach i will be apreciated.