问:
Python DataFrame Copy
I am trying to create a new dataframe based on some criteria based on an original dataframe.

```<code>df = pandas.io.sql.read_sql(sql, conn)

Count_Row = df.shape[0]
for j in range(Count_Row - 1):

    if df.iloc[j, 0] == df.iloc[j + 1, 0]:
        print(df.iloc[j, 2] + df.iloc[j + 1, 2], df.iloc[j, 4], df.iloc[j, 6], df.iloc[j, 3])
</code>```

However instead of printing I want to add that data to a new dataframe.

How is this possible?

答:
Don't use a slow "for" loop to do this.  Instead, generate a mask which is True for the elements you want, then select those elements:

```<code>matches = df.iloc[:-1,0] == df.iloc[1:,0]
new_df = df.iloc[:-1][matches]
</code>```

This will be 10-100x faster than the approach you had before.

At the end, new_df will contain copies of the selected rows.

[:-1] means "all elements before the last one."

Title: Python DataFrame Copy

Body:
I am trying to create a new dataframe based on some criteria based on an original dataframe.

df = pandas.io.sql.read_sql(sql, conn)

Count_Row = df.shape[0]
for j in range(Count_Row - 1):

    if df.iloc[j, 0] == df.iloc[j + 1, 0]:
        print(df.iloc[j, 2] + df.iloc[j + 1, 2], df.iloc[j, 4], df.iloc[j, 6], df.iloc[j, 3])

However instead of printing I want to add that data to a new dataframe.

How is this possible?

Body:
Don't use a slow "for" loop to do this.  Instead, generate a mask which is True for the elements you want, then select those elements:

matches = df.iloc[:-1,0] == df.iloc[1:,0]
new_df = df.iloc[:-1][matches]

This will be 10-100x faster than the approach you had before.

At the end, new_df will contain copies of the selected rows.

[:-1] means "all elements before the last one."


来源: stackexchange

问:
"Error: spawn EACCES" showing on cordova build android project
Click here to see error image

How to resolve this problem?? Thanks in advance

答: I had the same issue and I tried all sort of permission change and it still didn't work. My problem started with the update of android studio which in turn forced me to update Cordova. Finally I got it working by downloading the latest Android Studio (2.3.2) and installing it. I am also using Mac.</p>

ContentLicense: CC BY-SA 3.0


问:
How to PROVE the precedence of '&&' and '||' by coding in Java?
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

```<code>boolExp1 || boolExp2 && boolExp3 || boolExp4
</code>```

The code above produces the same results no matter the precedence of && and ||, that is,

```<code>false || false && true || false
</code>```

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

答:
This is relyed upon all the time in lines like the following.

Clearly these examples would blow up if the first expression were not always evaluated and the second expression not evaluated conditionally.

```<code>// second expression on evaluated if text != null in both cases.
String text = ??
if (text != null && text.length() > 0)

if (text == null || text.length() == 0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

boolExp1 || boolExp2 && boolExp3 || boolExp4

The code above produces the same results no matter the precedence of && and ||, that is,

false || false && true || false

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

Body:
This is relyed upon all the time in lines like the following.

Clearly these examples would blow up if the first expression were not always evaluated and the second expression not evaluated conditionally.

// second expression on evaluated if text != null in both cases.
String text = ??
if (text != null && text.length() > 0)

if (text == null || text.length() == 0

ContentLicense: CC BY-SA 2.5


问:
xterm.js reconnect with same PWD
I am using xterm.js in my web project to have a terminal on the web page. Every time I refresh my page or reconnect socket when a socket connection is broken due to internet fluctuation from the client. The current PWD directory is lost and it falls to specified CWD directory which is user home in my case. So again I have to do cd where I was working.

How can I connect and remain at same PWD where I was last time before page refreshing or socket disconnect?

One of the things I tried is to store term object and connect through the same object when reconnecting if it is already present. Not deleting process and object in on WebSocket disconnect.

var http = require('http');
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var pty = require('node-pty');
var cors = require('cors');
app.use(cors());
app.options('*', cors());
var terminals = {}; //global terminals

function getUser(token) {
    return new Promise((resolve, reject) => {
      try {
        return http.get({
            host: '',
            path: '',
            headers: {'token': token}
        }, function(response) {
            // Continuously update stream with data
            var body = '';
            response.on('data', function(d) {
                body += d;
            });
            response.on('end', function() {
                return resolve(JSON.parse(body));
            });
        });
      } catch (err) {
        console.log('Api failed');
        console.log(err);
        reject;
      }
    })
}

app.ws('/terminals/:user_id', function (ws, req) {
  try {
    getUser(req.params.user_id) /* cheking with api if user exist in my database*/
      .then(user_info => {
        if(terminals[parseInt(req.params.user_id)]){
          var term = terminals[parseInt(req.params.user_id)];
        }else {
          var term = pty.spawn(process.platform === 'win32' ? 'cmd.exe' : 'bash', [], {
            name: 'xterm-color',
            cwd: cwd,
            env: process.env
          });
          terminals[parseInt(req.params.user_id)] = term;
        }

        term.on('data', function(data) {
          ws.send(data);
        });

        ws.on('message', function(msg) {
          term.write(msg);
        });

        ws.on('close', function () {
          // process.kill(term.pid);
          // delete terminals[parseInt(req.params.pid)];
          // delete logs[req.params.pid];
        });
      })
      .catch(err => {
      })
  } catch (err) {
      console.log('Terminal webSocket failed');
      console.log(err);
  }
});

app.listen(3000);```

This is not working for me. This gets me connect only first time but when I refresh my page terminal does not connect with existing store object.

Also, this has a problem if the spawned process is killed by the system but it still remains in javascript object and script try to reconnect with same term object it will fail.

Any guidelines how to achieve reconnect with same PWD.

Details

OS version: Mac OS ,
xterm.js version: 2.2.3

答:
This can be solved very easily by just updating the ~/.bashrc on server

Putting below two line in ~/.bashrc file worked for me

```<code>PROMPT_COMMAND+='printf %s "$PWD" > ~/.storepwd'
[ -s ~/.lastdirectory ] && cd `cat ~/.lastdirectory`
</code>```

Ref Save last working directory on Bash logout

Title: xterm.js reconnect with same PWD

Body:
I am using xterm.js in my web project to have a terminal on the web page. Every time I refresh my page or reconnect socket when a socket connection is broken due to internet fluctuation from the client. The current PWD directory is lost and it falls to specified CWD directory which is user home in my case. So again I have to do cd where I was working.

How can I connect and remain at same PWD where I was last time before page refreshing or socket disconnect?

One of the things I tried is to store term object and connect through the same object when reconnecting if it is already present. Not deleting process and object in on WebSocket disconnect.

var http = require('http');
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var pty = require('node-pty');
var cors = require('cors');
app.use(cors());
app.options('*', cors());
var terminals = {}; //global terminals

function getUser(token) {
    return new Promise((resolve, reject) => {
      try {
        return http.get({
            host: '',
            path: '',
            headers: {'token': token}
        }, function(response) {
            // Continuously update stream with data
            var body = '';
            response.on('data', function(d) {
                body += d;
            });
            response.on('end', function() {
                return resolve(JSON.parse(body));
            });
        });
      } catch (err) {
        console.log('Api failed');
        console.log(err);
        reject;
      }
    })
}

app.ws('/terminals/:user_id', function (ws, req) {
  try {
    getUser(req.params.user_id) /* cheking with api if user exist in my database*/
      .then(user_info => {
        if(terminals[parseInt(req.params.user_id)]){
          var term = terminals[parseInt(req.params.user_id)];
        }else {
          var term = pty.spawn(process.platform === 'win32' ? 'cmd.exe' : 'bash', [], {
            name: 'xterm-color',
            cwd: cwd,
            env: process.env
          });
          terminals[parseInt(req.params.user_id)] = term;
        }

        term.on('data', function(data) {
          ws.send(data);
        });

        ws.on('message', function(msg) {
          term.write(msg);
        });

        ws.on('close', function () {
          // process.kill(term.pid);
          // delete terminals[parseInt(req.params.pid)];
          // delete logs[req.params.pid];
        });
      })
      .catch(err => {
      })
  } catch (err) {
      console.log('Terminal webSocket failed');
      console.log(err);
  }
});

app.listen(3000);

This is not working for me. This gets me connect only first time but when I refresh my page terminal does not connect with existing store object.

Also, this has a problem if the spawned process is killed by the system but it still remains in javascript object and script try to reconnect with same term object it will fail.

Any guidelines how to achieve reconnect with same PWD.

Details

OS version: Mac OS ,
xterm.js version: 2.2.3

Body:
This can be solved very easily by just updating the ~/.bashrc on server

Putting below two line in ~/.bashrc file worked for me

PROMPT_COMMAND+='printf %s "$PWD" > ~/.storepwd'
[ -s ~/.lastdirectory ] && cd `cat ~/.lastdirectory`

Ref Save last working directory on Bash logout


问:
What is the most suitable control to use for 3D rendering and animation programming in Windows Forms?
I am researching 3D and 2D rendering animation. I found the PictureBox control
is pretty okay for this purpose, but I feel I have only very beginner level knowledge. I am curious to know if it is possible to make a moderately complex level of rendering applications with the PictureBox control. In short, which is the best control in the Windows application tool box to be selected for my intended purpose?

I am making a Windows Forms application with C#.

答:
The latest libraries you can use are from Xamarin,

SkiaSharp

UrhoSharp

They wrap over Skia and Urho engine so that you can render 2D or 3D contents in WinForms or WPF or any other kind of applications.


问:
python: compare data of different date types
I have a question of comparing data of datetime64[ns] and date like '2017-01-01'.

here is the code:
df.loc[(df['Date'] >= datetime.date(2017.1.1), 'TimeRange'] = '2017.1'

but , an error has been showed and said descriptor 'date' requires a 'datetime.datetime' object but received a 'int'.

how can i compare a datetime64 to data (2017-01-01 or 2-17-6-1 and likes)

Thanks

答:
You need to ensure that the data you're comparing it with is also in the same format. Assuming that you have two datetime objects, you can do it like this:

```<code>import datetime
print(df.loc[(df['Date'] >= datetime.date(2017, 1, 1), 'TimeRange'])
</code>```

This will create a datetime object and list out the filtered results. You can also assign the results an updated value as you have mentioned above.

Body:
You need to ensure that the data you're comparing it with is also in the same format. Assuming that you have two datetime objects, you can do it like this:

import datetime
print(df.loc[(df['Date'] >= datetime.date(2017, 1, 1), 'TimeRange'])

This will create a datetime object and list out the filtered results. You can also assign the results an updated value as you have mentioned above.


问:
Swift 3 UISwitch in TableViewCell loses State when scrolling
That's weird: I just set up a new Single-View iOS Project and put a TableView into the Main.storyboard. In this TableView I put a TableViewCell and into this Cell, I put an UILabel and an UISwitch.
For this TableViewCell I created a CocoaTouchClass MyTableViewCell and set this for the TableViewCell's Class in Interfacebuilder.
I connected Outlets for the UILabel and UISwitch to MyTableViewCell, as well as an action for the switch.
Also I connected the TableView's dataSource and delegate to the ViewController.

So, as I think, basic stuff for setting up a table.

My ViewController looks like this:

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableData = [[String: Bool]]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for index in 1...40 {
        self.tableData.append([String(index): index%2 == 0])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
    let object = tableData[indexPath.row].first!

    cell.myLabel.text = object.key
    cell.mySwitch.setOn(object.value, animated: false)

    return cell
}
</code>```

}

So, I populate the Table with some Rows of Data and switch every second UISwitch to on.

The MyTableViewCell-Class is nothing special as well:

```<code>class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func switched(_ sender: UISwitch) {
    print("Switched: \(sender.isOn)")
}
</code>```

}

Ok, fire up the iOS-Simulator and I see the Table as expected. 40 Table-Lines don't fit on one screen, so the TableView makes itself scrollable.

Now: when I change the state of one UISwitch, and drag the TableView so the changed UISwitch gets out of view and then drag the TableView so the changed UISwitch gets visible again, it is changed back to its initial state.
The Switch-event gets fired like it should.

So, what am I doing wrong? Am I missing something?

I recorded a 4-seconds-Screencast to demonstrate, what's going on:
http://b-bereich.de/download/swiftSwitch.mov

答:
Add function prepareForReuse() in your custom cell class and set switch state to off by default. -: </p>

```<code> class MyTableViewCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var mySwitch: UISwitch!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func switched(_ sender: UISwitch) {
        print("Switched: \(sender.isOn)")
    }

    override func prepareForReuse(){
    // SET SWITCH STATE OFF HERE
    }
</code>```

Body:
That's weird: I just set up a new Single-View iOS Project and put a TableView into the Main.storyboard. In this TableView I put a TableViewCell and into this Cell, I put an UILabel and an UISwitch.
For this TableViewCell I created a CocoaTouchClass MyTableViewCell and set this for the TableViewCell's Class in Interfacebuilder.
I connected Outlets for the UILabel and UISwitch to MyTableViewCell, as well as an action for the switch.
Also I connected the TableView's dataSource and delegate to the ViewController.

So, as I think, basic stuff for setting up a table.

My ViewController looks like this:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableData = [[String: Bool]]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for index in 1...40 {
        self.tableData.append([String(index): index%2 == 0])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
    let object = tableData[indexPath.row].first!

    cell.myLabel.text = object.key
    cell.mySwitch.setOn(object.value, animated: false)

    return cell
}

}

So, I populate the Table with some Rows of Data and switch every second UISwitch to on.

The MyTableViewCell-Class is nothing special as well:

class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func switched(_ sender: UISwitch) {
    print("Switched: \(sender.isOn)")
}

}

Ok, fire up the iOS-Simulator and I see the Table as expected. 40 Table-Lines don't fit on one screen, so the TableView makes itself scrollable.

Now: when I change the state of one UISwitch, and drag the TableView so the changed UISwitch gets out of view and then drag the TableView so the changed UISwitch gets visible again, it is changed back to its initial state.
The Switch-event gets fired like it should.

So, what am I doing wrong? Am I missing something?

I recorded a 4-seconds-Screencast to demonstrate, what's going on:
http://b-bereich.de/download/swiftSwitch.mov

Body:
Add function prepareForReuse() in your custom cell class and set switch state to off by default. -:

 class MyTableViewCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var mySwitch: UISwitch!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func switched(_ sender: UISwitch) {
        print("Switched: \(sender.isOn)")
    }

    override func prepareForReuse(){
    // SET SWITCH STATE OFF HERE
    }


问:
XAMARIN - add video from youtube
i search information how to add video from youtube, example:
I want add video from some youtube link.
I think that it should be in webview, but i need some details, because i can't find any information about my problem.</p>

答:
firstly you must copy the link above the video youtube when you click on share then choose integrate and select the src of the youtube video

then in your c sharp create :

and you're gonna see the video inside the web view

```<code>WebView webview = FindViewById<WebView>(Resource.Id.webView1);
        video =("the src of the youtube video");
        var uri = Android.Net.Uri.Parse(video);
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        webview.SetWebChromeClient(new WebChromeClient());
        webview.LoadUrl(video);
</code>```

Title: XAMARIN - add video from youtube

Body:
firstly you must copy the link above the video youtube when you click on share then choose integrate and select the src of the youtube video

then in your c sharp create :

and you're gonna see the video inside the web view

WebView webview = FindViewById<WebView>(Resource.Id.webView1);
        video =("the src of the youtube video");
        var uri = Android.Net.Uri.Parse(video);
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        webview.SetWebChromeClient(new WebChromeClient());
        webview.LoadUrl(video);


问:
How can I make a java program always running?
How can I make a java program such that it is always running on the system (such as a daemon or service), but only allow one instance of the program to run? I would like it to start either when I run the program or when the system starts (either is fine).</p>

答: Take a look at commons-daemon</p>

Body: Take a look at commons-daemon


问:
Setting edit text of fragment from Activity giving null pointer
I have just started using fragments. I have created a edit text in fragment and I want to fill it from activity but it is giving me null pointer exception. May be OnCreateView runs after fragmenttransaction is committed. I have made it working from another way but I am just a little curious why it is not working. I have searched it but could not find answer of my problem. Any help would be appreciated

Here is my code In activity:

```<code>FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();

mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception
</code>```

Then in fragment class:

```<code>public class Myfragment extends Fragment {
    EditText edittext_fragment;

    public static Myfragment newInstance() {
        return new Myfragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
        InitializeFragment(myInflatedView);
        return myInflatedView;
    }

    private void InitializeFragment(View myInflatedView) {
        edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
    }

    public void set_fragment_editext(String value) {
        edittext_fragment.setText(value);
    }

}
</code>```

答:
oncreateview is called after you call the setText function, hence the null pointer.

Pass the string as an argument.

```<code>public class Myfragment extends Fragment {
EditText edittext_fragment;
String textViewText;

public static Myfragment newInstance(String textViewText){
this.textViewText = textViewText;
return new Myfragment();
}

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
InitializeFragment(myInflatedView);
set_fragment_editext(textViewText);
return myInflatedView;
}

private void InitializeFragment(View myInflatedView) {
edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
}
private void set_fragment_editext(String value) {
edittext_fragment.setText(value);
}
}
</code>```

Activity code:

```<code>Myfragment mFragment = Myfragment.newInstance("Hello World");
</code>```

Body:
I have just started using fragments. I have created a edit text in fragment and I want to fill it from activity but it is giving me null pointer exception. May be OnCreateView runs after fragmenttransaction is committed. I have made it working from another way but I am just a little curious why it is not working. I have searched it but could not find answer of my problem. Any help would be appreciated

Here is my code In activity:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();

mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception

Then in fragment class:

public class Myfragment extends Fragment {
    EditText edittext_fragment;

    public static Myfragment newInstance() {
        return new Myfragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
        InitializeFragment(myInflatedView);
        return myInflatedView;
    }

    private void InitializeFragment(View myInflatedView) {
        edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
    }

    public void set_fragment_editext(String value) {
        edittext_fragment.setText(value);
    }

}

Body:
oncreateview is called after you call the setText function, hence the null pointer.

Pass the string as an argument.

public class Myfragment extends Fragment {
EditText edittext_fragment;
String textViewText;

public static Myfragment newInstance(String textViewText){
this.textViewText = textViewText;
return new Myfragment();
}

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
InitializeFragment(myInflatedView);
set_fragment_editext(textViewText);
return myInflatedView;
}

private void InitializeFragment(View myInflatedView) {
edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
}
private void set_fragment_editext(String value) {
edittext_fragment.setText(value);
}
}

Activity code:

Myfragment mFragment = Myfragment.newInstance("Hello World");


问:
How to display specific img on li hover without get request in react?
I have 4 boxes(
 elements) and 4 images. Task is to show specific image when user hovers specific box. If user hovers over box 0 show image 0 if 1 show image 1.

On hover I update the state currantBox(for example currantBox: 1) and pass it to the img src attribute like so:

```<code><img src={this.props.content[this.props.currantBox]}/>
</code>```

content is a JSON array with img paths. Problem is that react on each hover ie render ie state update React makes get request to download the image, which is not efficient at all.

What is the best way to implement my idea or fix currant implementation?

答:
You could pre-load the images:

```<code>componentDidMount() {
  let loaded = 0;
  this.allLoaded = false;
  this.props.content.forEach(src => {
    var image = new Image();
    image.onLoad = function() {
      console.log('image is now loaded');
      loaded = loaded + 1;
      if (loaded === this.props.content.length) this.allLoaded = true;
    };
    image.src = src;
  }
}
</code>```

With the above code, you can now check this.allLoaded before displaying anything. Note that this is a simple implementation and relies on the props never changing. If the props are expected to change after mount you may want to code something slightly more complex which accounts for that. But this should give you an idea on how to pre-load your images.

Body:
I have 4 boxes(
 elements) and 4 images. Task is to show specific image when user hovers specific box. If user hovers over box 0 show image 0 if 1 show image 1.

On hover I update the state currantBox(for example currantBox: 1) and pass it to the img src attribute like so:

content is a JSON array with img paths. Problem is that react on each hover ie render ie state update React makes get request to download the image, which is not efficient at all.

What is the best way to implement my idea or fix currant implementation?

Body:
You could pre-load the images:

componentDidMount() {
  let loaded = 0;
  this.allLoaded = false;
  this.props.content.forEach(src => {
    var image = new Image();
    image.onLoad = function() {
      console.log('image is now loaded');
      loaded = loaded + 1;
      if (loaded === this.props.content.length) this.allLoaded = true;
    };
    image.src = src;
  }
}

With the above code, you can now check this.allLoaded before displaying anything. Note that this is a simple implementation and relies on the props never changing. If the props are expected to change after mount you may want to code something slightly more complex which accounts for that. But this should give you an idea on how to pre-load your images.


问:
replace NAs in a column of a data.table with means of the same column grouped by a factor
I have the following sample data table

```<code>steps.dt = data.table(steps=rep(0:2, each=3),
date=as.factor(rep(c("10/2/2012", "10/3/2012", "10/4/2012"), each = 3)), interval = as.factor(rep(c(0,5,10), each = 3)))
</code>```

inserting a few NAs

```<code>steps.dt[c(2,5,8),"steps"]=NA
</code>```

the table now looks like this

```<code>   steps      date interval
1:     0 10/2/2012        0
2:    NA 10/2/2012        0
3:     0 10/2/2012        0
4:     1 10/3/2012        5
5:    NA 10/3/2012        5
6:     1 10/3/2012        5
7:     2 10/4/2012       10
8:    NA 10/4/2012       10
9:     2 10/4/2012       10
</code>```

Now, I am trying to replace the NAs in the column "steps" with the means of steps grouped by the factor "interval"

I have looked at some of the posts on SO like this but that I need the replacement to be grouped by a factor is complicating it. Is there a way to do this without using a loop? thank you!

答:
Solution using dplyr</p>

```<code>library(dplyr)
steps.dt = steps.dt %>% group_by(interval) %>%
                        mutate(steps = ifelse(is.na(steps),mean(steps,na.rm = T),steps))
</code>```

Body:
I have the following sample data table

steps.dt = data.table(steps=rep(0:2, each=3),
date=as.factor(rep(c("10/2/2012", "10/3/2012", "10/4/2012"), each = 3)), interval = as.factor(rep(c(0,5,10), each = 3)))

inserting a few NAs

steps.dt[c(2,5,8),"steps"]=NA

the table now looks like this

   steps      date interval
1:     0 10/2/2012        0
2:    NA 10/2/2012        0
3:     0 10/2/2012        0
4:     1 10/3/2012        5
5:    NA 10/3/2012        5
6:     1 10/3/2012        5
7:     2 10/4/2012       10
8:    NA 10/4/2012       10
9:     2 10/4/2012       10

Now, I am trying to replace the NAs in the column "steps" with the means of steps grouped by the factor "interval"

I have looked at some of the posts on SO like this but that I need the replacement to be grouped by a factor is complicating it. Is there a way to do this without using a loop? thank you!

Body:
Solution using dplyr

library(dplyr)
steps.dt = steps.dt %>% group_by(interval) %>%
                        mutate(steps = ifelse(is.na(steps),mean(steps,na.rm = T),steps))


问:
What does {$value} means inside of a curl post request?
I have the following curl post request

```<code>   $Curl_Session = curl_init($url);
        curl_setopt($Curl_Session, CURLOPT_POST, count($post));
        curl_setopt($Curl_Session, CURLOPT_POSTFIELDS, "login={$username}&password={$password}");
        curl_setopt($Curl_Session, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($Curl_Session, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($Curl_Session, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt($Curl_Session, CURLOPT_SSL_VERIFYPEER, false );
        $request = curl_exec($Curl_Session);
</code>```

what does the use of {} means? Can this request be vulnerable to xss ( i mean the login and password parameters)?

It's a curl request with the type set to application/json

答:
http://php.net/manual/en/language.types.string.php

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {.

Yes, the way you're using it is vulnerable to injection. You're better passing an array of POST fields, like this:

```<code>curl_setopt($Curl_Session, CURLOPT_POSTFIELDS, ['login' => $username, 'password' => $password];
</code>```

Body:
I have the following curl post request

   $Curl_Session = curl_init($url);
        curl_setopt($Curl_Session, CURLOPT_POST, count($post));
        curl_setopt($Curl_Session, CURLOPT_POSTFIELDS, "login={$username}&password={$password}");
        curl_setopt($Curl_Session, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($Curl_Session, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($Curl_Session, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt($Curl_Session, CURLOPT_SSL_VERIFYPEER, false );
        $request = curl_exec($Curl_Session);

what does the use of {} means? Can this request be vulnerable to xss ( i mean the login and password parameters)?

It's a curl request with the type set to application/json

Body:
http://php.net/manual/en/language.types.string.php

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {.

Yes, the way you're using it is vulnerable to injection. You're better passing an array of POST fields, like this:

curl_setopt($Curl_Session, CURLOPT_POSTFIELDS, ['login' => $username, 'password' => $password];


问:
Android app layout: elements appear on different places
I'm developing Android version of our iOS app, but having layout issues. Elements appear on different places on different screen sizes. Here's the iOS counterpart I have to replicate.
iPhone's layout

Here's my app. What will be the best layout combination to replicate the iOS counterpart.

Here's my version:

Android layout image

Here's the xml of my layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <TextView
        android:id="@+id/text_rssi"
        android:layout_width="@dimen/_90sdp"
        android:layout_height="@dimen/_16sdp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_50sdp"
        android:background="@drawable/btn_indicators_disconnect" />

    <TextView
        android:id="@+id/text_rssi_val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_rssi"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_5sdp"
        android:text="0"
        android:textColor="#FFF"
        android:textSize="@dimen/_12sdp" />

    <LinearLayout
        android:id="@+id/layout_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/searching_all_off_circle"
        android:orientation="vertical"
        android:padding="@dimen/_5sdp"
        android:layout_below="@+id/text_rssi_val"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="53dp">

        <Button
            android:id="@+id/btn_CheckLister"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="@dimen/_45sdp"
            android:background="@drawable/searching_all_off" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_btnLock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_parked_location"
        android:layout_marginBottom="@dimen/_20sdp">

        <Button
            android:id="@+id/btn_unlock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="@dimen/_65sdp"
            android:background="@drawable/unlock_unpressed" />

        <Button
            android:id="@+id/btn_lock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/_65sdp"
            android:background="@drawable/lock_unpressed" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn_parked_location"
        android:layout_width="@dimen/_150sdp"
        android:layout_height="@dimen/_35sdp"
        android:layout_above="@+id/ble_list_devices"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="@dimen/_12sdp"
        android:background="@drawable/parked_icon" />

    <TextView
        android:id="@+id/ble_list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#565656"
        android:padding="@dimen/_8sdp"
        android:text="Searching..."
        android:textAlignment="center"
        android:textColor="#FFF"
        android:textSize="@dimen/_14sdp" />

</RelativeLayout>
</code>```

答:
That's because you are using a RelativeLayout, which aligns its contents relative to the root element in the ViewGroup. According to the official documentation -

RelativeLayout is a view group that displays child views in relative
  positions. The position of each view can be specified as relative to
  sibling elements (such as to the left-of or below another view) or in
  positions relative to the parent RelativeLayout area (such as aligned
  to the bottom, left or center).

In my opinion, elements should adjust their positions accordingly for all screen sizes, and for that, there is a better option than the RelativeLayout, and that is the ConstraintLayout, which works similar to how ConstraintLayout on iOS.

Body:
I'm developing Android version of our iOS app, but having layout issues. Elements appear on different places on different screen sizes. Here's the iOS counterpart I have to replicate.
iPhone's layout

Here's my app. What will be the best layout combination to replicate the iOS counterpart.

Here's my version:

Android layout image

Here's the xml of my layout:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <TextView
        android:id="@+id/text_rssi"
        android:layout_width="@dimen/_90sdp"
        android:layout_height="@dimen/_16sdp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_50sdp"
        android:background="@drawable/btn_indicators_disconnect" />

    <TextView
        android:id="@+id/text_rssi_val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_rssi"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_5sdp"
        android:text="0"
        android:textColor="#FFF"
        android:textSize="@dimen/_12sdp" />

    <LinearLayout
        android:id="@+id/layout_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/searching_all_off_circle"
        android:orientation="vertical"
        android:padding="@dimen/_5sdp"
        android:layout_below="@+id/text_rssi_val"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="53dp">

        <Button
            android:id="@+id/btn_CheckLister"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="@dimen/_45sdp"
            android:background="@drawable/searching_all_off" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_btnLock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_parked_location"
        android:layout_marginBottom="@dimen/_20sdp">

        <Button
            android:id="@+id/btn_unlock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="@dimen/_65sdp"
            android:background="@drawable/unlock_unpressed" />

        <Button
            android:id="@+id/btn_lock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/_65sdp"
            android:background="@drawable/lock_unpressed" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn_parked_location"
        android:layout_width="@dimen/_150sdp"
        android:layout_height="@dimen/_35sdp"
        android:layout_above="@+id/ble_list_devices"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="@dimen/_12sdp"
        android:background="@drawable/parked_icon" />

    <TextView
        android:id="@+id/ble_list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#565656"
        android:padding="@dimen/_8sdp"
        android:text="Searching..."
        android:textAlignment="center"
        android:textColor="#FFF"
        android:textSize="@dimen/_14sdp" />

</RelativeLayout>


问:
Sum specific columns using loop
I have a table that looks like this: (Note: this is just a partial table, my real table has several more columns of qresult_# and trial_#)

```<code>Contract    FA     NAAR    q    trial_1   qresult_1    trial_2    qresult_2
CM300      9746    47000  0.5    0.4352      d          0.7534        l
UL350     80000      0    0.01   0.9287      l          0.2336        l
RAD34     50000    10000  0.943  0.6161      d          0.1545        d
</code>```

The table is calculated using a for loop, so that the columns trial_i and qresult_i are created for as many columns as I wish. This is the code used to create the table:

```<code>testdata <- data.frame(Contract = as.character(c("CM300","UL350","RAD34")),
                  FA = as.numeric(as.character(c("9746","80000","50000"))),
                  NAAR = as.numeric(as.character(c("47000","0","10000"))),
                  q = as.numeric(as.character(c("0.50","0.01","0.943"))))

trialmax <- 2
for(i in 1:trialmax){
   trial <- runif(3, min = 0, max = 1)
   testdata[ , paste0("trial_", i)] <- trial
   testdata[ , paste0("qresult_", i)] <- ifelse(trial >= testdata$q, "l", "d")
}
</code>```

Here is my question: I would like to sum the FA column and the NAAR column for all contracts labeled 'd', and all contracts labeled 'l' for each trial individually. So for trial_1, the FA for 'd' would be 59746 and NAAR for 'd' would be 57000, the FA for 'l' would be 80000 and the NAAR for 'l' would be 0. And repeat this for each trial. The end result would be four values for each trial.

I haven't found a code that allows me to run it successfully. I would like the expected output to be four values for each trial. Perhaps look something like this, repeated for each trial:

```<code>trial1_d_fa <- if(trial_1 = 'd') {sum(testdata$FA)}
trial1_l_fa <- if(trial_1 = 'l') {sum (testdata$FA)}
trial1_d_naar <- if(trial_1 = 'd') {sum(testdata$NAAR)}
trial1_l_naar <- if(trial_1 = 'l') {sum(testdata$NAAR)}
</code>```

I am struggling with getting a for loop to work, since the column name in the code is defined using i. I am new to R, so any tips are greatly appreciated!

EDIT: Update

The code suggested by bouncyball below worked on my test data, but when I used it on my real data, I got the following error message:

```<code>Error in match.names(clabs, names(xi)) :
names do not match previous names
</code>```

Looking through this website, I can see it is an issue with the rbind() function. I have tried converting the column names to match my data, but I continue to get the same error.

Here is the beginning of my dataset head(data). Any advice is appreciated!

```<code>Contract    FA     NAAR      q      trial_1    qresult_1    trial_2    qresult_2
CM20002U  10000   4902.34   0.0255   0.7921        l        0.5182       l
CM20051U  45700   28788.81  0.0121   0.0083        d        0.0707       l
CM20076U  50000   20824.54  0.1054   0.5616        l        0.0915       d
</code>```

答:
Here's a way using lapply and by functions. We need to repeat the call to do.call('rbind', ...) because there are two entries in the list resulting from lapply:

```<code>trial_max <- 2

do.call('rbind',
        do.call('rbind',
                lapply(paste0('qresult_', 1:trial_max), function(q){
                  by(testdata, testdata[,q], FUN = function(d)
                    data.frame('id' = q,
                               'val' = unique(d[,q]),
                               'sum_FA' = sum(d$FA),
                               'sum_NAAR' = sum(d$NAAR),
                               stringsAsFactors = FALSE))
})))

         id val sum_FA sum_NAAR
1 qresult_1   d  59746    57000
2 qresult_2   d  59746    57000
3 qresult_1   l  80000        0
4 qresult_2   l  80000        0
</code>```

Using lapply, we iterate over the qresult_i columns, then we use the by function to apply a function to testdata split by the values in the respective qresult_i columns. Finally, we store the results in a data.frame.

The results are stored in a data.frame, which should make it easy to subset and get the values you're interested in.

Title: Sum specific columns using loop

Body:
I have a table that looks like this: (Note: this is just a partial table, my real table has several more columns of qresult_# and trial_#)

Contract    FA     NAAR    q    trial_1   qresult_1    trial_2    qresult_2
CM300      9746    47000  0.5    0.4352      d          0.7534        l
UL350     80000      0    0.01   0.9287      l          0.2336        l
RAD34     50000    10000  0.943  0.6161      d          0.1545        d

The table is calculated using a for loop, so that the columns trial_i and qresult_i are created for as many columns as I wish. This is the code used to create the table:

testdata <- data.frame(Contract = as.character(c("CM300","UL350","RAD34")),
                  FA = as.numeric(as.character(c("9746","80000","50000"))),
                  NAAR = as.numeric(as.character(c("47000","0","10000"))),
                  q = as.numeric(as.character(c("0.50","0.01","0.943"))))

trialmax <- 2
for(i in 1:trialmax){
   trial <- runif(3, min = 0, max = 1)
   testdata[ , paste0("trial_", i)] <- trial
   testdata[ , paste0("qresult_", i)] <- ifelse(trial >= testdata$q, "l", "d")
}

Here is my question: I would like to sum the FA column and the NAAR column for all contracts labeled 'd', and all contracts labeled 'l' for each trial individually. So for trial_1, the FA for 'd' would be 59746 and NAAR for 'd' would be 57000, the FA for 'l' would be 80000 and the NAAR for 'l' would be 0. And repeat this for each trial. The end result would be four values for each trial.

I haven't found a code that allows me to run it successfully. I would like the expected output to be four values for each trial. Perhaps look something like this, repeated for each trial:

trial1_d_fa <- if(trial_1 = 'd') {sum(testdata$FA)}
trial1_l_fa <- if(trial_1 = 'l') {sum (testdata$FA)}
trial1_d_naar <- if(trial_1 = 'd') {sum(testdata$NAAR)}
trial1_l_naar <- if(trial_1 = 'l') {sum(testdata$NAAR)}

I am struggling with getting a for loop to work, since the column name in the code is defined using i. I am new to R, so any tips are greatly appreciated!

EDIT: Update

The code suggested by bouncyball below worked on my test data, but when I used it on my real data, I got the following error message:

Error in match.names(clabs, names(xi)) :
names do not match previous names

Looking through this website, I can see it is an issue with the rbind() function. I have tried converting the column names to match my data, but I continue to get the same error.

Here is the beginning of my dataset head(data). Any advice is appreciated!

Contract    FA     NAAR      q      trial_1    qresult_1    trial_2    qresult_2
CM20002U  10000   4902.34   0.0255   0.7921        l        0.5182       l
CM20051U  45700   28788.81  0.0121   0.0083        d        0.0707       l
CM20076U  50000   20824.54  0.1054   0.5616        l        0.0915       d

Body:
Here's a way using lapply and by functions. We need to repeat the call to do.call('rbind', ...) because there are two entries in the list resulting from lapply:

trial_max <- 2

do.call('rbind',
        do.call('rbind',
                lapply(paste0('qresult_', 1:trial_max), function(q){
                  by(testdata, testdata[,q], FUN = function(d)
                    data.frame('id' = q,
                               'val' = unique(d[,q]),
                               'sum_FA' = sum(d$FA),
                               'sum_NAAR' = sum(d$NAAR),
                               stringsAsFactors = FALSE))
})))

         id val sum_FA sum_NAAR
1 qresult_1   d  59746    57000
2 qresult_2   d  59746    57000
3 qresult_1   l  80000        0
4 qresult_2   l  80000        0

Using lapply, we iterate over the qresult_i columns, then we use the by function to apply a function to testdata split by the values in the respective qresult_i columns. Finally, we store the results in a data.frame.

The results are stored in a data.frame, which should make it easy to subset and get the values you're interested in.


问:
Multiple Machines -- Process Many Files Concurrently?
I need to concurrently process a large amount of files (thousands of different files, with avg. size of 2MB per file).

All the information is stored on one (1.5TB) network hard drive, and will be accessed (read) by about 30 different machines. For efficiency, each machine will be reading (and processing) different files (there are thousands of files that need to be processed).

Every machine -- following its reading of a file from the 'incoming' folder on the 1.5TB hard drive -- will be processing the information and be ready to output the processed information back to the 'processed' folder on the 1.5TB drive. the processed information for every file is of roughly the same average size as the input files (about ~2MB per file).

Are there any 'do' and 'donts' when one is building such an operation? is it a problem to have 30 machines or so read (or write) information to the same network drive, at the same time?
(note: existing files will only be read, not appended/written; new files will be created from scratch, so there are no issues of multiple access to the same file...).
Are there any bottlenecks that I should expect?

(I am use Linux, Ubuntu 10.04 LTS on all machines if it all matters)

答:
You need to be careful that two worker processes don't pick up (and try to do) the same piece of work at the same time.

Unfortunately, NFS filesystems don't have semantics that allow you to easily do that.

So what I'd recommend is to use something like Gearman and a producer/consumer model, where one process gives out work to whoever is available to do it.

Another possibility is to have a database (e.g. mysql) with a table of all tasks, and have the processes atomically "claim" tasks for themselves.

But all of this is only worthwhile if your processes are mostly CPU-bound. If you're trying to get more IO bandwidth (or operations) out of your NAS by using multiple clients, it's not going to work.

I am assuming that you will be running at least gigabit ethernet here (or it's probably not worth it).

Have you tried running multiple processes on the same machine?


问:
Condition validation in for loop
my below code to get square root works fine

```<code>package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(Sqrt(9))
}

func Sqrt(x float64) float64 {
    v := float64(1)
    p := float64(0)

    for {
        p = v
        v -= (v*v - x) / (2 * v)
        fmt.Println(toFixed(p, 5), toFixed(v, 5))
        if toFixed(p, 5) == toFixed(v, 5) {
            break
        }
    }

    return v
}

func toFixed(num float64, precision int) float64 {
    output := math.Pow(10, float64(precision))
    return float64(round(num*output)) / output
}

func round(num float64) int {
    return int(num + math.Copysign(0.5, num))
}
</code>```

but if I change the for loop in Sqrt function and remove if break from the loop like below then control flow do not get into for loop and Sqrt() function quits with value as 1.

```<code>for toFixed(p, 5) == toFixed(v, 5) {
    p = v
    v -= (v*v - x) / (2 * v)
    fmt.Println(toFixed(p, 5), toFixed(v, 5))
}
</code>```

Can you please suggest issue in above code?

Thanks

答:
You should be checking for inequality != in your for condition.

I modified your code and it seems to be working fine now:

```<code>package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(Sqrt(9))
}

func Sqrt(x float64) float64 {
    v := float64(1)
    p := float64(0)

    for toFixed(p, 5) != toFixed(v, 5) {
        p = v
        v -= (v*v - x) / (2 * v)
    }

    return v
}

func toFixed(num float64, precision int) float64 {
    output := math.Pow(10, float64(precision))
    return float64(round(num*output)) / output
}

func round(num float64) int {
    return int(num + math.Copysign(0.5, num))
}
</code>```

Title: Condition validation in for loop

Body:
my below code to get square root works fine

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(Sqrt(9))
}

func Sqrt(x float64) float64 {
    v := float64(1)
    p := float64(0)

    for {
        p = v
        v -= (v*v - x) / (2 * v)
        fmt.Println(toFixed(p, 5), toFixed(v, 5))
        if toFixed(p, 5) == toFixed(v, 5) {
            break
        }
    }

    return v
}

func toFixed(num float64, precision int) float64 {
    output := math.Pow(10, float64(precision))
    return float64(round(num*output)) / output
}

func round(num float64) int {
    return int(num + math.Copysign(0.5, num))
}

but if I change the for loop in Sqrt function and remove if break from the loop like below then control flow do not get into for loop and Sqrt() function quits with value as 1.

for toFixed(p, 5) == toFixed(v, 5) {
    p = v
    v -= (v*v - x) / (2 * v)
    fmt.Println(toFixed(p, 5), toFixed(v, 5))
}

Can you please suggest issue in above code?

Thanks

Body:
You should be checking for inequality != in your for condition.

I modified your code and it seems to be working fine now:

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(Sqrt(9))
}

func Sqrt(x float64) float64 {
    v := float64(1)
    p := float64(0)

    for toFixed(p, 5) != toFixed(v, 5) {
        p = v
        v -= (v*v - x) / (2 * v)
    }

    return v
}

func toFixed(num float64, precision int) float64 {
    output := math.Pow(10, float64(precision))
    return float64(round(num*output)) / output
}

func round(num float64) int {
    return int(num + math.Copysign(0.5, num))
}


问:
plaese can anyone help me to draw radial seekbar
Radial SeekBar

Please help me to how to draw a Radial SeekBar, Plaese check the image url that is actual design of seek bar. I tried many ways but not worked out properly.

I tried like this

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
tools:context="com.scanner.com.protracterview.MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="0"
    android:id="@+id/number"
    android:textSize="18sp"
    android:layout_marginBottom="30dp"
    android:gravity="center"/>

<com.goodiebag.protractorview.ProtractorView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:arcColor="#91d8f7"
    app:arcProgressColor="#91d8f7"
    app:tickColor="#4a4a4a"
    app:indicatorType="line"
    app:tickProgressColor="#abe6"
    app:textColor="#000"
    app:textProgressColor="#FF0000"
    app:angleTextSize="0dp"
    app:arcWidth="2dp"
    app:progressWidth="2dp"
    app:tickOffset="18dp"
    app:tickLength="0dp"
    app:angle="15"
    android:id="@+id/protrat"
    app:tickIntervals="15"
    app:ticksBetweenLabel="three"
    app:touchInside="true"
    app:roundEdges="true"
    android:layout_below="@+id/number"
    android:layout_alignParentEnd="true" />
</code>```

答:
If you want something like this -
Follow this - (Matt Joseph)

There is a class CircularSeekBar.java paste it in your project

attrs.xml (in res/values/attrs.xml)

and your xml file should be like this,

```<code><mrbrown.arcseekbar.CircularSeekBar
    android:id="@+id/circularSeekBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:start_angle="180"
    app:end_angle="0"
    app:circle_x_radius="500dp"
    app:circle_y_radius="500dp"
    app:use_custom_radii="true"
    app:progress="0"
    app:max="100"
    app:pointer_alpha_ontouch="100"
    app:pointer_color="#0174DF"
    app:pointer_halo_color="#880174DF"/>
</code>```

Body:
Radial SeekBar

Please help me to how to draw a Radial SeekBar, Plaese check the image url that is actual design of seek bar. I tried many ways but not worked out properly.

I tried like this

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
tools:context="com.scanner.com.protracterview.MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="0"
    android:id="@+id/number"
    android:textSize="18sp"
    android:layout_marginBottom="30dp"
    android:gravity="center"/>

<com.goodiebag.protractorview.ProtractorView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:arcColor="#91d8f7"
    app:arcProgressColor="#91d8f7"
    app:tickColor="#4a4a4a"
    app:indicatorType="line"
    app:tickProgressColor="#abe6"
    app:textColor="#000"
    app:textProgressColor="#FF0000"
    app:angleTextSize="0dp"
    app:arcWidth="2dp"
    app:progressWidth="2dp"
    app:tickOffset="18dp"
    app:tickLength="0dp"
    app:angle="15"
    android:id="@+id/protrat"
    app:tickIntervals="15"
    app:ticksBetweenLabel="three"
    app:touchInside="true"
    app:roundEdges="true"
    android:layout_below="@+id/number"
    android:layout_alignParentEnd="true" />

Body:
If you want something like this -
Follow this - (Matt Joseph)

There is a class CircularSeekBar.java paste it in your project

attrs.xml (in res/values/attrs.xml)

and your xml file should be like this,

<mrbrown.arcseekbar.CircularSeekBar
    android:id="@+id/circularSeekBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:start_angle="180"
    app:end_angle="0"
    app:circle_x_radius="500dp"
    app:circle_y_radius="500dp"
    app:use_custom_radii="true"
    app:progress="0"
    app:max="100"
    app:pointer_alpha_ontouch="100"
    app:pointer_color="#0174DF"
    app:pointer_halo_color="#880174DF"/>


问:
How to change warning text when pattern is used in input?
When I use pattern in input like this:

```<code><input type="text" value="" pattern="(\d|(\d,\d{0,2}))">
</code>```

I receive popup warning with text. How can I easily change this text?

答:
```<code><input type="text" value="" pattern="(\d|(\d,\d{0,2}))" oninvalid="this.setCustomValidity('ERROR_TEXT')" oninput="this.setCustomValidity('')"/>
</code>```

Try this code, corrected to clear after input...

Body:
When I use pattern in input like this:

<input type="text" value="" pattern="(\d|(\d,\d{0,2}))">

I receive popup warning with text. How can I easily change this text?

Body:
<input type="text" value="" pattern="(\d|(\d,\d{0,2}))" oninvalid="this.setCustomValidity('ERROR_TEXT')" oninput="this.setCustomValidity('')"/>

Try this code, corrected to clear after input...


问:
Head First C string.h related questions
```<code>#include <stdio.h>
#include <string.h>

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}
</code>```

Above is a function that will display a string backward on the screen. But I don't understand the 7th line (char *t = s+ len-1;). Could anybody explain this is spoken English please?

答:
Main logic behind this functions is that this code:

```<code>char *t = s+ len-1;
</code>```

return a pointer to the address of the last char in the char pointer you are passing to the function. The loop prints it by decrementing it:

```<code>t = t - 1;
</code>```

So in simple words it prints the char pointer from backwards.

Title: Head First C string.h related questions

Body:
#include <stdio.h>
#include <string.h>

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}

Above is a function that will display a string backward on the screen. But I don't understand the 7th line (char *t = s+ len-1;). Could anybody explain this is spoken English please?

Body:
Main logic behind this functions is that this code:

char *t = s+ len-1;

return a pointer to the address of the last char in the char pointer you are passing to the function. The loop prints it by decrementing it:

t = t - 1;

So in simple words it prints the char pointer from backwards.


问:
Start Background Task using ASP.Net Core Middleware
I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}
</code>```

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?

答:
Instead of

```<code>await serviceWithAsyncTask .DoAsync();
</code>```

you could use

```<code> ThreadPool.QueueUserWorkItem(delegate {
       SomeMethod();
   });
</code>```

In this approach an additional thread will be used from the thread pool which is of course a requirement if you want the code to run on a thread other than the main thread :-)

Any code placed after this block will run immediately.  Also note that if your web server process (kestral) is recycled by IIS or whatever reverse proxy you are using then your background worker will be aborted immediately.   So your background worker needs to be written defensively with this in mind.

Also please note that SomeMethod() is not itself an async method.  But it's being called from a background thread so it's running asyncronously (i.e. independent of the main thread.)

Body:
I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?

Body:
Instead of

await serviceWithAsyncTask .DoAsync();

you could use

 ThreadPool.QueueUserWorkItem(delegate {
       SomeMethod();
   });

In this approach an additional thread will be used from the thread pool which is of course a requirement if you want the code to run on a thread other than the main thread :-)

Any code placed after this block will run immediately.  Also note that if your web server process (kestral) is recycled by IIS or whatever reverse proxy you are using then your background worker will be aborted immediately.   So your background worker needs to be written defensively with this in mind.

Also please note that SomeMethod() is not itself an async method.  But it's being called from a background thread so it's running asyncronously (i.e. independent of the main thread.)


问:
Displaying a static image using React, Typescript and Webpack
I'm attempting to display an image in a React component as part of a project using webpack and webpack-dev-server.

So far I have completed the following steps:

Used npm to install file-loader

Updated webpack.config.js to add a loader for image files

Imported the image I want into my component

Used the import in my img tag

Having taken these steps, webpack fails to compile with a 'cannot find module' error:

```<code>ERROR in [at-loader] ./src/components/App.tsx:4:26
    TS2307: Cannot find module '../images/kitten-header.jpg'.
</code>```

My folder structure is as follows:

```<code>/dist
   /images
      kitten-header.jpg
   bundle.js
   bundle.js.map
/node_modules
   (content ignored for brevity)
/src
   /components
      App.tsx
   /images
      kitten-header.jpg
   /styles
      App.less
   index.tsx
index.html
package.json
tsconfig.json
webpack.config.js
</code>```

The new loader that I added to my webpack.config.js is:

```<code>test: /\.(jpe?g|gif|png|svg)$/, loader: "file-loader?name=./images/[name].[ext]"
</code>```

I've imported the image file, in App.tsx, like this:

```<code>import kittenHeader from '../images/kitten-header.jpg';
</code>```

...and used the import in an img tag like this:

```<code><img src={ kittenHeader } />
</code>```

Note: Full text of webpack.config.js and App.tsx were provided until I got a little bit closer to the answer and realized they weren't relevant (see update 1).

I assume I'm making some very trivial error with regards to the relative path in the import.  As you can imagine, I've tried various alternatives.

Can anyone provide some insight?

For reference, as I'm continuously hitting articles and questions relating to the wrong version of webpack, here are my versions:

React 15.5.4

Webpack 2.6.1

Webpack-dev-server 2.4.5

TypeScript 2.3.2

Update 1: 2017.06.05

So, looking at this SO question and this post on Medium, I've been able to identify that the problem lies not with how I've used webpack, but with that fact that I'm using TypeScript.  The error is a typescript error caused by the fact that the typescript compiler doesn't know what a .jpg file is.

Apparently, I'm going to need to provide a d.ts file or use a require statement.

Almost there...

答:
The error, TS2307: Cannot find module '../images/kitten-header.jpg', is highlighting that the TypeScript compiler does not understand the import of a .jpg file.

The webpack configuration is fine, as evidenced by the image file being copied to the dist folder successfully despite the compile error.

There are two ways that we can resolve the issue.

Firstly, we could bypass the TypeScript import by using a 'require' statement.  To do this, the import...

```<code>import kittenHeader from '../images/kitten-header.jpg';
</code>```

...can be replaced with a require...

```<code>const kittenHeader = require('../images/kitten-header.jpg');
</code>```

...and that should be all that's needed.

Note that, in my case I also needed to install some typings to support the 'require' statement.  Without these, I was getting a TS2304: Cannot find name 'require' error.

Originally I used @types/node, as described in this SO answer, but @EvanSebastian pointed out that node is intended to support writing NodeJS modules, which is not what I'm doing (see comments on the question).

I tried @types/webpack-env, as suggested, but this resulted in a TS2322: Type '{ src: {}; }' is not assignable to type 'HTMLProps<HTMLImageElement>'. error against the src property of my image tag.

Most recently, I've switched to using @types/requirejs, which I'm hoping is focused enough to avoid including a load of inappropriate additional types. It is currently working:

```<code>npm install @types/requirejs --save-dev
</code>```

Alternatively, we could keep the import and provide a d.ts file with type information declaring an appropriate module.  I've not been able to discover exactly what this file would look like.

Body:
I'm attempting to display an image in a React component as part of a project using webpack and webpack-dev-server.

So far I have completed the following steps:

Used npm to install file-loader

Updated webpack.config.js to add a loader for image files

Imported the image I want into my component

Used the import in my img tag

Having taken these steps, webpack fails to compile with a 'cannot find module' error:

ERROR in [at-loader] ./src/components/App.tsx:4:26
    TS2307: Cannot find module '../images/kitten-header.jpg'.

My folder structure is as follows:

/dist
   /images
      kitten-header.jpg
   bundle.js
   bundle.js.map
/node_modules
   (content ignored for brevity)
/src
   /components
      App.tsx
   /images
      kitten-header.jpg
   /styles
      App.less
   index.tsx
index.html
package.json
tsconfig.json
webpack.config.js

The new loader that I added to my webpack.config.js is:

test: /\.(jpe?g|gif|png|svg)$/, loader: "file-loader?name=./images/[name].[ext]"

I've imported the image file, in App.tsx, like this:

import kittenHeader from '../images/kitten-header.jpg';

...and used the import in an img tag like this:

Note: Full text of webpack.config.js and App.tsx were provided until I got a little bit closer to the answer and realized they weren't relevant (see update 1).

I assume I'm making some very trivial error with regards to the relative path in the import.  As you can imagine, I've tried various alternatives.

Can anyone provide some insight?

For reference, as I'm continuously hitting articles and questions relating to the wrong version of webpack, here are my versions:

React 15.5.4

Webpack 2.6.1

Webpack-dev-server 2.4.5

TypeScript 2.3.2

Update 1: 2017.06.05

So, looking at this SO question and this post on Medium, I've been able to identify that the problem lies not with how I've used webpack, but with that fact that I'm using TypeScript.  The error is a typescript error caused by the fact that the typescript compiler doesn't know what a .jpg file is.

Apparently, I'm going to need to provide a d.ts file or use a require statement.

Almost there...

Body:
The error, TS2307: Cannot find module '../images/kitten-header.jpg', is highlighting that the TypeScript compiler does not understand the import of a .jpg file.

The webpack configuration is fine, as evidenced by the image file being copied to the dist folder successfully despite the compile error.

There are two ways that we can resolve the issue.

Firstly, we could bypass the TypeScript import by using a 'require' statement.  To do this, the import...

import kittenHeader from '../images/kitten-header.jpg';

...can be replaced with a require...

const kittenHeader = require('../images/kitten-header.jpg');

...and that should be all that's needed.

Note that, in my case I also needed to install some typings to support the 'require' statement.  Without these, I was getting a TS2304: Cannot find name 'require' error.

Originally I used @types/node, as described in this SO answer, but @EvanSebastian pointed out that node is intended to support writing NodeJS modules, which is not what I'm doing (see comments on the question).

I tried @types/webpack-env, as suggested, but this resulted in a TS2322: Type '{ src: {}; }' is not assignable to type 'HTMLProps<HTMLImageElement>'. error against the src property of my image tag.

Most recently, I've switched to using @types/requirejs, which I'm hoping is focused enough to avoid including a load of inappropriate additional types. It is currently working:

npm install @types/requirejs --save-dev

Alternatively, we could keep the import and provide a d.ts file with type information declaring an appropriate module.  I've not been able to discover exactly what this file would look like.


问:
how to send an object to C# WCF service from PHP using SOAP
I'm having trouble sending a custom object thats defined as a datacontract in my WCF web service from PHP. I'm attempting to accomplish this via SOAP.

Here is what the dataContract looks like:

```<code>[DataContract]
    public class simplyCustomer
    {
        [DataMember]
        public int id;
        [DataMember]
        public string name;
        [DataMember]
        public string contact;
        [DataMember]
        public string street1;
        [DataMember]
        public string street2;
        [DataMember]
        public string city;
        [DataMember]
        ...
    }
</code>```

So I have a function that takes simplyCustomer as parameter on WCF service. The php can receive simplyCustomer just fine using another function that returns one. However, if I call the one that accepts it using this code in PHP:

```<code>$retVal = $simplyService->__soapCall("addCustomer",array('parameters'=>$params));
</code>```

The SOAP envelope that this call generates leaves the object NULL causing the WCF service to complain about null reference.

Here is the envelope that is generated:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:addCustomer/></SOAP-ENV:Body></SOAP-ENV:Envelope>
</code>```

The parameters should be where addCustomer is but there's nothing there.

Any help would be greatly appreciated!

Thanks!

答:
I faced the same issue when building a private project.

My solution was to use T4 to generate service- and datacontract proxies, maybe you find it useful. Message me if you have any questions, the templates are not tested to their full extent.

You find the templates on github, including sample servicecontracts/datacontracts:

https://github.com/schaermu/wcf-phpclient-t4

feel free to fork the project!

cheers

Body:
I'm having trouble sending a custom object thats defined as a datacontract in my WCF web service from PHP. I'm attempting to accomplish this via SOAP.

Here is what the dataContract looks like:

[DataContract]
    public class simplyCustomer
    {
        [DataMember]
        public int id;
        [DataMember]
        public string name;
        [DataMember]
        public string contact;
        [DataMember]
        public string street1;
        [DataMember]
        public string street2;
        [DataMember]
        public string city;
        [DataMember]
        ...
    }

So I have a function that takes simplyCustomer as parameter on WCF service. The php can receive simplyCustomer just fine using another function that returns one. However, if I call the one that accepts it using this code in PHP:

$retVal = $simplyService->__soapCall("addCustomer",array('parameters'=>$params));

The SOAP envelope that this call generates leaves the object NULL causing the WCF service to complain about null reference.

Here is the envelope that is generated:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:addCustomer/></SOAP-ENV:Body></SOAP-ENV:Envelope>

The parameters should be where addCustomer is but there's nothing there.

Any help would be greatly appreciated!

Thanks!


问:
How to use headers attribute to make table A11Y compliant?
I'm creating an application that should be WCAG 2.0 compliant.
I'm checking my pages using AChecker and I'm experiencing some problems with table. I get the following 2 issues:

Data table with both row and column headers does not use scope to identify cells

Data table with more than one row/column of headers does not use id and headers attributes to identify cells

Here is the source code of my table:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it" lang="it">
    <body>
        <table class="ui celled center aligned unstackable table seven column day">
            <thead>
                <tr>
                    <th colspan="7">
                        <span class="link">Giugno 2017</span>
                        <span class="prev link">
                            <span class="ifix chevron left icon"></span>
                        </span>
                        <span class="next link">
                            <span class="ifix chevron right icon"></span>
                        </span>
                    </th>
                </tr>
                <tr>
                    <th>Dom</th>
                    <th>Lun</th>
                    <th>Mar</th>
                    <th>Mer</th>
                    <th>Gio</th>
                    <th>Ven</th>
                    <th>Sab</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="link adjacent disabled">28</td>
                    <td class="link adjacent disabled">29</td>
                    <td class="link adjacent disabled">30</td>
                    <td class="link adjacent disabled">31</td>
                    <td class="link">1</td>
                    <td class="link">2</td>
                    <td class="link">3</td>
                </tr>
                <tr>
                    <td class="link">4</td>
                    <td class="link today focus">5</td>
                    <td class="link">6</td>
                    <td class="link">7</td>
                    <td class="link">8</td>
                    <td class="link">9</td>
                    <td class="link">10</td>
                </tr>
                <tr>
                    <td class="link">11</td>
                    <td class="link">12</td>
                    <td class="link">13</td>
                    <td class="link">14</td>
                    <td class="link">15</td>
                    <td class="link">16</td>
                    <td class="link">17</td>
                </tr>
                <tr>
                    <td class="link">18</td>
                    <td class="link">19</td>
                    <td class="link">20</td>
                    <td class="link">21</td>
                    <td class="link">22</td>
                    <td class="link">23</td>
                    <td class="link">24</td>
                </tr>
                <tr>
                    <td class="link">25</td>
                    <td class="link">26</td>
                    <td class="link">27</td>
                    <td class="link">28</td>
                    <td class="link">29</td>
                    <td class="link">30</td>
                    <td class="link adjacent disabled">1</td>
                </tr>
                <tr>
                    <td class="link adjacent disabled">2</td>
                    <td class="link adjacent disabled">3</td>
                    <td class="link adjacent disabled">4</td>
                    <td class="link adjacent disabled">5</td>
                    <td class="link adjacent disabled">6</td>
                    <td class="link adjacent disabled">7</td>
                    <td class="link adjacent disabled">8</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>
</code>```

Link to related Plunker.

According to this W3C documentation page do you know the right way to use headers in my case?

I tried to do it by myself and I edited my code. Here is the result:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it" lang="it">
    <body>
        <table class="ui celled center aligned unstackable table seven column day">
            <thead>
                <tr>
                    <th id="month" scope="col" colspan="7">
                        <span class="link">Giugno 2017</span>
                        <span class="prev link">
                            <span class="ifix chevron left icon"></span>
                        </span>
                        <span class="next link">
                            <span class="ifix chevron right icon"></span>
                        </span>
                    </th>
                </tr>
                <tr>
                    <th id="dom" headers="month" scope="col">Dom</th>
                    <th id="lun" headers="month" scope="col">Lun</th>
                    <th id="mar" headers="month" scope="col">Mar</th>
                    <th id="mer" headers="month" scope="col">Mer</th>
                    <th id="gio" headers="month" scope="col">Gio</th>
                    <th id="ven" headers="month" scope="col">Ven</th>
                    <th id="sab" headers="month" scope="col">Sab</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td headers="dom" class="link adjacent disabled">28</td>
                    <td headers="lun" class="link adjacent disabled">29</td>
                    <td headers="mar" class="link adjacent disabled">30</td>
                    <td headers="mer" class="link adjacent disabled">31</td>
                    <td headers="gio" class="link">1</td>
                    <td headers="ven" class="link">2</td>
                    <td headers="sab" class="link">3</td>
                </tr>
                <tr>
                    <td headers="dom" class="link">4</td>
                    <td headers="lun" class="link today focus">5</td>
                    <td headers="mar" class="link">6</td>
                    <td headers="mer" class="link">7</td>
                    <td headers="gio" class="link">8</td>
                    <td headers="ven" class="link">9</td>
                    <td headers="sab" class="link">10</td>
                </tr>
                <tr>
                    <td headers="dom" class="link">11</td>
                    <td headers="lun" class="link">12</td>
                    <td headers="mar" class="link">13</td>
                    <td headers="mer" class="link">14</td>
                    <td headers="gio" class="link">15</td>
                    <td headers="ven" class="link">16</td>
                    <td headers="sab" class="link">17</td>
                </tr>
                <tr>
                    <td headers="dom" class="link">18</td>
                    <td headers="lun" class="link">19</td>
                    <td headers="mar" class="link">20</td>
                    <td headers="mer" class="link">21</td>
                    <td headers="gio" class="link">22</td>
                    <td headers="ven" class="link">23</td>
                    <td headers="sab" class="link">24</td>
                </tr>
                <tr>
                    <td headers="dom" class="link">25</td>
                    <td headers="lun" class="link">26</td>
                    <td headers="mar" class="link">27</td>
                    <td headers="mer" class="link">28</td>
                    <td headers="gio" class="link">29</td>
                    <td headers="ven" class="link">30</td>
                    <td headers="sab" class="link adjacent disabled">1</td>
                </tr>
                <tr>
                    <td headers="dom" class="link adjacent disabled">2</td>
                    <td headers="lun" class="link adjacent disabled">3</td>
                    <td headers="mar" class="link adjacent disabled">4</td>
                    <td headers="mer" class="link adjacent disabled">5</td>
                    <td headers="gio" class="link adjacent disabled">6</td>
                    <td headers="ven" class="link adjacent disabled">7</td>
                    <td headers="sab" class="link adjacent disabled">8</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>
</code>```

Link to related Plunker.

Now AChecker says that there are "No known problems" in the page.
Anyway can you confirm that my modification is the right way to use id and headers in case of more than one th element in a table?

答:
What you are doing in the second table is technically correct. When you have colspans and rowspans, or when you have multiple s, then this approach makes it accessible. Some resources (which you may have already read):

H43: Using id and headers attributes to associate data cells with header cells in data tables from W3C's Techniques for WCAG 2.0.

Creating Accessible Tables from WebAIM (linked to the relevant section on the page).

This approach is verbose, though. You may want to use
 instead for your month/year so it is not announced with every cell (for most screen readers, maybe all).

This means your users still get context, but do not have to listen to it on every cell. At any time they can pop back out to confirm what the table caption is.

Body:
I'm creating an application that should be WCAG 2.0 compliant.
I'm checking my pages using AChecker and I'm experiencing some problems with table. I get the following 2 issues:

Data table with both row and column headers does not use scope to identify cells

Data table with more than one row/column of headers does not use id and headers attributes to identify cells

Here is the source code of my table:

<!DOCTYPE html>

                        Giugno 2017

                    Dom
                    Lun
                    Mar
                    Mer
                    Gio
                    Ven
                    Sab

                    28
                    29
                    30
                    31
                    1
                    2
                    3

                    4
                    5
                    6
                    7
                    8
                    9
                    10

                    11
                    12
                    13
                    14
                    15
                    16
                    17

                    18
                    19
                    20
                    21
                    22
                    23
                    24

                    25
                    26
                    27
                    28
                    29
                    30
                    1

                    2
                    3
                    4
                    5
                    6
                    7
                    8

Link to related Plunker.

According to this W3C documentation page do you know the right way to use headers in my case?

I tried to do it by myself and I edited my code. Here is the result:

<!DOCTYPE html>

                        Giugno 2017

                    Dom
                    Lun
                    Mar
                    Mer
                    Gio
                    Ven
                    Sab

                    28
                    29
                    30
                    31
                    1
                    2
                    3

                    4
                    5
                    6
                    7
                    8
                    9
                    10

                    11
                    12
                    13
                    14
                    15
                    16
                    17

                    18
                    19
                    20
                    21
                    22
                    23
                    24

                    25
                    26
                    27
                    28
                    29
                    30
                    1

                    2
                    3
                    4
                    5
                    6
                    7
                    8

Link to related Plunker.

Now AChecker says that there are "No known problems" in the page.
Anyway can you confirm that my modification is the right way to use id and headers in case of more than one th element in a table?

Body:
What you are doing in the second table is technically correct. When you have colspans and rowspans, or when you have multiple <th>s, then this approach makes it accessible. Some resources (which you may have already read):

H43: Using id and headers attributes to associate data cells with header cells in data tables from W3C's Techniques for WCAG 2.0.

Creating Accessible Tables from WebAIM (linked to the relevant section on the page).

This approach is verbose, though. You may want to use <caption> instead for your month/year so it is not announced with every cell (for most screen readers, maybe all).

This means your users still get context, but do not have to listen to it on every cell. At any time they can pop back out to confirm what the table caption is.


问:
anyone can find the syntax misstake in my php?
I'm trying to write out the errors, which are created in my .php , as an alert in my .html but i cant get it to run.

```<code><?php if(isset($_SESSION["error"])){
     echo "<script> alert(".$_SESSION["error"].");";
     echo "</script>";}
    ?>
</code>```

i thnk its just a misstake in the syntax, becuase when i run it in an online php testing program it works

php is enabled in .html and its working 10 lines later :D

in this example its working:

```<code><?php if(!isset($_SESSION["login_user"])){
                    echo "<fieldset> <form id='login' method='post' action='../php/login.php'>";
                    echo "<input type='text' name='email' placeholder='E-Mail Adresse' required>";
                    echo "<input type='password' name='passwort' placeholder='Passwort' required><br/>";
                    echo "<a href='registrierung.html'>Registrieren</a>";
                    echo "          <input name='submit' id='anmelden' type='submit' value='Login'>";
                    echo "      </form>";
                    echo "</fieldset>";
                    }
                    else{
                    //Hier Html für eingeloggt Kasten Bitte
                    }
                ?>
</code>```

答:
Never done such an error handling.
But if you want to alert a String in JavaScript ist has to be in quotes.
So I think it has to be:
        echo " alert(' ".$_SESSION["error"]." '); ";</p>

Body:
I'm trying to write out the errors, which are created in my .php , as an alert in my .html but i cant get it to run.

<?php if(isset($_SESSION["error"])){
     echo "";}
    ?>

i thnk its just a misstake in the syntax, becuase when i run it in an online php testing program it works

php is enabled in .html and its working 10 lines later :D

in this example its working:

<?php if(!isset($_SESSION["login_user"])){
                    echo "<fieldset> <form id='login' method='post' action='../php/login.php'>";
                    echo "<input type='text' name='email' placeholder='E-Mail Adresse' required>";
                    echo "<input type='password' name='passwort' placeholder='Passwort' required>
";
                    echo "Registrieren";
                    echo "          <input name='submit' id='anmelden' type='submit' value='Login'>";
                    echo "      </form>";
                    echo "</fieldset>";
                    }
                    else{
                    //Hier Html für eingeloggt Kasten Bitte
                    }
                ?>


问:
Weird memory increase on application pool recycle
I'd like to describe strange issue I've noticed while analyzing my asp.net application in production and ask for some advice or opinion on the following matter.

Application usually runs with some 80-90 MB of memory footprint. This seems stable since no memory leaks have been detected so far - no slight increase in memory usage over time. Yet, problem occurs when application pool recycles (I'm using shared hosting and judging by logs it occurs either when app is idle for 20 mins or every ~30 hours - something like that). The issue is that used memory almost doubles for some period on recycle - it goes to some 160-170 MBs without any explanation. This is confusing, since it is common claim that recycling should purge the memory and all other resources - at least I get it that way. System holds this amount of memory for some 7-8 hours and then memory usage drops to it's usual level of 90-100 MB, again, with no apparent reason (at least not know to me). All the time, application seems to work well - no significant delays or troubles with site availability - to the users everything seems OK, no complaints so far. When looking at the memory consumption over time graph - it looks almost like a step function.

The important thing is that I haven't been able to reproduce this sort of behavior in my testing environment. Occasionally, I've been getting notes from provider administrators that my app is using more resources than allowed and this really bugs me.

So, what I would like to know - is there any possible scenario where application pool recycling does not release all memory resources ? Is there any advice or guideline what I should focus on ? I'm not an expert in this area, but I've been reading about things like overlapping recycling, serialization problems on recycle and couple more issues ... Any ideas ? Similar experience ?

Thanks

答:
This post provides a pretty good overview of what happens when your site's app pool is recycled: http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx

My speculation is that your memory usage is increasing due to the JIT-compilation that follows every recycle of the app pool. My guess is that your shared host has different configuration and environmental settings than your development server.

IMHO, if you're using ~100 megs of memory on a shared host, you are asking for trouble if it's a host like DiscountASP.NET or GoDaddy. If you care at all about that website, go get a VPS or some more configurable hosting where you can pay a premium for a higher memory limit.