问:
Windows Forms Application Performance
My app has many controls on its surface, and more are added dynamically at runtime.

Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).

What are your tips and tricks to improve WinForms app performance?

答:
Although, I'm not sure how these approaches could apply when resizing a window.

Handle the ResizeBegin and ResizeEnd events to call SuspendLayout() and ResumeLayout().  These events are only on the System.Windows.Form class (although I wish they were also on Control).

OwnerDisplayName: Shuft

Title: Windows Forms Application Performance

OwnerDisplayName: Brian Ensink


来源: stackexchange

问:
In Delphi: How to skip sections of code while debugging?
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

```<code>function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;
</code>```

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

答:
If you're jumping into FastMM code, then there are memory operations occurring. The code you've shown doesn't have any memory operations, so your question is incomplete. I'll try to guess at what you meant.

When a subroutine has local variables of compiler-managed types (such as strings, interfaces, or dynamic arrays), the function prologue has non-trivial work to do. The prologue is also where reference counts of input parameters are adjusted. The debugger represents the prologue in the begin line of the function. If the current execution point is that line, and you "step into" it, you'll be taken to the RTL code for managing the special types. (I wouldn't expect FastMM to be involved there, either, but maybe things have changed from what I'm used to.) One easy thing to do in that situation is to "step over" the begin line instead of into it; use F8.

If you're really pressing F7 when entering your highlighted line, then you're doing it wrong. That's stepping into the begin line, not the line where DoStuff is called. So whether you get taken to the FastMM code has nothing to do with the implementation of DoStuff. To debug the call to DoStuff, the current execution point should already be the line with the call on it.

If you only want to debug DoStuff on iteration 23498938, then you can set a conditional breakpoint in that function. Click in the gutter to make a normal breakpoint, and then right-click it to display its properties. There you can define a condition that will be evaluated every time execution reaches that point. The debugger will only stop there when the condition is true. Press F8 to "step over" the DoStuff call, and if the condition is true, the debugger will stop there as though you'd pressed F7 instead.

You can toggle the "use debug DCUs" option to avoid stepping into most RTL and VCL units. I don't know whether FastMM is included in that set. The key difference is whether the DCUs you've linked to were compiled with debug information. The setting alters the library path to include or exclude the subdirectory where the debug DCUs are. I think you can configure the set of included or excluded debug directories so that a custom set of directories is added or removed based on the "debug DCUs" setting.

Back to breakpoints. You can set up breakpoint groups by assigning names to your breakpoints. You can use an advanced breakpoint to enable or disable a named group of breakpoints when you pass it. (Breakpoint groups can have just one breakpoint, if you want.) So, for example, if you only want to break at location X if you've also passed some other location Y in your program, you could set a disabled breakpoint at X and a non-breaking breakpoint at Y. Set the "enable groups" setting at Y to enable group X.

You can also take advantage of disabled breakpoints without automatic enabling and disabling. Your breakpoints appear in the "breakpoints" debugger window. If you're stepping through DoStuff and you decide you want to inspect bla this time, go to the breakpoint window and enable the breakpoint at bla. No need to navigate to bla's implementation to set the breakpoint there.

For more about advanced breakpoints, see Using Non-Breaking Breakpoints in Delphi, and article by Cary Jensen from a few years ago.

OwnerDisplayName: Wouter van Nifterick

ContentLicense: CC BY-SA 2.5

Body:
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

LastEditorDisplayName: Wouter van Nifterick

OwnerDisplayName: Rob Kennedy

LastEditorDisplayName: Rob Kennedy


问:
Why is this Perl script using the File::Tail module not working?
I'm working on a simple Perl script to monitor a log file using the File::Tail module, but I can't seem to get the module working properly.

The idea is to use it over IRC, but this didn't seem to work so after tinkering with the interactive interpreter I've narrowed the problem down to File::Tail. I've cut it down the following basic example to monitor the file and nothing happens at all when new entries are appended to the file:

```<code>#!/usr/bin/perl -w

use strict;

use File::Tail;

my $file = File::Tail->new("/var/log/apache2/error.log");

while(defined(my $line = $file->read))
{
    print "$line\n";
}
</code>```

Can anyone suggest what the problem might be? I've gone through the perldoc entry and this is virtually copied from there so I can't really see that I've made any glaring errors. I'm running Ubuntu Lucid.

答: Is it possible that this is a permissions error? Can the user you're running the script as access /var/log/apache2/error.log?

Body:
I'm working on a simple Perl script to monitor a log file using the File::Tail module, but I can't seem to get the module working properly.

The idea is to use it over IRC, but this didn't seem to work so after tinkering with the interactive interpreter I've narrowed the problem down to File::Tail. I've cut it down the following basic example to monitor the file and nothing happens at all when new entries are appended to the file:

#!/usr/bin/perl -w

use strict;

use File::Tail;

my $file = File::Tail->new("/var/log/apache2/error.log");

while(defined(my $line = $file->read))
{
    print "$line\n";
}

Can anyone suggest what the problem might be? I've gone through the perldoc entry and this is virtually copied from there so I can't really see that I've made any glaring errors. I'm running Ubuntu Lucid.


问:
Typeahead data is not shown at the text box and no results at the network tab
I was working on a script using jquery ui autocomplete, but it seems not working, so someone add a script to help me using typeahead.js library, here is his answer:

```<code><script>
$(function() {
  $("#searchTxt").typeahead({
    source: function(query, process) {
      var textVal=$("#searchTxt").val();
      $.ajax({
        url: '/php/autoComplete.php', // Please add full URL here
        type: 'POST',
        data: 'term=' + textVal,
        dataType: 'JSON',
        async: true,
        success: function(data) {
          process(data);
          console.log(textVal);
        }
      });
    }
  });
});
</script>
</code>```

I added it like it is and changed my PHP script to:

```<code>$cid = $_SESSION['clinic_id'];

$searchTxt = '%'.$_REQUEST['term'].'%';
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid and patient_name_en LIKE :searchTxt OR dob LIKE :searchTxt OR patient_id LIKE :searchTxt OR patient_phone LIKE :searchTxt OR unhcr_registration_number LIKE :searchTxt ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->bindValue(':searchTxt', $searchTxt);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
</code>```

I added the libraries (I am using bootstrap 4 so I downloaded the typeaheadjs.css library for it):

```<code><link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">
<link rel="stylesheet" href="../css/typeaheadjs.css">
<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery-ui.js"></script>
<script src="../js/typeahead.bundle.js"></script>
</code>```

Now when I type in the searchTxt text box: I can't see any output at the network tab neither at the text box as results. (No errors at the console).

答:
Please refer this demo #5

```<code>$('#demo5').typeahead({
    ajax: {
            url: '/cities/list',
            triggerLength: 1
          }
});
</code>```

autocomplete.php should return json format of data as below

```<code>[
  {
    id: 1,
    name: 'John'
  },
  {
    id: 2,
    name: 'Alex'
  },
  {
    id: 3,
    name: 'Terry'
  }
]
</code>```

Demo link

Documentation link

Github Link

Hope you will get it.

ContentLicense: CC BY-SA 3.0

Body:
I was working on a script using jquery ui autocomplete, but it seems not working, so someone add a script to help me using typeahead.js library, here is his answer:

I added it like it is and changed my PHP script to:

$cid = $_SESSION['clinic_id'];

$searchTxt = '%'.$_REQUEST['term'].'%';
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid and patient_name_en LIKE :searchTxt OR dob LIKE :searchTxt OR patient_id LIKE :searchTxt OR patient_phone LIKE :searchTxt OR unhcr_registration_number LIKE :searchTxt ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->bindValue(':searchTxt', $searchTxt);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);

I added the libraries (I am using bootstrap 4 so I downloaded the typeaheadjs.css library for it):

<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">
<link rel="stylesheet" href="../css/typeaheadjs.css">

Now when I type in the searchTxt text box: I can't see any output at the network tab neither at the text box as results. (No errors at the console).

Body:
Please refer this demo #5

$('#demo5').typeahead({
    ajax: {
            url: '/cities/list',
            triggerLength: 1
          }
});

autocomplete.php should return json format of data as below

[
  {
    id: 1,
    name: 'John'
  },
  {
    id: 2,
    name: 'Alex'
  },
  {
    id: 3,
    name: 'Terry'
  }
]

Demo link

Documentation link

Github Link

Hope you will get it.


问:
Add and Remove Strikethrough of TextView Android
Hello guys I'm having an issue putting strikethrough in my textview. This is what I'm doing right now:

```<code>  private void initControls() {

    tvNote = (TextView) findViewById (R.id.textView1);
    tvNote.setVisibility(View.GONE);

    fillData();

}

private void fillData() {

      dbConnect();

      // Array list of sync data items
      ArrayList<SyncDataItems> itemList = new ArrayList<SyncDataItems>();

      List<Todos> todos = dbHelper.getAllTodos();

      SyncDataItems _items;

      for (Todos cn : todos) {
          String log = "ID: " + cn.getID() + " , Todo: " + cn.getTodo();
          Log.e("Todo List ", log);
          _items = new SyncDataItems(cn.getTodo(), cn.getTodo(), true);
          itemList.add(_items);
      }

      dataAdapter = new MyCustomAdapter(this, R.layout.item_info, itemList);
      listView = (ListView) findViewById(R.id.listView1);
      // Assign adapter to ListView
      listView.setAdapter(dataAdapter);

      if(dataAdapter.getCount() == 0) {
          tvNote.setVisibility(View.VISIBLE);
          tvNote.setText("No Records Yet");
      }

}

  private class MyCustomAdapter extends ArrayAdapter<SyncDataItems> {

      private ArrayList<SyncDataItems> itemList;

      public MyCustomAdapter(Context context, int textViewResourceId,

      ArrayList<SyncDataItems> itemList) {
       super(context, textViewResourceId, itemList);
           this.itemList = new ArrayList<SyncDataItems>();
           this.itemList.addAll(itemList);
      }

      private class ViewHolder {
           TextView code;
           CheckBox name;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {

            holder = null;

            Log.v("ConvertView", String.valueOf(position));

            if (convertView == null) {

                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                convertView = vi.inflate(R.layout.item_info, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);

                convertView.setTag(holder);

                holder.name.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        SyncDataItems _item = (SyncDataItems) cb.getTag();

                        _item.setSelected(cb.isChecked());

                        holder.name.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                if ( isChecked ) {
                                    Log.e("TAG", "Checked!");
                                    holder.code.append("Checked!");
                                    holder.code.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                } else {
                                    holder.code.setPaintFlags(holder.code.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
                                    Log.e("TAG", "Unchecked!");
                                }
                            }
                        });

                    }
                });

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final SyncDataItems item = itemList.get(position);

            holder.code.setText(item.getItem());
            holder.name.setChecked(item.isSelected());

            holder.name.setTag(item);

            return convertView;
        }

}
</code>```

But the strikethrough effect is not working when I check or uncheck the checkbox. any ideas? Your help will be truly appreciated. Thanks.

答:
shortest way to remove strike through any text which is part of some view</p>

```<code>tvNote.setPaintFlags(0);
</code>```

Body:
Hello guys I'm having an issue putting strikethrough in my textview. This is what I'm doing right now:

  private void initControls() {

    tvNote = (TextView) findViewById (R.id.textView1);
    tvNote.setVisibility(View.GONE);

    fillData();

}

private void fillData() {

      dbConnect();

      // Array list of sync data items
      ArrayList<SyncDataItems> itemList = new ArrayList<SyncDataItems>();

      List<Todos> todos = dbHelper.getAllTodos();

      SyncDataItems _items;

      for (Todos cn : todos) {
          String log = "ID: " + cn.getID() + " , Todo: " + cn.getTodo();
          Log.e("Todo List ", log);
          _items = new SyncDataItems(cn.getTodo(), cn.getTodo(), true);
          itemList.add(_items);
      }

      dataAdapter = new MyCustomAdapter(this, R.layout.item_info, itemList);
      listView = (ListView) findViewById(R.id.listView1);
      // Assign adapter to ListView
      listView.setAdapter(dataAdapter);

      if(dataAdapter.getCount() == 0) {
          tvNote.setVisibility(View.VISIBLE);
          tvNote.setText("No Records Yet");
      }

}

  private class MyCustomAdapter extends ArrayAdapter<SyncDataItems> {

      private ArrayList<SyncDataItems> itemList;

      public MyCustomAdapter(Context context, int textViewResourceId,

      ArrayList<SyncDataItems> itemList) {
       super(context, textViewResourceId, itemList);
           this.itemList = new ArrayList<SyncDataItems>();
           this.itemList.addAll(itemList);
      }

      private class ViewHolder {
           TextView code;
           CheckBox name;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {

            holder = null;

            Log.v("ConvertView", String.valueOf(position));

            if (convertView == null) {

                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                convertView = vi.inflate(R.layout.item_info, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);

                convertView.setTag(holder);

                holder.name.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        SyncDataItems _item = (SyncDataItems) cb.getTag();

                        _item.setSelected(cb.isChecked());

                        holder.name.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                if ( isChecked ) {
                                    Log.e("TAG", "Checked!");
                                    holder.code.append("Checked!");
                                    holder.code.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                } else {
                                    holder.code.setPaintFlags(holder.code.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
                                    Log.e("TAG", "Unchecked!");
                                }
                            }
                        });

                    }
                });

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final SyncDataItems item = itemList.get(position);

            holder.code.setText(item.getItem());
            holder.name.setChecked(item.isSelected());

            holder.name.setTag(item);

            return convertView;
        }

}

But the strikethrough effect is not working when I check or uncheck the checkbox. any ideas? Your help will be truly appreciated. Thanks.

Body:
shortest way to remove strike through any text which is part of some view

tvNote.setPaintFlags(0);


问:
Enter key event handler on react-bootstrap Input component
I have an Input component with a button (buttonAfter property), I set an onClick handler associated to the button and so user can type some text and clic the button to fire the right action.

However, I would like user to be able to press [Enter] key (keycode 13) to achieve the same effect as clicking on the button, just to make the UI easier to use.

I could not find a way to do it, of course I tried onKeydown to register an handler for key down event but it is just ignored.

答:
The question can also be related to React-bootstrap.
React-bootstrap also has a way to handle instance when ever a button or enter key or any form element is pressed.

The below code explains how to handle an instance when enterkey is pressed without the involvement of React Handlers.(and that makes it cool)

```<code>import React from "react";
import ReactDOM from "react-dom";
import { FormGroup, FormControl } from "react-bootstrap";

class TestInput extends Component {

  search() {
    console.log("Enter Button Pressed");
  }

  render() {
    return (
      <FormGroup>

        <InputGroup>
          <FormControl
            placeholder="Press Enter"
            type="input"
            onKeyPress={event => {
              if (event.key === "Enter") {
                this.search();
              }
            }}
          />
        </InputGroup>

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

React Bootstrap does not support Input form element anymore.
Instead it introduced below items at your disposal

The FormGroup component wraps a form control with proper spacing, along with support for a label, help text, and validation state.

Wrap your form control in an InputGroup, then use for normal add-ons and for button add-ons.

The FormControl component renders a form control with Bootstrap styling.

References:

https://react-bootstrap.github.io/components.html#forms
https://react-bootstrap.github.io/components.html#forms-input-groups

Body:
The question can also be related to React-bootstrap.
React-bootstrap also has a way to handle instance when ever a button or enter key or any form element is pressed.

The below code explains how to handle an instance when enterkey is pressed without the involvement of React Handlers.(and that makes it cool)

import React from "react";
import ReactDOM from "react-dom";
import { FormGroup, FormControl } from "react-bootstrap";

class TestInput extends Component {

  search() {
    console.log("Enter Button Pressed");
  }

  render() {
    return (
      <FormGroup>

        <InputGroup>
          <FormControl
            placeholder="Press Enter"
            type="input"
            onKeyPress={event => {
              if (event.key === "Enter") {
                this.search();
              }
            }}
          />
        </InputGroup>

      </FormGroup>
    );
  }
}

React Bootstrap does not support Input form element anymore.
Instead it introduced below items at your disposal

The FormGroup component wraps a form control with proper spacing, along with support for a label, help text, and validation state.

Wrap your form control in an InputGroup, then use for normal add-ons and for button add-ons.

The FormControl component renders a form control with Bootstrap styling.

References:

https://react-bootstrap.github.io/components.html#forms
https://react-bootstrap.github.io/components.html#forms-input-groups


问:
if multiple threads are updating the same variable, what should be done so each thread updates the variable correctly?
If multiple threads are updating the same variable, what should I do so each thread updates the variable correctly?

Any help would be greatly appreciated

答:
There are several options:

1) Using no synchronization at all

This can only work if the data is of primitive type (not long/double), and you don't care about reading stale values (which is unlikely)

2) Declaring the field as volatile

This will guarantee that stale values are never read. It also works fine for objects (assuming the objects aren't changed after creation), because of the happens-before guarantees of volatile variables (See "Java Memory Model").

3) Using java.util.concurrent.AtomicLong, AtomicInteger etc

They are all thread safe, and support special operations like atomic incrementation and atomic compare-and-set operations.

4) Protecting reads and writes with the same lock

This approach provides mutual exclusion, which allows defining a large atomic operation, where multiple data members are manipulated as a single operation.


问:
Running function without events in render
I'm new with ReactJS and want to ask how functions works here. I have a class, function and render like this :

```<code>class MainTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      results: []
    };
    this.getREST = this.getREST.bind(this);
  }
  getREST() {
    console.log(this.props.str)
    axios.get(this.props.str)
      .then(res => {
        const results = res.data.results.map(obj => obj);
        this.setState({results});
    });
    console.log(this.state.results);
  }
  render() {
    return (
      <Table hover striped bordered hover responsive size="sm">
        <thead>
          <tr>
            <th>Name</th>
            <th>Name</th>
            <th>Name</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {this.state.results.map(result =>
            <tr key={result.Name}>
              <td>{result.Name}</td>
              <td>{result.Name}</td>
              <td>{result.Name}</td>
              <td>{result.Name}</td>
            </tr>
          )}
        </tbody>
      </Table>
    );
  }
}
</code>```

I can run getRest() function with button event using something like this

```<code><button onClick={this.handleClick.bind(this)} value="Click me" />
</code>```

But how can i run getRest() function without any events, just in render()?

答:
You should fetch your data in componentDidMount lifecycle method, not in render.

```<code>componentDidMount(){
      axios.get(this.props.str)
      .then(res => {
        const results = res.data.results.map(obj => obj);
        this.setState({results});
    });
}
</code>```

Body:
I'm new with ReactJS and want to ask how functions works here. I have a class, function and render like this :

class MainTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      results: []
    };
    this.getREST = this.getREST.bind(this);
  }
  getREST() {
    console.log(this.props.str)
    axios.get(this.props.str)
      .then(res => {
        const results = res.data.results.map(obj => obj);
        this.setState({results});
    });
    console.log(this.state.results);
  }
  render() {
    return (

            Name
            Name
            Name
            Name

          {this.state.results.map(result =>

              {result.Name}
              {result.Name}
              {result.Name}
              {result.Name}

          )}

    );
  }
}

I can run getRest() function with button event using something like this

<button onClick={this.handleClick.bind(this)} value="Click me" />

But how can i run getRest() function without any events, just in render()?

Body:
You should fetch your data in componentDidMount lifecycle method, not in render.

componentDidMount(){
      axios.get(this.props.str)
      .then(res => {
        const results = res.data.results.map(obj => obj);
        this.setState({results});
    });
}


问:
"Driver is not defined" Python/Selenium
I want to use Selenium on Python but I have an alert message:

driver-webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe") NameError: name 'driver' is not defined

I have installed the Chrome Driver, what else must I do ?

答:
```<code>driver = webdriver.Chrome(path_to_your_chromedriver.exe)
</code>```

If chromedriver is in your PATH you dont have to specify. Remember to use double slashes - or put an r in front of the chromedriver path

```<code>... = webdriver.Chrome(r'path_without_doubble_slashes)
</code>```

Title: "Driver is not defined" Python/Selenium

Body:
driver = webdriver.Chrome(path_to_your_chromedriver.exe)

If chromedriver is in your PATH you dont have to specify. Remember to use double slashes - or put an r in front of the chromedriver path

... = webdriver.Chrome(r'path_without_doubble_slashes)


问:
Draw a simple circle uiimage
I try to make a 20x20 UIImage with a simple blue circle.
I try with this function, but the result is a blue circle in a black square.
How do I remove the black square around the circle?

Function:

```<code>+ (UIImage *)blueCircle {
    static UIImage *blueCircle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(20.f, 20.f), YES, 0.0f);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSaveGState(ctx);

        CGRect rect = CGRectMake(0, 0, 20, 20);
        CGContextSetFillColorWithColor(ctx, [UIColor cyanColor].CGColor);
        CGContextFillEllipseInRect(ctx, rect);

        CGContextRestoreGState(ctx);
        blueCircle = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

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

actual result:

答:
Try this </p>

```<code>UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
</code>```

Title: Draw a simple circle uiimage

Body:
I try to make a 20x20 UIImage with a simple blue circle.
I try with this function, but the result is a blue circle in a black square.
How do I remove the black square around the circle?

Function:

+ (UIImage *)blueCircle {
    static UIImage *blueCircle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(20.f, 20.f), YES, 0.0f);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSaveGState(ctx);

        CGRect rect = CGRectMake(0, 0, 20, 20);
        CGContextSetFillColorWithColor(ctx, [UIColor cyanColor].CGColor);
        CGContextFillEllipseInRect(ctx, rect);

        CGContextRestoreGState(ctx);
        blueCircle = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

    });
    return blueCircle;
}

actual result:

Body:
Try this

UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);


问:
Creating all possible pairs from elements in a list and then sorting them evenly
So I have 3 to 8 players, I want each one to play against all the others 1 vs 1.
The matches are done sequentially one at a time.
The ordering within a pair isn't important (a vs b == b vs a).

I'm creating the matchup pairs in a simple nested loop, in which I loop over the players and pair the current index with all the following indexes.

The problem is that player 1 will play all his matches and then have nothing to do, while player 8 will have to wait.

Is there any way to evenly distribute the pairs, so all players have equal downtime?

I'm currently randomizing the array containing the pairs, but I'm looking for a better way.

答:
You can use a Round-robin tournament scheduling algorithm.

The circle method is the standard algorithm to create a schedule for a
  round-robin tournament. All competitors are assigned to numbers, and
  then paired in the first round:

Round 1. (1 plays 14, 2 plays 13, ... )

```<code> 1  2  3  4  5  6  7
14 13 12 11 10  9  8
</code>```

then fix one of the contributors in the first or last column of the table (number one in this example) and
  rotate the others clockwise one position

Round 2. (1 plays 13, 14 plays 12, ... )

```<code> 1 14  2  3  4  5  6
13 12 11 10  9  8  7
</code>```

Round 3. (1 plays 12, 13 plays 11, ... )

```<code> 1 13 14  2  3  4  5
12 11 10  9  8  7  6
</code>```

until you end up almost back at the initial position

Round 13. (1 plays 2, 3 plays 14, ... )

```<code> 1  3  4  5  6  7  8
 2 14 13 12 11 10  9
</code>```

Body:
You can use a Round-robin tournament scheduling algorithm.

The circle method is the standard algorithm to create a schedule for a
  round-robin tournament. All competitors are assigned to numbers, and
  then paired in the first round:

Round 1. (1 plays 14, 2 plays 13, ... )

 1  2  3  4  5  6  7
14 13 12 11 10  9  8

then fix one of the contributors in the first or last column of the table (number one in this example) and
  rotate the others clockwise one position

Round 2. (1 plays 13, 14 plays 12, ... )

 1 14  2  3  4  5  6
13 12 11 10  9  8  7

Round 3. (1 plays 12, 13 plays 11, ... )

 1 13 14  2  3  4  5
12 11 10  9  8  7  6

until you end up almost back at the initial position

Round 13. (1 plays 2, 3 plays 14, ... )

 1  3  4  5  6  7  8
 2 14 13 12 11 10  9


问:
Truncating a byte array vs. substringing the Encoded string coming out of SHA-256
I am not familiar with Hashing algorithms and the risks associated when using them and therefore have a question on the answer below that I received on a previous question . . .

Based on the comment that the hash value must, when encoded to ASCII, fit within 16 ASCI characters, the solution is first, to choose some cryptographic hash function (the SHA-2 family includes SHA-256, SHA-384, and SHA-512)
  then, to truncate the output of the chosen hash function to 96 bits (12 bytes) - that is, keep the first 12 bytes of the hash function output and discard the remaining bytes
  then, to base-64-encode the truncated output to 16 ASCII characters (128 bits)
  yielding effectively a 96-bit-strong cryptographic hash.

If I substring the base-64-encoded string to 16 characters is that fundamentally different then keeping the first 12 bytes of the hash function and then base-64-encoding them? If so, could someone please explain (provide example code) for truncating the byte array?

I tested the substring of the full hash value against 36,000+ distinct values and had no collisions. The code below  is my current implementation.

Thanks for any help (and clarity) you can provide.

```<code>public static byte[] CreateSha256Hash(string data)
{
    byte[] dataToHash = (new UnicodeEncoding()).GetBytes(data);
    SHA256 shaM = new SHA256Managed();
    byte[] hashedData = shaM.ComputeHash(dataToHash);

    return hashedData;
}

public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row)
{
    byte[] hashedData = CreateSha256Hash(Row.HashString);

    string s = Convert.ToBase64String(hashedData, Base64FormattingOptions.None);

    Row.HashValue = s.Substring(0, 16);

}
</code>```

[Original post]
(http://stackoverflow.com/questions/4340471/is-there-a-hash-algorithm-that-produces-a-hash-size-of-64-bits-in-c)

答:
Truncating is as easy as adding Take(12) here:

Change

```<code> byte[] hashedData = CreateSha256Hash(Row.HashString);
</code>```

To:

```<code> byte[] hashedData = CreateSha256Hash(Row.HashString).Take(12).ToArray();
</code>```

Body:
I am not familiar with Hashing algorithms and the risks associated when using them and therefore have a question on the answer below that I received on a previous question . . .

Based on the comment that the hash value must, when encoded to ASCII, fit within 16 ASCI characters, the solution is first, to choose some cryptographic hash function (the SHA-2 family includes SHA-256, SHA-384, and SHA-512)
  then, to truncate the output of the chosen hash function to 96 bits (12 bytes) - that is, keep the first 12 bytes of the hash function output and discard the remaining bytes
  then, to base-64-encode the truncated output to 16 ASCII characters (128 bits)
  yielding effectively a 96-bit-strong cryptographic hash.

If I substring the base-64-encoded string to 16 characters is that fundamentally different then keeping the first 12 bytes of the hash function and then base-64-encoding them? If so, could someone please explain (provide example code) for truncating the byte array?

I tested the substring of the full hash value against 36,000+ distinct values and had no collisions. The code below  is my current implementation.

Thanks for any help (and clarity) you can provide.

public static byte[] CreateSha256Hash(string data)
{
    byte[] dataToHash = (new UnicodeEncoding()).GetBytes(data);
    SHA256 shaM = new SHA256Managed();
    byte[] hashedData = shaM.ComputeHash(dataToHash);

    return hashedData;
}

public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row)
{
    byte[] hashedData = CreateSha256Hash(Row.HashString);

    string s = Convert.ToBase64String(hashedData, Base64FormattingOptions.None);

    Row.HashValue = s.Substring(0, 16);

}

[Original post]
(http://stackoverflow.com/questions/4340471/is-there-a-hash-algorithm-that-produces-a-hash-size-of-64-bits-in-c)

Body:
Truncating is as easy as adding Take(12) here:

Change

 byte[] hashedData = CreateSha256Hash(Row.HashString);

To:

 byte[] hashedData = CreateSha256Hash(Row.HashString).Take(12).ToArray();


问:
How to output JSON for WordPress search page using Relevanssi?
I'm using the WordPress search plugin Relevanssi.

I'm trying to customise my search.php template to output JSON, like so:

```<code><?php

header('Content-Type: application/json');

$results = array();

if (have_posts()):
  while (have_posts()):
    the_post();
    $results[] = array(
      'permalink' => get_permalink(),
      'title' => get_the_title()
    );
  endwhile;
endif;

echo json_encode($results);

die();

?>
</code>```

However, I'm getting an error that headers are already sent.

Warning: Cannot modify header information - headers already sent by
  (output started at
  /Applications/MAMP/htdocs/NBC/wp-content/plugins/relevanssi/lib/search.php:554)
  in /Applications/MAMP/htdocs/NBC/wp-content/themes/NBC/search.php on
  line 3

Is there a better way to do this? The reason I need it as JSON is that I want to consume it with JS.

I have done this before on an older site, so perhaps the issues are with the latest version I'm using? 3.5.11

Note that the query DOES return results, but I get these errors on the page too, which causes me to receive invalid JSON data back.

Thanks!

答:
The issue goes away if I turn off WP_DEBUG in wp-config.php

```<code>define('WP_DEBUG', false);
</code>```

It must be something to do with WordPress internals that I don't understand.

Body:
I'm using the WordPress search plugin Relevanssi.

I'm trying to customise my search.php template to output JSON, like so:

<?php

header('Content-Type: application/json');

$results = array();

if (have_posts()):
  while (have_posts()):
    the_post();
    $results[] = array(
      'permalink' => get_permalink(),
      'title' => get_the_title()
    );
  endwhile;
endif;

echo json_encode($results);

die();

?>

However, I'm getting an error that headers are already sent.

Warning: Cannot modify header information - headers already sent by
  (output started at
  /Applications/MAMP/htdocs/NBC/wp-content/plugins/relevanssi/lib/search.php:554)
  in /Applications/MAMP/htdocs/NBC/wp-content/themes/NBC/search.php on
  line 3

Is there a better way to do this? The reason I need it as JSON is that I want to consume it with JS.

I have done this before on an older site, so perhaps the issues are with the latest version I'm using? 3.5.11

Note that the query DOES return results, but I get these errors on the page too, which causes me to receive invalid JSON data back.

Thanks!

Body:
The issue goes away if I turn off WP_DEBUG in wp-config.php

define('WP_DEBUG', false);

It must be something to do with WordPress internals that I don't understand.


问:
should the app first start with the default language?
I have created 4 languages for the app. I can change the Lauaguage, ok, but if close the app and then start I it again, the app starts atfirst with the default string.xml.

How to let the app starts with the last selected Language ?

should I call the the methode by OnCreate in the mainActivity ?

```<code>     @SuppressWarnings("deprecation")
    public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        Configuration conf = getResources().getConfiguration();
        conf.locale = myLocale;
        getResources().updateConfiguration(conf, dm);
        Intent refresh = new Intent(this, Languages.class);
        startActivity(refresh);
        /*         "en" = English
            "hi" =Hindi
            "fr" =French
            "it" =Italian
            "de" =German
            "es" =Spanish
            "ja" =Japanese
            "ko" =Korean
            "nl" =Dutch
            "pt" =Portuguese
            "ru" =Russian
            "zh" =Chinese
            "ar" = arabic
   */
    }
</code>```

How can the user change the default language ?

答:
I have used a long Way like below but it works. Thanks :

OnResume :

```<code>    selected_lang= myshared.getString("selected_lang","de");
    lang_found= Integer.parseInt(myshared.getString("lang_found","0"));
setLocale(selected_lang);

@SuppressWarnings("deprecation")
public void setLocale(String lang) {
    Locale myLocale = new Locale(lang);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    Configuration conf = getResources().getConfiguration();
    conf.locale = myLocale;
    getResources().updateConfiguration(conf, dm);

    if(lang_found==0) {
        Intent refresh = new Intent(this, MainActivity.class);
        startActivity(refresh);
        lang_found=1;
    }

@Override
protected void onDestroy() {

    lang_found=0;
    Save_setting();
    super.onDestroy();
}
</code>```

Body:
I have created 4 languages for the app. I can change the Lauaguage, ok, but if close the app and then start I it again, the app starts atfirst with the default string.xml.

How to let the app starts with the last selected Language ?

should I call the the methode by OnCreate in the mainActivity ?

     @SuppressWarnings("deprecation")
    public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        Configuration conf = getResources().getConfiguration();
        conf.locale = myLocale;
        getResources().updateConfiguration(conf, dm);
        Intent refresh = new Intent(this, Languages.class);
        startActivity(refresh);
        /*         "en" = English
            "hi" =Hindi
            "fr" =French
            "it" =Italian
            "de" =German
            "es" =Spanish
            "ja" =Japanese
            "ko" =Korean
            "nl" =Dutch
            "pt" =Portuguese
            "ru" =Russian
            "zh" =Chinese
            "ar" = arabic
   */
    }

How can the user change the default language ?

Body:
I have used a long Way like below but it works. Thanks :

OnResume :

    selected_lang= myshared.getString("selected_lang","de");
    lang_found= Integer.parseInt(myshared.getString("lang_found","0"));
setLocale(selected_lang);

@SuppressWarnings("deprecation")
public void setLocale(String lang) {
    Locale myLocale = new Locale(lang);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    Configuration conf = getResources().getConfiguration();
    conf.locale = myLocale;
    getResources().updateConfiguration(conf, dm);

    if(lang_found==0) {
        Intent refresh = new Intent(this, MainActivity.class);
        startActivity(refresh);
        lang_found=1;
    }

@Override
protected void onDestroy() {

    lang_found=0;
    Save_setting();
    super.onDestroy();
}


问:
does false sharing occur when data is read in openmp?
If I have a C++ program with OpenMP parallelization, where different threads constantly use some small shared array only for reading data from it, does false sharing occur in this case? in other words, is false sharing related only to memory write operations, or it can also happen with memory read operations.

答: Typically used cache coherence protocols, such as MESI (modified, exclusive, shared, invalid), have a specific state for cache lines called "shared". Cache lines are in this state if they are read by multiple processors. Each processor then has a copy of the cache line and can safely read from it without false-sharing. On a write, all processors are informed to invalidate the cache line which is the main cause for false-sharing</p>


问:
HTML - change image inside frame and keep frame size intact
My main goal is to have a simple frame (as you can see) with few text lines and images. The thing I want to do, is make this frame flexible. By that I mean - if I change picture inside of it (bigger -> smaller) the frame should change. It should stay fixed.

Online editor: https://www.bootply.com/Y09Zn1wir3#

HTML:

```<code><div class="col-md-4">
  <div class="single-image-wrap">
    <div class="single-image">
      <div class="name">NAME</div>
      <div class="img-wrap">
        <img src="https://cdn.pixabay.com/photo/2013/07/12/14/07/basketball-147794_960_720.png" class="first-image">
      </div>
      <div class="extra-info">
        <div class="bottom-text">ABC</div>
      </div>
    </div>
  </div>
</div>

<div class="col-md-4">
  <div class="single-image-wrap">
    <div class="single-image">
      <div class="name">NAME</div>
      <div class="img-wrap">
        <img src="https://cdn.pixabay.com/photo/2013/07/12/14/07/basketball-147794_960_720.png" class="second-image">
      </div>
      <div class="extra-info">
        <div class="bottom-text">ABC</div>
      </div>
    </div>
  </div>
</div>
</code>```

CSS:

```<code>/* CSS used here will be applied after bootstrap.css */
.single-image{
    border: 1px solid orange;
    width: 100%;
    text-align: center;
    margin: 0px 0px 15px 0px;
    float: right;
}

.name{
    padding: 20px 0px 0px 0px;
    color: black;
    height: 75px;
    font-size: 18px;
}

.img-wrap{
    padding-bottom: 50px;
    padding-top: 25px;
}

.first-image{
    width: 200px;
}

.second-image{
    width: 150px;
}

.extra-info{
    border-top: 1px solid orange;
}

.bottom-text{
    padding-top: 15px;
    height: 50px;
    letter-spacing: 0.1em;
}
</code>```

I tried to add height property to such as:

.single-image{
    ...
    height: 405px;
}

Result: https://www.codeply.com/go/2s2hH3nbju

But it doesn't look correct, as bottom text floats somewhere up.
I need a solution for different type of image sizes. Any ideas?

答:
You need to set the height of .img-wrap, too.

```<code>.single-image{
  border: 1px solid orange;
  width: 100%;
  text-align: center;
  margin: 0px 0px 15px 0px;
  float: right;
  height: 405px;
}

.img-wrap{
  padding-bottom: 50px;
  padding-top: 25px;
  height:250px;
  overflow:hidden;
}
</code>```

Body:
My main goal is to have a simple frame (as you can see) with few text lines and images. The thing I want to do, is make this frame flexible. By that I mean - if I change picture inside of it (bigger -> smaller) the frame should change. It should stay fixed.

Online editor: https://www.bootply.com/Y09Zn1wir3#

HTML:

NAME

ABC

NAME

ABC

CSS:

/* CSS used here will be applied after bootstrap.css */
.single-image{
    border: 1px solid orange;
    width: 100%;
    text-align: center;
    margin: 0px 0px 15px 0px;
    float: right;
}

.name{
    padding: 20px 0px 0px 0px;
    color: black;
    height: 75px;
    font-size: 18px;
}

.img-wrap{
    padding-bottom: 50px;
    padding-top: 25px;
}

.first-image{
    width: 200px;
}

.second-image{
    width: 150px;
}

.extra-info{
    border-top: 1px solid orange;
}

.bottom-text{
    padding-top: 15px;
    height: 50px;
    letter-spacing: 0.1em;
}

I tried to add height property to such as:

.single-image{
    ...
    height: 405px;
}

Result: https://www.codeply.com/go/2s2hH3nbju

But it doesn't look correct, as bottom text floats somewhere up.
I need a solution for different type of image sizes. Any ideas?

Body:
You need to set the height of .img-wrap, too.

.single-image{
  border: 1px solid orange;
  width: 100%;
  text-align: center;
  margin: 0px 0px 15px 0px;
  float: right;
  height: 405px;
}

.img-wrap{
  padding-bottom: 50px;
  padding-top: 25px;
  height:250px;
  overflow:hidden;
}


问:
xcode debugging goes back and forth during stepping through the code
I have a really weird problem with Xcode 3.2.5

In a normal code sequence XCode steps couple of lines back then continues, then again sometimes back and continues again during step mode.

This only happens in one project, but there in all files. Here an example:

When jumping in this function Xcode goes through the lines in the following sequence:
2 -> 1 -> 2 -> 3 ->5 -> 8 -> 3 -> 4 -> 5 -> 6 -> 7 ->...

I dont understand what is going on here. Please do you have any idea?

Rebooting the machine and the iPhone doesn't help.

By the way, the complete code works fine and runs without errors. It seems that the cursor sometimes goes to lines where the code is not being executed. If a certain line is entered twice by the cursor, only the second time it changes the variables in assignments etc..

Really weird!

Thanks for any hint...

```<code> 1  - (void)viewWillAppear:(BOOL)animated {
 // D_IN;
 2  [super viewWillAppear:animated];

 //get the dataManager global Object, so we always have a structured accesss to the data!
3 WebiAppDelegate *mainDelegate = (WebiAppDelegate *)[[UIApplication sharedApplication]delegate];
4 self.webiDataManager = mainDelegate.webiDataManager;

5 message.hidden = YES;
6 message.text = @"";
7 message.userInteractionEnabled = NO;
...
</code>```

答:
I agree with the comments.  It looks like you're trying to debug optimized code.  Try compiling with no optimization and the debugger should behave more sensibly.

e.g. gcc -O0 ...

Body:
I have a really weird problem with Xcode 3.2.5

In a normal code sequence XCode steps couple of lines back then continues, then again sometimes back and continues again during step mode.

This only happens in one project, but there in all files. Here an example:

When jumping in this function Xcode goes through the lines in the following sequence:
2 -> 1 -> 2 -> 3 ->5 -> 8 -> 3 -> 4 -> 5 -> 6 -> 7 ->...

I dont understand what is going on here. Please do you have any idea?

Rebooting the machine and the iPhone doesn't help.

By the way, the complete code works fine and runs without errors. It seems that the cursor sometimes goes to lines where the code is not being executed. If a certain line is entered twice by the cursor, only the second time it changes the variables in assignments etc..

Really weird!

Thanks for any hint...

 1  - (void)viewWillAppear:(BOOL)animated {
 // D_IN;
 2  [super viewWillAppear:animated];

 //get the dataManager global Object, so we always have a structured accesss to the data!
3 WebiAppDelegate *mainDelegate = (WebiAppDelegate *)[[UIApplication sharedApplication]delegate];
4 self.webiDataManager = mainDelegate.webiDataManager;

5 message.hidden = YES;
6 message.text = @"";
7 message.userInteractionEnabled = NO;
...


问:
how do you change some id or textlike the id of a textview everywhere in android studio
My problem is that when I have completed my app and then want to change the id of some textview I have to do it one by one everywhere in the main activity. Thats horrible ! Is there a way to just search and select all the Id's and change them altogether. I hope you guys understand.</p>

答: highlight the item you want to rename, then click refactor -> rename</p>


问:
Calculating total amount

What I wants to calculate total amount when plus or minus button clicked of the listview row item and update the changes to the  total please help me get out of this problem
Thanks in advance

答:
I have a solution for this ,may be it gets you help

```<code><TextView
    android:id="@+id/cartTotal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="RS 0.00"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textStyle="bold" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/cartTotal"
    android:text="Total: "
    android:textAppearance="?android:attr/textAppearanceMedium" />

<ListView
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/textView2" />`
</code>```

design layout for adapter like given screen

```<code> <TextView
    android:id="@+id/tiem_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="TextView"
    android:textSize="20dp" />

<TextView
    android:id="@+id/flag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="TextView"
    android:textSize="20dp" />

<TextView

    android:id="@+id/eachPrice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="120.0"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/ext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="Index Total Price"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/editText2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:hint="Qty" />

    <Button
        android:id="@+id/plus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/minus"
        android:layout_alignBottom="@+id/minus"
        android:layout_marginEnd="18dp"
        android:layout_marginRight="18dp"
        android:layout_toLeftOf="@+id/minus"
        android:layout_toStartOf="@+id/minus"
        android:text="+" />

    <Button
        android:id="@+id/minus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText2"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="-" />

</RelativeLayout>
</code>```

Model Item

```<code>public class CartItem {

String name;
String flag;
int UserQty;
double ProductPrice;
double ProductSalePrice;
private Double ext = 0.00;

public Double getExt() {
    return ext;
}

public void setExt(Double ext) {
    this.ext = ext;
}

public double getProductSalePrice() {
    return ProductSalePrice;
}

public void setProductSalePrice(double productSalePrice) {
    ProductSalePrice = productSalePrice;
}

public double getProductPrice() {
    return ProductPrice;
}

public void setProductPrice(double productPrice) {
    ProductPrice = productPrice;
}

public int getUserQty() {
    return UserQty;
}

public void setUserQty(int userQty) {
    UserQty = userQty;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getFlag() {
    return flag;
}

public void setFlag(String flag) {
    this.flag = flag;
}
</code>```

}

```<code>**Main Activity**
</code>```

public class MainActivity extends Activity {
    String url = "http://139.59.43.252/cnsgoCash/api/ws/controller/?access=true&action=get_category_by_product_list&id=5";
    ProgressDialog PD;
    Button payment;

```<code>private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    payment=(Button)findViewById(R.id.payment);
    ExpandList = (ExpandableListView) findViewById(R.id.expandableListView);
    PD = new ProgressDialog(this);
    PD.setMessage("Loading.....");
    PD.setCancelable(false);
    makejsonobjreq();

/*  Click*/
    payment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                Intent in =new Intent(MainActivity.this,AddedItemActivity.class);
                startActivity(in);

        }
    });
    ExpandList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        }
    });

}

private void makejsonobjreq() {
    PD.show();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            System.out.println("Json String :" + String.valueOf(response));
            Log.e("RES", String.valueOf(response));
            ArrayList<Group> list = new ArrayList<Group>();
            ArrayList<Child> ch_list;
            try {
                //Iterator<String> key = response.keys();
                JSONArray jsonArray=response.getJSONArray("data");

                for(int i=0;i<jsonArray.length();i++){
                    JSONObject object= jsonArray.getJSONObject(i)  ;
                    String k = object.getString("categoryName");

                    Log.e("Parent","hello"+k);
                    Group gru = new Group();
                    gru.setName(k);
                    ch_list = new ArrayList<Child>();
                    JSONArray ja = object.getJSONArray("productdetails");
                    for (int j = 0; j < ja.length(); j++) {
                        JSONObject jo = ja.getJSONObject(j);
                        Child ch = new Child();
                        //Log.e("Child","hello"+jo.getString("productName"));
                        ch.setName(jo.getString("productCode"));
                        ch.setFlag(jo.getString("productName"));
                        ch.setUserQty(jo.getString("quantity"));
                        ch.setProductPrice(jo.getString("sellPrice"));
                        ch_list.add(ch);
                    } // child for loop end
                    gru.setItems(ch_list);
                    list.add(gru);
                }

                ExpAdapter = new ExpandListAdapter(MainActivity.this, list);
                ExpandList.setAdapter(ExpAdapter);
                PD.dismiss();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonObjectRequest);
}
</code>```

}

Title: Calculating total amount

Body:
I have a solution for this ,may be it gets you help

<TextView
    android:id="@+id/cartTotal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="RS 0.00"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textStyle="bold" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/cartTotal"
    android:text="Total: "
    android:textAppearance="?android:attr/textAppearanceMedium" />

<ListView
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/textView2" />`

design layout for adapter like given screen

 <TextView
    android:id="@+id/tiem_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="TextView"
    android:textSize="20dp" />

<TextView
    android:id="@+id/flag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="TextView"
    android:textSize="20dp" />

<TextView

    android:id="@+id/eachPrice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="120.0"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/ext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"
    android:text="Index Total Price"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/editText2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:hint="Qty" />

    <Button
        android:id="@+id/plus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/minus"
        android:layout_alignBottom="@+id/minus"
        android:layout_marginEnd="18dp"
        android:layout_marginRight="18dp"
        android:layout_toLeftOf="@+id/minus"
        android:layout_toStartOf="@+id/minus"
        android:text="+" />

    <Button
        android:id="@+id/minus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText2"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="-" />

</RelativeLayout>

Model Item

public class CartItem {

String name;
String flag;
int UserQty;
double ProductPrice;
double ProductSalePrice;
private Double ext = 0.00;

public Double getExt() {
    return ext;
}

public void setExt(Double ext) {
    this.ext = ext;
}

public double getProductSalePrice() {
    return ProductSalePrice;
}

public void setProductSalePrice(double productSalePrice) {
    ProductSalePrice = productSalePrice;
}

public double getProductPrice() {
    return ProductPrice;
}

public void setProductPrice(double productPrice) {
    ProductPrice = productPrice;
}

public int getUserQty() {
    return UserQty;
}

public void setUserQty(int userQty) {
    UserQty = userQty;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getFlag() {
    return flag;
}

public void setFlag(String flag) {
    this.flag = flag;
}

}

**Main Activity**

public class MainActivity extends Activity {
    String url = "http://139.59.43.252/cnsgoCash/api/ws/controller/?access=true&action=get_category_by_product_list&id=5";
    ProgressDialog PD;
    Button payment;

private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    payment=(Button)findViewById(R.id.payment);
    ExpandList = (ExpandableListView) findViewById(R.id.expandableListView);
    PD = new ProgressDialog(this);
    PD.setMessage("Loading.....");
    PD.setCancelable(false);
    makejsonobjreq();

/*  Click*/
    payment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                Intent in =new Intent(MainActivity.this,AddedItemActivity.class);
                startActivity(in);

        }
    });
    ExpandList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        }
    });

}

private void makejsonobjreq() {
    PD.show();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            System.out.println("Json String :" + String.valueOf(response));
            Log.e("RES", String.valueOf(response));
            ArrayList<Group> list = new ArrayList<Group>();
            ArrayList<Child> ch_list;
            try {
                //Iterator<String> key = response.keys();
                JSONArray jsonArray=response.getJSONArray("data");

                for(int i=0;i<jsonArray.length();i++){
                    JSONObject object= jsonArray.getJSONObject(i)  ;
                    String k = object.getString("categoryName");

                    Log.e("Parent","hello"+k);
                    Group gru = new Group();
                    gru.setName(k);
                    ch_list = new ArrayList<Child>();
                    JSONArray ja = object.getJSONArray("productdetails");
                    for (int j = 0; j < ja.length(); j++) {
                        JSONObject jo = ja.getJSONObject(j);
                        Child ch = new Child();
                        //Log.e("Child","hello"+jo.getString("productName"));
                        ch.setName(jo.getString("productCode"));
                        ch.setFlag(jo.getString("productName"));
                        ch.setUserQty(jo.getString("quantity"));
                        ch.setProductPrice(jo.getString("sellPrice"));
                        ch_list.add(ch);
                    } // child for loop end
                    gru.setItems(ch_list);
                    list.add(gru);
                }

                ExpAdapter = new ExpandListAdapter(MainActivity.this, list);
                ExpandList.setAdapter(ExpAdapter);
                PD.dismiss();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonObjectRequest);
}

}


问:
Postgresql pgadmin log can't work
```https://www.pgadmin.org/docs/pgadmin3/1.22/status.html```

Hi, I have one server can activate this function, it means I can see the server log in my PGADMIN tool, but I don't know why other servers can't.

I follow the instructions on this official page.

```<code>log_destination = ‘stderr’
logging_collector = on
log_directory = 'pg_log'
log_file_mode = 0600
log_truncate_on_rotation = on
log_filename = ‘postgresql-%Y-%m-%d_%H%M%S.log’
</code>```

But the tool still shows "Logs are not available for this server"

Please help me, thank you!

答:
Login postgres DB, then load the extension, it works!</p>

```<code>CREATE EXTENSION adminpack;
</code>```

Title: Postgresql pgadmin log can't work

Body:
https://www.pgadmin.org/docs/pgadmin3/1.22/status.html

Hi, I have one server can activate this function, it means I can see the server log in my PGADMIN tool, but I don't know why other servers can't.

I follow the instructions on this official page.

log_destination = ‘stderr’
logging_collector = on
log_directory = 'pg_log'
log_file_mode = 0600
log_truncate_on_rotation = on
log_filename = ‘postgresql-%Y-%m-%d_%H%M%S.log’

But the tool still shows "Logs are not available for this server"

Please help me, thank you!

Body:
Login postgres DB, then load the extension, it works!

CREATE EXTENSION adminpack;


问:
how to replace text with numerical vaue in excel
I having a response in excle cell as below

"abx:hi,systemTime:120202020202"

In which i want to replace

systemTime:120202020202

with empty space. I tried with =SUBSTITUTE(SUBSTITUTE(A1,"systemTime",""), ":","")but not working as expected. Could you please help

答:
Is this what you want

```<code>=LEFT(A1,FIND("systemTime",A1)-1)
</code>```

EDIT: As per comments

```<code>=SUBSTITUTE(A1,MID(A1,FIND("systemTime",A1)-1,FIND(",",MID(A1,FIND("systemTime",A1)-1,LEN(A1)-FIND("systemTime",A1)))),"")
</code>```

Body:
Is this what you want

=LEFT(A1,FIND("systemTime",A1)-1)

EDIT: As per comments

=SUBSTITUTE(A1,MID(A1,FIND("systemTime",A1)-1,FIND(",",MID(A1,FIND("systemTime",A1)-1,LEN(A1)-FIND("systemTime",A1)))),"")


Title: Javascript - wait for 1 minute for every 10 loop?

Body:
How can I wait for 1 or 2 minute for every 10 loop?

For instance, this is my working code:

var dates = ["2016-08-31T23:00:00.000Z","2016-09-01T23:00:00.000Z","2016-09-02T23:00:00.000Z","2016-09-03T23:00:00.000Z","2016-09-04T23:00:00.000Z","2016-09-05T23:00:00.000Z","2016-09-06T23:00:00.000Z","2016-09-07T23:00:00.000Z","2016-09-08T23:00:00.000Z","2016-09-09T23:00:00.000Z","2016-09-10T23:00:00.000Z","2016-09-11T23:00:00.000Z","2016-09-12T23:00:00.000Z","2016-09-13T23:00:00.000Z","2016-09-14T23:00:00.000Z","2016-09-15T23:00:00.000Z","2016-09-16T23:00:00.000Z","2016-09-17T23:00:00.000Z","2016-09-18T23:00:00.000Z","2016-09-19T23:00:00.000Z","2016-09-20T23:00:00.000Z","2016-09-21T23:00:00.000Z","2016-09-22T23:00:00.000Z","2016-09-23T23:00:00.000Z","2016-09-24T23:00:00.000Z","2016-09-25T23:00:00.000Z","2016-09-26T23:00:00.000Z","2016-09-27T23:00:00.000Z","2016-09-28T23:00:00.000Z","2016-09-29T23:00:00.000Z","2016-09-30T23:00:00.000Z","2016-10-01T23:00:00.000Z"];

var counter = 0;

// Loop the dates and convert them to this format: yyyy-m-d
dates.forEach(function(date, index) {
    counter ++;

    console.log(date);

    // Reset when you reach 10 counts.
    if (counter === 10) {
        counter = 0;
    }

    // Wait for 2 minute before the next 10 loop.
    setTimeout( function() {
       //
    }, 120000);
});

Is it possible? Any ideas?

EDIT:

What I am after:

2016-08-31T23:00:00.000Z
2016-09-01T23:00:00.000Z
2016-09-02T23:00:00.000Z
2016-09-03T23:00:00.000Z
2016-09-04T23:00:00.000Z
2016-09-05T23:00:00.000Z
2016-09-06T23:00:00.000Z
2016-09-07T23:00:00.000Z
2016-09-08T23:00:00.000Z
2016-09-09T23:00:00.000Z

(wait for 2 minute here)

2016-09-10T23:00:00.000Z
2016-09-11T23:00:00.000Z
2016-09-12T23:00:00.000Z
2016-09-13T23:00:00.000Z
2016-09-14T23:00:00.000Z
2016-09-15T23:00:00.000Z
2016-09-16T23:00:00.000Z
2016-09-17T23:00:00.000Z
2016-09-18T23:00:00.000Z
2016-09-19T23:00:00.000Z

(wait for 2 minute here)

2016-09-20T23:00:00.000Z
2016-09-21T23:00:00.000Z
2016-09-22T23:00:00.000Z
2016-09-23T23:00:00.000Z
2016-09-24T23:00:00.000Z
2016-09-25T23:00:00.000Z
2016-09-26T23:00:00.000Z
2016-09-27T23:00:00.000Z
2016-09-28T23:00:00.000Z
2016-09-29T23:00:00.000Z

(wait for 2 minute here)

2016-09-30T23:00:00.000Z
2016-10-01T23:00:00.000Z

Body:
You can use setInterval and inside just for loop to increment by 10 in each interval.

var dates = ["2016-08-31T23:00:00.000Z", "2016-09-01T23:00:00.000Z", "2016-09-02T23:00:00.000Z", "2016-09-03T23:00:00.000Z", "2016-09-04T23:00:00.000Z", "2016-09-05T23:00:00.000Z", "2016-09-06T23:00:00.000Z", "2016-09-07T23:00:00.000Z", "2016-09-08T23:00:00.000Z", "2016-09-09T23:00:00.000Z", "2016-09-10T23:00:00.000Z", "2016-09-11T23:00:00.000Z", "2016-09-12T23:00:00.000Z", "2016-09-13T23:00:00.000Z", "2016-09-14T23:00:00.000Z", "2016-09-15T23:00:00.000Z", "2016-09-16T23:00:00.000Z", "2016-09-17T23:00:00.000Z", "2016-09-18T23:00:00.000Z", "2016-09-19T23:00:00.000Z", "2016-09-20T23:00:00.000Z", "2016-09-21T23:00:00.000Z", "2016-09-22T23:00:00.000Z", "2016-09-23T23:00:00.000Z", "2016-09-24T23:00:00.000Z", "2016-09-25T23:00:00.000Z", "2016-09-26T23:00:00.000Z", "2016-09-27T23:00:00.000Z", "2016-09-28T23:00:00.000Z", "2016-09-29T23:00:00.000Z", "2016-09-30T23:00:00.000Z", "2016-10-01T23:00:00.000Z"];
var c = 0
var time = 2000; // 2 sec just for demo

function loopDates() {
  for (var i = c; i < c + 10; i++) {
    if (dates[i]) {
      var date = dates[i].slice(0, 10);
      console.log(date)
    }
  }
  c += 10

  if (c >= dates.length) clearInterval(x)
}

loopDates()
var x = setInterval(loopDates, time)


问:
How to attach PDF to email using PHP

This is php code and its working, all the form content successfully send to mail id, but i want to attach PDF file also to email using php this function.
  But how i can, i don't know.

I would like to add a specified PDF file as a file attachment to the email. How would I do that?

```<code><?php
$name  = $_REQUEST["name"];
$phone = $_REQUEST["phone"];
$email = $_REQUEST["email"];
$address = $_REQUEST["address"];
$message = $_REQUEST["message"];
date_default_timezone_set("Asia/Calcutta");
$todayis = date("y-m-d H:i:s", time());
$subject = "PVC Order From Website ";
$to      = "iamrightful@gmail.com";
$msg .= "<table width='600' border='0' align='center' cellpadding='0' ellspacing='0' style='font-family:Arial, Helvetica, sans-serif;
font-size:13pt; border:1px solid #0f3f6a;'>";
$msg .= "<tr>";
$msg .= "<td width='16' height='25' bgcolor='#f9cf7b'> </td>";
$msg .= "<td width='96' bgcolor='#f9cf7b'>Name</td>";
$msg .= "<td width='10' height='25' bgcolor='#f9cf7b'><strong>:</strong></td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>$name</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<td height='25' bgcolor='#f9cf7b'> </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>Mobile </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'><strong>:</strong></td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>$phone</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<tr>";
$msg .= "<td height='25' bgcolor='#f9cf7b'> </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>Email Id </td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'><strong>:</strong></td>";
$msg .= "<td height='25' bgcolor='#f9cf7b'>$email</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<td height='25'> </td>";
$msg .= "<td height='25'>Address</td>";
$msg .= "<td height='25'><strong>:</strong></td>";
$msg .= "<td height='25'>$address</td>";
$msg .= "</tr>";
$msg .= "<tr>";
$msg .= "<td height='25'> </td>";
$msg .= "<td height='25'>Discription</td>";
$msg .= "<td height='25'><strong>:</strong></td>";
$msg .= "<td height='25'>$message</td>";
$msg .= "</tr>";
$msg .= "</table>";
$headers = "From: $c_name < $c_email >.";
$headers = "Bcc: admin < $Bcc >.";
$headers .= "\r\nContent-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $msg, $headers);
header("Location:thankyou.html");
</code>```

答:
Normally you will pass three values to the mail() function plus some headers. In the example below I skip the value for the message value, because the message is defined as a MIME part together with the attachment.

```<code>function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
 $file = $path.$filename;
 $file_size = filesize($file);
 $handle = fopen($file, "r");
 $content = fread($handle, $file_size);
 fclose($handle);
 $content = chunk_split(base64_encode($content));
 $uid = md5(uniqid(time()));
 $header = "From: ".$from_name." <".$from_mail.">\r\n";
 $header .= "Reply-To: ".$replyto."\r\n";
 $header .= "MIME-Version: 1.0\r\n";
 $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
 $header .= "This is a multi-part message in MIME format.\r\n";
 $header .= "--".$uid."\r\n";
 $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
 $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
 $header .= $message."\r\n\r\n";
 $header .= "--".$uid."\r\n";
 $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
 $header .= "Content-Transfer-Encoding: base64\r\n";
 $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
 $header .= $content."\r\n\r\n";
 $header .= "--".$uid."--";
 if (mail($mailto, $subject, "", $header)) {
 echo "mail send ... OK"; // or use booleans here
 } else {
 echo "mail send ... ERROR!";
 }
}
</code>```

Below is an example on how I use this function to send an email message with one attached .zip file:

```<code>$my_file = "somefile.zip";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,rndo you like this script? I hope it will help.rnrngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
</code>```

Title: How to attach PDF to email using PHP

Body:
This is php code and its working, all the form content successfully send to mail id, but i want to attach PDF file also to email using php this function.
  But how i can, i don't know.

I would like to add a specified PDF file as a file attachment to the email. How would I do that?

<?php
$name  = $_REQUEST["name"];
$phone = $_REQUEST["phone"];
$email = $_REQUEST["email"];
$address = $_REQUEST["address"];
$message = $_REQUEST["message"];
date_default_timezone_set("Asia/Calcutta");
$todayis = date("y-m-d H:i:s", time());
$subject = "PVC Order From Website ";
$to      = "iamrightful@gmail.com";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Name	";
$msg .= ":	";
$msg .= "$name	";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Mobile 	";
$msg .= ":	";
$msg .= "$phone	";
$msg .= "
";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Email Id 	";
$msg .= ":	";
$msg .= "$email	";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Address	";
$msg .= ":	";
$msg .= "$address	";
$msg .= "
";
$msg .= "
";
$msg .= " 	";
$msg .= "Discription	";
$msg .= ":	";
$msg .= "$message	";
$msg .= "
";
$msg .= "
";
$headers = "From: $c_name < $c_email >.";
$headers = "Bcc: admin < $Bcc >.";
$headers .= "\r\nContent-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $msg, $headers);
header("Location:thankyou.html");

Body:
Normally you will pass three values to the mail() function plus some headers. In the example below I skip the value for the message value, because the message is defined as a MIME part together with the attachment.

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
 $file = $path.$filename;
 $file_size = filesize($file);
 $handle = fopen($file, "r");
 $content = fread($handle, $file_size);
 fclose($handle);
 $content = chunk_split(base64_encode($content));
 $uid = md5(uniqid(time()));
 $header = "From: ".$from_name." <".$from_mail.">\r\n";
 $header .= "Reply-To: ".$replyto."\r\n";
 $header .= "MIME-Version: 1.0\r\n";
 $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
 $header .= "This is a multi-part message in MIME format.\r\n";
 $header .= "--".$uid."\r\n";
 $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
 $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
 $header .= $message."\r\n\r\n";
 $header .= "--".$uid."\r\n";
 $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
 $header .= "Content-Transfer-Encoding: base64\r\n";
 $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
 $header .= $content."\r\n\r\n";
 $header .= "--".$uid."--";
 if (mail($mailto, $subject, "", $header)) {
 echo "mail send ... OK"; // or use booleans here
 } else {
 echo "mail send ... ERROR!";
 }
}

Below is an example on how I use this function to send an email message with one attached .zip file:

$my_file = "somefile.zip";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,rndo you like this script? I hope it will help.rnrngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);


问:
Two-key encryption/decryption?
I'm looking to store some fairly sensitive data using PHP and MySQL and will be using some form of reversible encryption to do so since I need to get the data back out in plain text for it to be of any use.

I'll be deriving the encryption key from the users' username/password combination but I'm stumped for what to do in the (inevitable) event of a password being forgotten. I realise that the purpose of encryption is that it can only be undone using the correct key but this must have been addressed before..

I'm trying to get my head around whether or not public key cryptography would apply to the problem but all I can think of is that the private key will still need to be correct to decrypt the data..

Any ideas?

答:
It's not clear what you are striving for, so advice on how to implement it is hard.

Standards like PGP and S/MIME encrypt each message with a new symmetric key. Those keys are then encrypted for each recipient of the message. This way, instead of duplicating the message (which could be very large) for each recipient, everyone gets the same ciphertext, and only the key (which is small) is duplicated—but encrypted differently for each recipient.

Maybe you could do something similar here, encrypting the key with the user's password, and encrypting another copy with your public key. If the user forgets their password, you can recover the message for them (after an appropriate backup identity verification) using your private key.

Title: Two-key encryption/decryption?


问:
How to set a checkbox's checked-attribute via its changed-eventlistener
I have a matrix in angular.js 4 (with material.angular) which is filled with checkboxes. When the user clicks a checkbox, a HTTP-Request is send to backend server. In case the backend server is not available or the service call goes wrong for any reason, I want the checkbox to return to it's previous state (checked/unchecked). Therefore I implemented the following change-eventhandler to make the service call and react dependent on the result of the service call:

```<code>zuordnungChanged(rolle_id: string, recht_id: string) {
let a = this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id];
if (a === true ){
  this.rechtematrix.rechtEntziehen(rolle_id, recht_id).subscribe(() => {
      a = false;
      this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
      //Notify user
      });
    },
    () => {
      //Notify user
    });
} else {
  this.rechtematrix.rechtVergeben(rolle_id, recht_id).subscribe(() => {
      a = true;
      this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
      //Notify User
      });
  },
    () => {
      //Notify user
    }
  );
}
}
</code>```

The zuordnungsmatrix variable is defined and filled like that:

```<code>private zuordnungen: Array<any>;
  private zuordnungsmatrix = [];

erstelleZuordnungsmatrix(): void {
    for (let rolle of this.zuordnungen) {
      for ( let recht of rolle.recht_ids) {
        this.zuordnungsmatrix["Rolle_" + rolle.rolle_id + "_Recht_" + recht] = true;
      }
    }
  }
</code>```

I bound  the values from zuordnungsmatrix to the checkbox' checked-attribute like this:

```<code><table td-data-table *ngIf="rechteUndRollenVorhanden()">
      <tr>
        <th td-data-table-column></th>
      <th td-data-table-column *ngFor="let rolle of rollen" [id]="'Rolle_' + rolle.rolle_id">{{rolle.beschreibung}}</th>
      </tr>
      <tr td-data-table-row *ngFor="let recht of rechte" [id]="'Recht_' + recht.recht_id">
        <td td-data-table-cell>{{recht.beschreibung}}</td>
        <td td-data-table-cell *ngFor="let rolle of rollen">
          <md-checkbox [id]="'Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id"
                       [checked]="zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false"
                        (change)="zuordnungChanged(rolle.rolle_id, recht.recht_id, $event)">{{zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false}}
          </md-checkbox>
        </td>
      </tr>
    </table>
</code>```

My problem know is that I don't know how to let the checkboxes represent the actual state of zuordnungsmatrix. The variable is updated and this binding in the view works as well:

```<code>{{zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false}}
</code>```

But I tried a lot to update the checkbox but It didn't work. Anyway, the initial setting of the checkbox' checked-state works fine. How can I update a checkbox' state in its own event listener?

答:
The solution is pretty simple:

For some reason Angular doesn't update the changed value of the checkbox via One-Way-Binding. You simply have to explicit set the checked status . To do that you can pass the event from HTML to the component via the parameter $event. This is already done in the example above.

In the change event handler in the component you can read the event and get a reference to the checkbox element. All you have to do then is setting the checked attribute of this element ($event.source.checked).
The event handler from the question now looks like this:

```<code>zuordnungChanged(rolle_id: string, recht_id: string, event: any) {
    let a = this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id];
    if (a === true ){
      this.rechtematrix.rechtEntziehen(rolle_id, recht_id).subscribe(() => {
          //Happy case
          a = false;
          this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
          //Notify user
          });
        },
        () => {
          //Bad case
          event.source.checked = this.zuordnungsmatrix['Rolle_' + rolle_id + '_Recht_' + recht_id];
          //Notify user
        });
    } else {
      this.rechtematrix.rechtVergeben(rolle_id, recht_id).subscribe(() => {
          //Happy case
          a = true;
          this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
          //Notify User
          });
      },
        () => {
          //Bad case
          event.source.checked = this.zuordnungsmatrix['Rolle_' + rolle_id + '_Recht_' + recht_id];
          //Notify user
        }
      );
    }
}
</code>```

Note that the attribute setting is only done, when the REST-call fails. This is because in happy case the checkbox is updated automatically by user interaction.

Body:
I have a matrix in angular.js 4 (with material.angular) which is filled with checkboxes. When the user clicks a checkbox, a HTTP-Request is send to backend server. In case the backend server is not available or the service call goes wrong for any reason, I want the checkbox to return to it's previous state (checked/unchecked). Therefore I implemented the following change-eventhandler to make the service call and react dependent on the result of the service call:

zuordnungChanged(rolle_id: string, recht_id: string) {
let a = this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id];
if (a === true ){
  this.rechtematrix.rechtEntziehen(rolle_id, recht_id).subscribe(() => {
      a = false;
      this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
      //Notify user
      });
    },
    () => {
      //Notify user
    });
} else {
  this.rechtematrix.rechtVergeben(rolle_id, recht_id).subscribe(() => {
      a = true;
      this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
      //Notify User
      });
  },
    () => {
      //Notify user
    }
  );
}
}

The zuordnungsmatrix variable is defined and filled like that:

private zuordnungen: Array<any>;
  private zuordnungsmatrix = [];

erstelleZuordnungsmatrix(): void {
    for (let rolle of this.zuordnungen) {
      for ( let recht of rolle.recht_ids) {
        this.zuordnungsmatrix["Rolle_" + rolle.rolle_id + "_Recht_" + recht] = true;
      }
    }
  }

I bound  the values from zuordnungsmatrix to the checkbox' checked-attribute like this:

      {{rolle.beschreibung}}

        {{recht.beschreibung}}

          <md-checkbox [id]="'Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id"
                       [checked]="zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false"
                        (change)="zuordnungChanged(rolle.rolle_id, recht.recht_id, $event)">{{zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false}}
          </md-checkbox>

My problem know is that I don't know how to let the checkboxes represent the actual state of zuordnungsmatrix. The variable is updated and this binding in the view works as well:

{{zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false}}

But I tried a lot to update the checkbox but It didn't work. Anyway, the initial setting of the checkbox' checked-state works fine. How can I update a checkbox' state in its own event listener?

Body:
The solution is pretty simple:

For some reason Angular doesn't update the changed value of the checkbox via One-Way-Binding. You simply have to explicit set the checked status . To do that you can pass the event from HTML to the component via the parameter $event. This is already done in the example above.

In the change event handler in the component you can read the event and get a reference to the checkbox element. All you have to do then is setting the checked attribute of this element ($event.source.checked).
The event handler from the question now looks like this:

zuordnungChanged(rolle_id: string, recht_id: string, event: any) {
    let a = this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id];
    if (a === true ){
      this.rechtematrix.rechtEntziehen(rolle_id, recht_id).subscribe(() => {
          //Happy case
          a = false;
          this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
          //Notify user
          });
        },
        () => {
          //Bad case
          event.source.checked = this.zuordnungsmatrix['Rolle_' + rolle_id + '_Recht_' + recht_id];
          //Notify user
        });
    } else {
      this.rechtematrix.rechtVergeben(rolle_id, recht_id).subscribe(() => {
          //Happy case
          a = true;
          this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
          //Notify User
          });
      },
        () => {
          //Bad case
          event.source.checked = this.zuordnungsmatrix['Rolle_' + rolle_id + '_Recht_' + recht_id];
          //Notify user
        }
      );
    }
}

Note that the attribute setting is only done, when the REST-call fails. This is because in happy case the checkbox is updated automatically by user interaction.


问:
Espresso: Interact with Play Store Popup
In the app I am working on, there is a button that will open the Google Play Store page of the app. With Espresso, I want to check if the correct page is opened.

```<code>// this is the code I already have

onView(withId(R.id.SettingsButton)).perform(click());
onView(withId(R.id.RateAppButton)).perform(scrollTo(),click());

// now the Play Store should be opened (like a popup)
</code>```

Now I want to find out if the displayed app title includes the correct app name and if it is an actual play store page. Since Espresso somewhat doesn't interact with the buttons in this view, what options do I have?
How can I work with this new view?

答:
As you mentioned correctly, espresso can just interact with your own package.
To interact with other apps or the android system UI (e.g. permission dialogs) you have to use ui-automator.

ui-automator works well if you combine it with espresso, you can just open the playstore link in your app with espresso and then check the new screen with ui-automator (and also press the system back button to return to your app).

You could for example use something like this to check if the correct title appears:

```<code> UiObject titleLabel = mDevice.findObject(new UiSelector().text("Your Title"));
 if(!titleLabel.exists())
 {
    throw new RuntimeException("wrong title!");
 }
</code>```

See this blogpost for a longer example.

Body:
In the app I am working on, there is a button that will open the Google Play Store page of the app. With Espresso, I want to check if the correct page is opened.

// this is the code I already have

onView(withId(R.id.SettingsButton)).perform(click());
onView(withId(R.id.RateAppButton)).perform(scrollTo(),click());

// now the Play Store should be opened (like a popup)

Now I want to find out if the displayed app title includes the correct app name and if it is an actual play store page. Since Espresso somewhat doesn't interact with the buttons in this view, what options do I have?
How can I work with this new view?

Body:
As you mentioned correctly, espresso can just interact with your own package.
To interact with other apps or the android system UI (e.g. permission dialogs) you have to use ui-automator.

ui-automator works well if you combine it with espresso, you can just open the playstore link in your app with espresso and then check the new screen with ui-automator (and also press the system back button to return to your app).

You could for example use something like this to check if the correct title appears:

 UiObject titleLabel = mDevice.findObject(new UiSelector().text("Your Title"));
 if(!titleLabel.exists())
 {
    throw new RuntimeException("wrong title!");
 }

See this blogpost for a longer example.


问:
How to test if a string contains an item within a list?
Say I have a string:

```<code>var s = "z_cams_c_ecmf_20160704120000_prod_fc_ml_012_go3.nc";
</code>```

and say I have a list of strings:

```<code>var items = new List<string>(){"fc", "an"};
</code>```

How can I test if s contains either fc or an?

I don't want to loop over items and test each case because I am looking for multiple conditions. For example, I will also want to test if s contains "prod" or "rean" or "test".

I suppose I could throw all my conditions (fc, an, prod, rean, test, etc...) into single list and iterate over each of them, but it doesn't feel right, given the user must supply JSON which is deseralized into an object with various lists for condition matching.

I suppose I am looking for something like the answer seen here, but I do not know what Mdd LH is...

答:
LINQ also uses loops, but you don't see them ;-)

```<code>bool contains = items.Any(s.Contains);
</code>```

If you want to ignore the case(so upper or lowercase letters):

```<code>contains = items.Any(i => s.IndexOf(i, StringComparison.InvariantCultureIgnoreCase) >= 0);
</code>```

Body:
Say I have a string:

var s = "z_cams_c_ecmf_20160704120000_prod_fc_ml_012_go3.nc";

and say I have a list of strings:

var items = new List<string>(){"fc", "an"};

How can I test if s contains either fc or an?

I don't want to loop over items and test each case because I am looking for multiple conditions. For example, I will also want to test if s contains "prod" or "rean" or "test".

I suppose I could throw all my conditions (fc, an, prod, rean, test, etc...) into single list and iterate over each of them, but it doesn't feel right, given the user must supply JSON which is deseralized into an object with various lists for condition matching.

I suppose I am looking for something like the answer seen here, but I do not know what Mdd LH is...

Body:
LINQ also uses loops, but you don't see them ;-)

bool contains = items.Any(s.Contains);

If you want to ignore the case(so upper or lowercase letters):

contains = items.Any(i => s.IndexOf(i, StringComparison.InvariantCultureIgnoreCase) >= 0);