问:
What the typical viewport size on a 1024x768 screen?
I am designing a web application, and I wish to know the largest size (x and y) that I can design for.

As of January 2008, about half of users are using 1024x278 screens, and probably less than 10% are using smaller screens. (Phone and palmtop users are an exception here.) So we are designing for minimum screen size of 1024x768.

However, that's the screen size, and when we are laying out our content we need to know the viewport size. There is evidence that most users have the browser maximized, but one still must subtract out space for OS decorations and browser chrome. People customize their chrome, so there is no single "right" answer; I am going for a reasonable bound that will accommodate the majority of users.

I see plenty of designers who say that they use a width of 960 pixels because it has many factors and can be divided up evenly -- but before deciding on this I want to know the maximum size that I can get away with, then I might choose to use somewhat less. I have seen max widths of 960, 974 or even 990 quoted... my own experiments seem to show a width of 1000 works OK.

Heights are even more difficult to come by: I find I can fit a vertical viewport height of 595 pixels works on the browsers that I've tried, with typical default OS and chrome settings. But I haven't tried very many, and I would rather see a more authoritative source. Surely someone else has done this research and done it better than me.

So my real question is this: What is the largest viewport size I can design for and expect it to fit without scrollbars for 80-90% of all users?

答:
All the answers you've found already are probably right.

For the casual user (Stereotypical: Win XP or Vista, IE6-7, no custom skins) a width close to 1000px would probably fit. If people have modified their browsers, not running them full-screen or have custom skins on their operating systems, this number might change.

If i were to design for a 1024px-width-resolution, I'd probably choose a width close to 980px. It's all up to you, and there's no "one and only answer". Around 960-1000px somewhere, depending on a whole lot of things.

When it comes to the height of the page, don't think too much about it. Put the most important information (navigation, logo, important content) at the top of the page, and don't be afraid of letting the user scroll to find the rest. People are used to, and know they have to, scroll. It's a natural limitation nobody expects you to do anything with.

For that most important information, a viewport with a height of around 550px or more could probably be expected.

So, ~980px * ~550px is probably a more or less standard viewport to use as a starting point :-)

OwnerDisplayName: mcherm

OwnerDisplayName: Arve Systad


来源: stackexchange

问:
IIS error 0x80005006 (2147463162)
I was told that we had an old virtual machine that had the same problem and it was fixed by downloading and installing an "iis develepor toolset".  Any idea what that "IIS developer toolset" might actually be?

IIS 7.0

This is on a windows 7 box trying to remote to a webserver and setup IIS.

```<code>  DirectoryEntry rvd = forms_website.Children.Cast<DirectoryEntry>().First();
rvd.Properties["AFName"].Value = "Default Application";
</code>```

答: 0x80005006 (2174763162) is a generic IIS property error that is thrown for a LOT of reasons. The installation of a toolkit may easily have corrected a permission setting on an extension, updated a property in the metabase, etc. This would not be a directed fix so much as a lucky one as it is possible that the error being thrown was completely unrelated to the tool set, but the update corrected an ancillary issue.</p>

ContentLicense: CC BY-SA 2.5

Title: IIS error 0x80005006 (2147463162)

Body:
I was told that we had an old virtual machine that had the same problem and it was fixed by downloading and installing an "iis develepor toolset".  Any idea what that "IIS developer toolset" might actually be?

IIS 7.0

This is on a windows 7 box trying to remote to a webserver and setup IIS.

  DirectoryEntry rvd = forms_website.Children.Cast<DirectoryEntry>().First();
rvd.Properties["AFName"].Value = "Default Application";


问:
jquery swap ul childs between two ul's
I have the following html with two lists, and I want to press a button and swap the ul's, li´s elements between the two

```<code><ul class="list-group" id="lines">
<li class="list-group-item> 1 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
<li class="list-group-item> 3 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>
</code>```

I have tried to accomplish this with the following jquery code

```<code>$("#swaplists").click(function () {

 var $temp1 = $("#lines").children.clone;
 var $temp2 = $("#columns").children.clone;
 clearLinesAndColumns();
 $temp2.appendTo("#lines");
 $temp1.appendTo("#columns");

});
</code>```

the expected result would be

```<code><ul class="list-group" id="lines">
<li class="list-group-item> 3 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
<li class="list-group-item> 1 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>
</code>```

But I get the error

Uncaught TypeError: Cannot read property 'appendTo' of undefined

How can I achieve this functionality with jquery and why is children.clone undefined?

答:
Instead of cloning and appending, you can simply get the html() and insert in other:

$("#swaplists").click(function() {
  var linesHtml = $("#lines").html();
  var columnsHtml = $("#columns").html();
  $("#lines").html(columnsHtml);
  $("#columns").html(linesHtml);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group" id="lines">
  <li class="list-group-item"> 1 <i class=" fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
  <li class="list-group-item"> 3 <i class=" fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<button id="swaplists">Swap</button></code>```

ContentLicense: CC BY-SA 3.0

Title: jquery swap ul childs between two ul's

Body:
I have the following html with two lists, and I want to press a button and swap the ul's, li´s elements between the two

 1

 2

 3

 4

I have tried to accomplish this with the following jquery code

$("#swaplists").click(function () {

 var $temp1 = $("#lines").children.clone;
 var $temp2 = $("#columns").children.clone;
 clearLinesAndColumns();
 $temp2.appendTo("#lines");
 $temp1.appendTo("#columns");

});

the expected result would be

 3

 4

 1

 2

But I get the error

Uncaught TypeError: Cannot read property 'appendTo' of undefined

How can I achieve this functionality with jquery and why is children.clone undefined?

Body:
Instead of cloning and appending, you can simply get the html() and insert in other:

$("#swaplists").click(function() {
  var linesHtml = $("#lines").html();
  var columnsHtml = $("#columns").html();
  $("#lines").html(columnsHtml);
  $("#columns").html(linesHtml);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group" id="lines">
  <li class="list-group-item"> 1 <i class=" fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
  <li class="list-group-item"> 3 <i class=" fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<button id="swaplists">Swap</button>


问:
QuillJS doesn't work with textarea
I am trying to use QuillJS on a specific form field in my Django 1.10 template as follows:

```<code><link href="https://cdn.quilljs.com/1.1.3/quill.snow.css" rel="stylesheet">

<script src="https://cdn.quilljs.com/1.1.3/quill.js"></script>
<!-- Initialize Quill editor -->
<script>
  var quill = new Quill('#id_text', {
    theme: 'snow'
  });
</script>
</code>```

The problem is that Django renders the form field I want to use Quill on as a textarea instead of a div, and Quill doesn't seem to work on it: any effects applied to text don't register either visually or in the resulting output, and when I try to edit an existing record the initial text doesn't show up in the editor, even though it is there in the source HTML between the textarea tags.

Is it a known issue that Quill doesn't work with textarea or is there something else that could be wrong?

答:
Try below code to get form data.</p>

```<code>var quill = new Quill('#editor-container', {
  modules: {
    toolbar: [
      ['bold', 'italic'],
      ['link', 'blockquote', 'code-block', 'image'],
      [{ list: 'ordered' }, { list: 'bullet' }]
    ]
  },
  placeholder: 'Compose an epic...',
  theme: 'snow'
});
var form = document.querySelector('form');
form.onsubmit = function() {
  // Populate hidden form on submit
  var about = document.querySelector('input[name=about]');
  about.value = JSON.stringify(quill.getContents());

  console.log("Submitted", $(form).serialize(), $(form).serializeArray());

alert('Open the console to see the submit data!')
  return false;
};
</code>```

Title: QuillJS doesn't work with textarea

Body:
I am trying to use QuillJS on a specific form field in my Django 1.10 template as follows:

<link href="https://cdn.quilljs.com/1.1.3/quill.snow.css" rel="stylesheet">

The problem is that Django renders the form field I want to use Quill on as a textarea instead of a div, and Quill doesn't seem to work on it: any effects applied to text don't register either visually or in the resulting output, and when I try to edit an existing record the initial text doesn't show up in the editor, even though it is there in the source HTML between the textarea tags.

Is it a known issue that Quill doesn't work with textarea or is there something else that could be wrong?

Body:
Try below code to get form data.

var quill = new Quill('#editor-container', {
  modules: {
    toolbar: [
      ['bold', 'italic'],
      ['link', 'blockquote', 'code-block', 'image'],
      [{ list: 'ordered' }, { list: 'bullet' }]
    ]
  },
  placeholder: 'Compose an epic...',
  theme: 'snow'
});
var form = document.querySelector('form');
form.onsubmit = function() {
  // Populate hidden form on submit
  var about = document.querySelector('input[name=about]');
  about.value = JSON.stringify(quill.getContents());

  console.log("Submitted", $(form).serialize(), $(form).serializeArray());

alert('Open the console to see the submit data!')
  return false;
};


问:
ionic2 frame work sending empty parameters in post(400 Badrequest)
login.ts

```<code>onlogin() {
    let login_email = "vvvv@gmail.com";
    let login_password = "123456"
    this.body = {
        login_email: login_email,
        login_password: login_password
    };

    this.auth.login(this.body).subscribe(data => {
        this.result = data
        console.log(data);
    });
}
</code>```

authservice.ts

```<code>login(param) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.apiUrl + '/login', JSON.stringify(param), options)
    .map((res: Response) => {
        if (res) {
            return { status: res.status, json: res.json() }
        }
    });
}
</code>```

Method is working fine in postman but, while sending the same request from ionic2 is generating an error.Get methods  were working fine but there is some issue in post.The request is sending empty parameters in post and generating error 400 Bad request.

答:
Login.ts

onlogin()
      {

```<code>const email = 'xxxxxx@gmail.com';
const password = '123456';
let body = new FormData();
body.append("login_email",email);
body.append("login_password",password);

        console.log(body);
        this.auth.login(body).subscribe(data => {this.result = data;
       this.navCtrl.push(HomePage,{result:this.result});
    });

}
</code>```

authservice.ts

```<code>   login(param)
  {
   const headers = new Headers({'ContentType':'application/formdata'});
   return this.http.post('/api',param,headers)
                .map(this.extractDataLogin)
                .catch(error => this.handleError(error));
   }
</code>```

Using formdata to send data resolved my problem

```<code>let body = new FormData();
body.append("login_email",email);
body.append("login_password",password);
</code>```

Body:
login.ts

onlogin() {
    let login_email = "vvvv@gmail.com";
    let login_password = "123456"
    this.body = {
        login_email: login_email,
        login_password: login_password
    };

    this.auth.login(this.body).subscribe(data => {
        this.result = data
        console.log(data);
    });
}

authservice.ts

login(param) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.apiUrl + '/login', JSON.stringify(param), options)
    .map((res: Response) => {
        if (res) {
            return { status: res.status, json: res.json() }
        }
    });
}

Method is working fine in postman but, while sending the same request from ionic2 is generating an error.Get methods  were working fine but there is some issue in post.The request is sending empty parameters in post and generating error 400 Bad request.

Body:
Login.ts

onlogin()
      {

const email = 'xxxxxx@gmail.com';
const password = '123456';
let body = new FormData();
body.append("login_email",email);
body.append("login_password",password);

        console.log(body);
        this.auth.login(body).subscribe(data => {this.result = data;
       this.navCtrl.push(HomePage,{result:this.result});
    });

}

authservice.ts

   login(param)
  {
   const headers = new Headers({'ContentType':'application/formdata'});
   return this.http.post('/api',param,headers)
                .map(this.extractDataLogin)
                .catch(error => this.handleError(error));
   }

Using formdata to send data resolved my problem

let body = new FormData();
body.append("login_email",email);
body.append("login_password",password);


问:
Laravel: Auth::user()->role_id in app.blade.php display Trying to get property of non-object
In my users table I add role_id column where 1 is admin and 2 is user. So, when I want to his page in header in my app.blade.php file like this:

```<code><ul class="nav navbar-nav">
   @if(Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>
</code>```

error appear:
(3/3) ErrorException
The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)

index() method in AdminUsersController looks like this:

```<code><?php

namespace App\Http\Controllers;

use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;

class AdminUsersController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);

        if(Auth::user()->role_id !== 1) {
            return redirect('/home');
        }

        return view('admin.users.index', compact('users'));
    }
</code>```

When I use check() instead of user()->role_id == 1, It works but then all users can see except one that not login, but I want to see only admin.

I cannot find the answer in similar topics...

答:
You are likely getting this error because Auth::user() is NULL as no user is logged in when you visit that route.

Try adding the below to your controller to ensure that only logged in users can use the AdminUsers controller.

```<code>/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    // user must log in to use this controller
    $this->middleware('auth');
}
</code>```

Whenever a user tries to visit one of the routes managed by this controller, s/he will be asked to login first. Then your Auth::user()->role_id == 1 will not return this error.

Reference: Laravel - protecting routes

Body:
In my users table I add role_id column where 1 is admin and 2 is user. So, when I want to his page in header in my app.blade.php file like this:

   @if(Auth::user()->role_id == 1)

Users

   @endif

error appear:
(3/3) ErrorException
The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)

index() method in AdminUsersController looks like this:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;

class AdminUsersController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);

        if(Auth::user()->role_id !== 1) {
            return redirect('/home');
        }

        return view('admin.users.index', compact('users'));
    }

When I use check() instead of user()->role_id == 1, It works but then all users can see except one that not login, but I want to see only admin.

I cannot find the answer in similar topics...

Body:
You are likely getting this error because Auth::user() is NULL as no user is logged in when you visit that route.

Try adding the below to your controller to ensure that only logged in users can use the AdminUsers controller.

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    // user must log in to use this controller
    $this->middleware('auth');
}

Whenever a user tries to visit one of the routes managed by this controller, s/he will be asked to login first. Then your Auth::user()->role_id == 1 will not return this error.

Reference: Laravel - protecting routes


问:
How would I eliminate spacing, line breaks to have a space-delimited string for each string within my list python
Hi everyone I am pretty new to python and wanted some help. I have some sample data and wanted to know how would I get rid of spacing for each string within each list.

```<code>data = [
 ['In dolore     .'], ['Voluptatum.    '],
 ['Veniam hic non minima.         '],
 ['Dolores       Quis enim'],
 ['     sequi ducimus']
 ]
 print data
</code>```

The Output I desire:

```<code>data = [
 ['In dolore.'], ['Voluptatum.'],
 ['Veniam hic non minima.'],
 ['Dolores Quis enim'],
 ['sequi ducimus']
 ]
</code>```

Here are the two ways I thought would work but didn't

```<code>for i in data:
str = ''.join(data)
final_data = str.replace("  ","")
print final_data
</code>```

my final attempt was this:

```<code>final_data = ''.join(data)
final_data.replace("  ", "")
print final_data
</code>```

答:
```<code>import re
final_data = [[re.sub('\s+\.', '.', re.sub('\s+', ' ', s)).strip()] for l in data for s in l]
print final_data

[['In dolore.'], ['Voluptatum.'], ['Veniam hic non minima.'], ['Dolores Quis enim'], ['sequi ducimus']]
</code>```

This way leading and trailing whitespaces are removed, while internal spaces are not eliminated entirely.

The inner substitution replaces multiple whitespace characters with a single spaces, and the outer substitution eliminates whitespace characters before a period. The strip function eliminates leading and trailing whitespace.

Body:
Hi everyone I am pretty new to python and wanted some help. I have some sample data and wanted to know how would I get rid of spacing for each string within each list.

data = [
 ['In dolore     .'], ['Voluptatum.    '],
 ['Veniam hic non minima.         '],
 ['Dolores       Quis enim'],
 ['     sequi ducimus']
 ]
 print data

The Output I desire:

data = [
 ['In dolore.'], ['Voluptatum.'],
 ['Veniam hic non minima.'],
 ['Dolores Quis enim'],
 ['sequi ducimus']
 ]

Here are the two ways I thought would work but didn't

for i in data:
str = ''.join(data)
final_data = str.replace("  ","")
print final_data

my final attempt was this:

final_data = ''.join(data)
final_data.replace("  ", "")
print final_data

Body:
import re
final_data = [[re.sub('\s+\.', '.', re.sub('\s+', ' ', s)).strip()] for l in data for s in l]
print final_data

[['In dolore.'], ['Voluptatum.'], ['Veniam hic non minima.'], ['Dolores Quis enim'], ['sequi ducimus']]

This way leading and trailing whitespaces are removed, while internal spaces are not eliminated entirely.

The inner substitution replaces multiple whitespace characters with a single spaces, and the outer substitution eliminates whitespace characters before a period. The strip function eliminates leading and trailing whitespace.


问:
VB.NET Generate unique 5 numbers between 1 and 10
Hello I 5 unique numbers betwen 0 and 10, I'm doing as following :

```<code>Dim RandomClass As New Random()
Dim RandomNumber As Integer
For counter As Integer = 0 To 5
    RandomNumber = RandomClass.Next(0, 10)
    MsgBox(RandomNumber )
Next
</code>```

Sometimes it works, I get those numbers : "1,7,4,9,3"
but sometimes I get a duplicate numbers like : "5,2,3,2,7"

How can I be sure to have unique numbers each time?

Thank you.

答:
try following:</p>

```<code> Sub Main()

    Dim a As String() = New String(2) {}
    Dim b As String
    Dim c As Integer = 0
    Dim d As String = " "
    Do
        Console.Clear()
        Console.Write("Enter your name:")
        a(c) = Console.ReadLine()
        c += 1

    Loop Until c = 3
    For Each d In a
        Console.Write(" " & d)
    Next
    Console.ReadLine()
</code>```

Body:
Hello I 5 unique numbers betwen 0 and 10, I'm doing as following :

Dim RandomClass As New Random()
Dim RandomNumber As Integer
For counter As Integer = 0 To 5
    RandomNumber = RandomClass.Next(0, 10)
    MsgBox(RandomNumber )
Next

Sometimes it works, I get those numbers : "1,7,4,9,3"
but sometimes I get a duplicate numbers like : "5,2,3,2,7"

How can I be sure to have unique numbers each time?

Thank you.

Body:
try following:

 Sub Main()

    Dim a As String() = New String(2) {}
    Dim b As String
    Dim c As Integer = 0
    Dim d As String = " "
    Do
        Console.Clear()
        Console.Write("Enter your name:")
        a(c) = Console.ReadLine()
        c += 1

    Loop Until c = 3
    For Each d In a
        Console.Write(" " & d)
    Next
    Console.ReadLine()


问:
How to display a day from the Date
Using SQL Server 2005

Table1

```<code>Date

19-12-2009
20-12-2010
.....
</code>```

Date Column datatype is DATETIME.

Expected Output

```<code>Monday
Tuesday
</code>```

How to make a query for getting the day...

答:
You can use the DATENAME function.

```<code>SELECT DATENAME(WEEKDAY,[Date])
FROM Table1
</code>```

Title: How to display a day from the Date

Body:
Using SQL Server 2005

Table1

Date

19-12-2009
20-12-2010
.....

Date Column datatype is DATETIME.

Expected Output

Monday
Tuesday

How to make a query for getting the day...

Body:
You can use the DATENAME function.

SELECT DATENAME(WEEKDAY,[Date])
FROM Table1


问:
Passing arguments from a variable with white space
I'd like to use a number of arguments defined in a variable when executing a command. Let me illustrate the case with a simple example:

Say I want to copy a file from one destination to another and that I will supply the arguments for cp through a variable. It works fine when the arguments does not contain any spaces:

```<code>#!/bin/sh
ARGS="file1 file2"

cp $ARGS
</code>```

strace shows the following expected interpretation:

```<code>execve("/bin/cp", ["cp", "file1", "file2"]
</code>```

However when I use arguments with spaces I cannot get it to work. I've tried putting each argument in escaped quotes and many other things, but it is interpreted as individual arguments:

```<code>#!/bin/sh
ARGS="\"file1\" \"file2\""

cp $ARGS
</code>```

the result is not two arguments, but four:

```<code>execve("/bin/cp", ["cp", "\"file", "1\"", "\"file", "2\""]
</code>```

To complicate things even further my final goal is to use variable substitutions within the supplied ARGS variable, but how do I get it to work? Consider the following:

```<code>FILENAME1="Picture 1.jpg"
FILENAME2="Picture 2.jpg"

ARGS="$FILENAME1 $FILENAME1"

cp $ARGS
</code>```

It results in four arguments:

```<code>execve("/bin/cp", ["cp", "Picture", "1.jpg", "Picture", "1.jpg"]
</code>```

答:
You cannot reliably use a single parameter to store a list of values; there is no way to distinguish between whitespace that is part of a value, and whitespace that separates values. Use an array instead.

```<code>#!/bin/bash

filename1="Picture 1.jpg"
filename2="Picture 2.jpg"

args=( "$filename1" "$filename2" )

cp "${args[@]}"
</code>```

Body:
I'd like to use a number of arguments defined in a variable when executing a command. Let me illustrate the case with a simple example:

Say I want to copy a file from one destination to another and that I will supply the arguments for cp through a variable. It works fine when the arguments does not contain any spaces:

#!/bin/sh
ARGS="file1 file2"

cp $ARGS

strace shows the following expected interpretation:

execve("/bin/cp", ["cp", "file1", "file2"]

However when I use arguments with spaces I cannot get it to work. I've tried putting each argument in escaped quotes and many other things, but it is interpreted as individual arguments:

#!/bin/sh
ARGS="\"file1\" \"file2\""

cp $ARGS

the result is not two arguments, but four:

execve("/bin/cp", ["cp", "\"file", "1\"", "\"file", "2\""]

To complicate things even further my final goal is to use variable substitutions within the supplied ARGS variable, but how do I get it to work? Consider the following:

FILENAME1="Picture 1.jpg"
FILENAME2="Picture 2.jpg"

ARGS="$FILENAME1 $FILENAME1"

cp $ARGS

It results in four arguments:

execve("/bin/cp", ["cp", "Picture", "1.jpg", "Picture", "1.jpg"]

Body:
You cannot reliably use a single parameter to store a list of values; there is no way to distinguish between whitespace that is part of a value, and whitespace that separates values. Use an array instead.

#!/bin/bash

filename1="Picture 1.jpg"
filename2="Picture 2.jpg"

args=( "$filename1" "$filename2" )

cp "${args[@]}"


问:
Java: Find the longest substring without any number and at least one upper case character
Came across a programming exercise and was stuck. The problem is:

You need to define a valid password for an email but the only
  restrictions are:

The password must contain one uppercase character

The password should not have numeric digit

Now, given a String, find the length of the longest substring which
  is a valid password.   For e.g Input Str = "a0Ba" , the output should
  be 2 as "Ba" is the valid substring.

I used the concept of longest substring without repeating characters which I already did before but was unable to modify it to find the solution to above problem. My code for longest substring without repeating characters is:

```<code>public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    Set<Character> set = new HashSet<>();
    int ans = 0, i = 0, j = 0;
    while (i < n && j < n) {
        // try to extend the range [i, j]
        if (!set.contains(s.charAt(j))){
            set.add(s.charAt(j++));
            ans = Math.max(ans, j - i);
        }
        else {
            set.remove(s.charAt(i++));
        }
    }
    return ans;
}
</code>```

答: This is a dynamic programming problem. You can solve this yourself using a matrix. It is easy enough. Just give it a try. Take the characters of the password as the rows and columns of the matrix. Add the diagonals if the current character appended to the last character forms a valid password. Start with the smallest valid password as the initial condition.</p>

Body:
Came across a programming exercise and was stuck. The problem is:

You need to define a valid password for an email but the only
  restrictions are:

The password must contain one uppercase character

The password should not have numeric digit

Now, given a String, find the length of the longest substring which
  is a valid password.   For e.g Input Str = "a0Ba" , the output should
  be 2 as "Ba" is the valid substring.

I used the concept of longest substring without repeating characters which I already did before but was unable to modify it to find the solution to above problem. My code for longest substring without repeating characters is:

public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    Set<Character> set = new HashSet<>();
    int ans = 0, i = 0, j = 0;
    while (i < n && j < n) {
        // try to extend the range [i, j]
        if (!set.contains(s.charAt(j))){
            set.add(s.charAt(j++));
            ans = Math.max(ans, j - i);
        }
        else {
            set.remove(s.charAt(i++));
        }
    }
    return ans;
}


问:
How to use correctly OperationQueue?
This question is relative to this thread: how-to-set-the-height-of-a-cell-depending-on-a-uilabel-with-a-typewriter-effect

In my tableViewController, my cell contains UILabel with a typewriter effect managed with setTextWithTypeAnimation;

```<code>func configureCell(tableView: UITableView, cell: ParagraphTableViewCell, atIndexPath indexPath: IndexPath) {

    let paragraph = paragraphArray[indexPath.row] as! Paragraph
    cell.paragraph = paragraph

        self.queue = OperationQueue()

        let operation1 = BlockOperation(block: {

            cell.dialogueLabel.setTextWithTypeAnimation(typedText: paragraph.dialogueLabel.text!, queue:self.queue, callBackAfterCharacterInsertion: {

                self.tableView.beginUpdates()
                self.tableView.endUpdates()
            })

        })

    operation1.completionBlock = {

    cell.buttonsStackViewHeightConstraint.constant = CGFloat(HEIGHT_CONSTRAINT)

    UIView.animate(withDuration: 0.3, animations: {
        cell.contentView.layoutIfNeeded()
    }, completion: nil)

    }

    queue.addOperation(operation1)

   }
</code>```

My typewriter is inside a UILabel extension :

```<code>extension UILabel {

func setTextWithTypeAnimation(typedText: String, queue: OperationQueue, characterInterval: TimeInterval = 0.05, callBackAfterCharacterInsertion:(()->())?) {

    text = ""

    for (_, character) in typedText.characters.enumerated() {

        if queue.isSuspended {

            OperationQueue.main.isSuspended = true
            OperationQueue.main.cancelAllOperations()
            break;
        }

        OperationQueue.main.addOperation {

            self.text = self.text! + String(character)
            callBackAfterCharacterInsertion?()

        }

        Thread.sleep(forTimeInterval: characterInterval)
    }
}
}
</code>```

First I used DispatchQueue to manage the animation inside a cell (see how-to-set-the-height-of-a-cell-depending-on-a-uilabel-with-a-typewriter-effect), but I needed to stop the thread when user closes the view controller. That's why I'm using OperationQueue (DispatchQueue cannot be stopped)

```<code>@IBAction func closeViewController(sender: AnyObject) {

    dismiss(animated: true, completion: nil)

        if self.queue != nil {

            self.queue.isSuspended = true
            self.queue.cancelAllOperations()
            self.queue = nil
    }
}
</code>```

The issue is when completionBlock is called, the app crashes when I try to update a layout constraint.

```<code>This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread.
</code>```

How can avoid this crash?

答:
You must call UI stuff on the mainQueue.

Example:

```<code>operation1.completionBlock = {
    DispatchQueue.main.async {
        cell.buttonsStackViewHeightConstraint.constant = CGFloat(HEIGHT_CONSTRAINT)

        UIView.animate(withDuration: 0.3, animations: {
            cell.contentView.layoutIfNeeded()
        }, completion: nil)
    }
}
</code>```

Title: How to use correctly OperationQueue?

Body:
This question is relative to this thread: how-to-set-the-height-of-a-cell-depending-on-a-uilabel-with-a-typewriter-effect

In my tableViewController, my cell contains UILabel with a typewriter effect managed with setTextWithTypeAnimation;

func configureCell(tableView: UITableView, cell: ParagraphTableViewCell, atIndexPath indexPath: IndexPath) {

    let paragraph = paragraphArray[indexPath.row] as! Paragraph
    cell.paragraph = paragraph

        self.queue = OperationQueue()

        let operation1 = BlockOperation(block: {

            cell.dialogueLabel.setTextWithTypeAnimation(typedText: paragraph.dialogueLabel.text!, queue:self.queue, callBackAfterCharacterInsertion: {

                self.tableView.beginUpdates()
                self.tableView.endUpdates()
            })

        })

    operation1.completionBlock = {

    cell.buttonsStackViewHeightConstraint.constant = CGFloat(HEIGHT_CONSTRAINT)

    UIView.animate(withDuration: 0.3, animations: {
        cell.contentView.layoutIfNeeded()
    }, completion: nil)

    }

    queue.addOperation(operation1)

   }

My typewriter is inside a UILabel extension :

extension UILabel {

func setTextWithTypeAnimation(typedText: String, queue: OperationQueue, characterInterval: TimeInterval = 0.05, callBackAfterCharacterInsertion:(()->())?) {

    text = ""

    for (_, character) in typedText.characters.enumerated() {

        if queue.isSuspended {

            OperationQueue.main.isSuspended = true
            OperationQueue.main.cancelAllOperations()
            break;
        }

        OperationQueue.main.addOperation {

            self.text = self.text! + String(character)
            callBackAfterCharacterInsertion?()

        }

        Thread.sleep(forTimeInterval: characterInterval)
    }
}
}

First I used DispatchQueue to manage the animation inside a cell (see how-to-set-the-height-of-a-cell-depending-on-a-uilabel-with-a-typewriter-effect), but I needed to stop the thread when user closes the view controller. That's why I'm using OperationQueue (DispatchQueue cannot be stopped)

@IBAction func closeViewController(sender: AnyObject) {

    dismiss(animated: true, completion: nil)

        if self.queue != nil {

            self.queue.isSuspended = true
            self.queue.cancelAllOperations()
            self.queue = nil
    }
}

The issue is when completionBlock is called, the app crashes when I try to update a layout constraint.

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread.

How can avoid this crash?

Body:
You must call UI stuff on the mainQueue.

Example:

operation1.completionBlock = {
    DispatchQueue.main.async {
        cell.buttonsStackViewHeightConstraint.constant = CGFloat(HEIGHT_CONSTRAINT)

        UIView.animate(withDuration: 0.3, animations: {
            cell.contentView.layoutIfNeeded()
        }, completion: nil)
    }
}


问:
Getting an error while calling GET /system/ping
I am getting an error while calling GET /system/ping

```<code>{
  "error": {
    "statusCode": 500,
    "name": "Error",
    "message": "error trying login and get user Context. Error: error trying to enroll user. Error: Enrollment failed with errors [[{\"code\":400,\"message\":\"Authorization failure\"}]]",
  }
}
</code>```

I have made the participant

```<code>Blockchain Participant
{
  '$class': 'org.optum.blockchainv5.Participant',
  ParticipantId: 'ParticipantId:2',
  Name: 'Vipul Bajaj'
}
</code>```

Then issued an identity to the participant

```<code>System Identity
{
  userID: 'ParticipantId:2',
  userSecret: 'dPJbJBsaOLaf'
}
</code>```

And then added that identity to default wallet

```<code>Wallet Identity
{
  enrollmentID: 'ParticipantId:2',
  enrollmentSecret: 'dPJbJBsaOLaf',
  id: 3
}
</code>```

And then set this wallet identity default by calling the POST /wallets/1/identities/3/setDefault

Got response code 204

And after calling GET system/ping gave me error.

答: just following up - if you're still getting this error, could you attach a trace log setting export DEBUG=composer:* ` then re-running the rest server - the log file is in a 'logs' directory (from where you start the composer-rest-server). Then we can see what's going on with the POST.</p>

Body:
I am getting an error while calling GET /system/ping

{
  "error": {
    "statusCode": 500,
    "name": "Error",
    "message": "error trying login and get user Context. Error: error trying to enroll user. Error: Enrollment failed with errors [[{\"code\":400,\"message\":\"Authorization failure\"}]]",
  }
}

I have made the participant

Blockchain Participant
{
  '$class': 'org.optum.blockchainv5.Participant',
  ParticipantId: 'ParticipantId:2',
  Name: 'Vipul Bajaj'
}

Then issued an identity to the participant

System Identity
{
  userID: 'ParticipantId:2',
  userSecret: 'dPJbJBsaOLaf'
}

And then added that identity to default wallet

Wallet Identity
{
  enrollmentID: 'ParticipantId:2',
  enrollmentSecret: 'dPJbJBsaOLaf',
  id: 3
}

And then set this wallet identity default by calling the POST /wallets/1/identities/3/setDefault

Got response code 204

And after calling GET system/ping gave me error.


问:
Beautify the URL for API by .htaccess and PHP

Consider that I am requesting this url for a JSON api response.

```<code>// url that user will type in the browser address bar
example.com/api/user/0001
</code>```

I have 2 Options:

Option A

The redirection will be like this. But The address in the browser will be the same like before.

```<code>example.com?get1=api&get2=user&get3=0001
</code>```

The ?get1=xxxxxx and &get2=xxxxxx and is IMPORTANT. if there is more slashes (/) in the url it will add more GET request like this&get4=xxxxx &get5=xxxxx and so on.

Then I will get the exact information form the $_GET['reques'] method like this!

```<code>$var_request = $_GET['get1'];
$var_type    = $_GET['get2'];
$var_id      = $_GET['get3'];
</code>```

Option B

The redirection will be like this. But The address in the browser will be the same like before.

```<code>example.com?request=api/user/0001
</code>```

Then I will get the exact information by exploding the api/user/0001 like this

```<code>// Geting request by $_GET
$request = $_GET['request'];

// Exploding by the (/)
$api = explode("/", $request);

// Getting my desired information
$var_request = $api[0];
$var_type    = $api[1];
$var_id      = $api[2];
</code>```

Remember: The URL will be same as before. It should not look like ?get= this. The url should be still example.com/api/user/0001 in the browser url bar.

答:
I think Option B will be easier to do this. Possible solution is-

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+)$ ?request=$1 [L]
</code>```

It redirects - example.com/api/user/0001 to example.com?request=api/user/0001 Without changing the address in the url bar in you browser.

Body:
Consider that I am requesting this url for a JSON api response.

// url that user will type in the browser address bar
example.com/api/user/0001

I have 2 Options:

Option A

The redirection will be like this. But The address in the browser will be the same like before.

example.com?get1=api&get2=user&get3=0001

The ?get1=xxxxxx and &get2=xxxxxx and is IMPORTANT. if there is more slashes (/) in the url it will add more GET request like this&get4=xxxxx &get5=xxxxx and so on.

Then I will get the exact information form the $_GET['reques'] method like this!

$var_request = $_GET['get1'];
$var_type    = $_GET['get2'];
$var_id      = $_GET['get3'];

Option B

The redirection will be like this. But The address in the browser will be the same like before.

example.com?request=api/user/0001

Then I will get the exact information by exploding the api/user/0001 like this

// Geting request by $_GET
$request = $_GET['request'];

// Exploding by the (/)
$api = explode("/", $request);

// Getting my desired information
$var_request = $api[0];
$var_type    = $api[1];
$var_id      = $api[2];

Remember: The URL will be same as before. It should not look like ?get= this. The url should be still example.com/api/user/0001 in the browser url bar.

Body:
I think Option B will be easier to do this. Possible solution is-

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+)$ ?request=$1 [L]

It redirects - example.com/api/user/0001 to example.com?request=api/user/0001 Without changing the address in the url bar in you browser.


问:
I want to create an array of words from a txt document in C#.
The Split method returns an error.</p>

```<code>static void Main(string[] args)
    {
        string[] ebook = File.ReadLines("C:\\Users\\Michael\\Downloads\\Documents\\x.txt").ToArray();

        string[] words = ebook.Split(' ');

    }
</code>```

答:
You should use File.ReadAllText:

```<code>var ebook = File.ReadAllText("C:\\Users\\Michael\\Downloads\\Documents\\x.txt");
var words = ebook.Split(' ');
</code>```

You were using File.ReadLines that returns an IEnumerable<string> representing each line of your .txt, but if you want to split all words it is more "comfortable" to split from a single string, and File.ReadAllText returns a string with all the text in your file.

File.ReadAllText documentation

Body:
The Split method returns an error.

static void Main(string[] args)
    {
        string[] ebook = File.ReadLines("C:\\Users\\Michael\\Downloads\\Documents\\x.txt").ToArray();

        string[] words = ebook.Split(' ');

    }

Body:
You should use File.ReadAllText:

var ebook = File.ReadAllText("C:\\Users\\Michael\\Downloads\\Documents\\x.txt");
var words = ebook.Split(' ');

You were using File.ReadLines that returns an IEnumerable<string> representing each line of your .txt, but if you want to split all words it is more "comfortable" to split from a single string, and File.ReadAllText returns a string with all the text in your file.

File.ReadAllText documentation


问:
Best way of chaining reduce with Java 8
I have the following code that I'm trying to improve:

```<code>BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);
</code>```

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

答:
You can simply chain-add all properties inside map:

```<code>BigDecimal total = entity.getAssociate().stream()
            .map(a -> a.getPropertyA()
                    .add(a.getPropertyB())
                    .add(a.getPropertyC())
                    .add(a.getPropertyD()))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
</code>```

Mind that this changes the order by which numbers are added.

Title: Best way of chaining reduce with Java 8

Body:
I have the following code that I'm trying to improve:

BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

Body:
You can simply chain-add all properties inside map:

BigDecimal total = entity.getAssociate().stream()
            .map(a -> a.getPropertyA()
                    .add(a.getPropertyB())
                    .add(a.getPropertyC())
                    .add(a.getPropertyD()))
            .reduce(BigDecimal.ZERO, BigDecimal::add);

Mind that this changes the order by which numbers are added.


问:
Perl in Windows Vista 32bit?
I want to practice Perl in Windows Vista 32bit, how can I do it ?

Thanks.

答:
download Active perl and enjoy

http://www.activestate.com/activeperl

Title: Perl in Windows Vista 32bit?


问:
Disabling Chrome Autofill
I have been running into issues with the chrome autofill behavior on several forms.

The fields in the form all have very common and accurate names, such as "email", "name", or "password", and they also have autocomplete="off" set.

The autocomplete flag has successfully disabled the autocomplete behavior, where a dropdown of values appear as you start typing, but has not changed the values that Chrome auto-populates the fields as.

This behavior would be ok except that chrome is filling the inputs incorrectly, for example filling the phone input with an email address. Customers have complained about this, so it's verified to be happening in multiple cases, and not as some some sort of result to something that I've done locally on my machine.

The only current solution I can think of is to dynamically generate custom input names and then extract the values on the backend, but this seems like a pretty hacky way around this issue. Are there any tags or quirks that change the autofill behavior that could be used to fix this?

答:
None of the other solutions to these question worked for me.

The only think that worked is this one:

It removes "name" and "id" attributes from elements and assigns them
  back after 1ms. Put this in document get ready.

```<code>$(document).ready(function() {
    $('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {

                var input = this;
                var name = $(input).attr('name');
                var id = $(input).attr('id');

                $(input).removeAttr('name');
                $(input).removeAttr('id');

                setTimeout(function () {
                    $(input).attr('name', name);
                    $(input).attr('id', id);
                }, 1);
            });
});
</code>```

Title: Disabling Chrome Autofill

Body:
None of the other solutions to these question worked for me.

The only think that worked is this one:

It removes "name" and "id" attributes from elements and assigns them
  back after 1ms. Put this in document get ready.

$(document).ready(function() {
    $('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {

                var input = this;
                var name = $(input).attr('name');
                var id = $(input).attr('id');

                $(input).removeAttr('name');
                $(input).removeAttr('id');

                setTimeout(function () {
                    $(input).attr('name', name);
                    $(input).attr('id', id);
                }, 1);
            });
});


问:
rstudio like repl for spark-shell
I am looking for an interactive way to work with the spark-shell that would resemble rstudio.
My use is simple - I want to write code in the editor and execute line-by-line in the terminal of spark shell.
I have tried Jupyter notebooks and Zeppelin, but they seem to not yet be as ready as the Python backends.
Currently I cut and paste every time, but that becomes tiring after a short while.
Google searches haven't come up with anything I found useful.

答:
There two options:

Using Scala Worksheets in Intellij IDEA. It can simultaneously display the result as you type.There is no need to copy paste the code every time. Refer to this question to set it up: How to setup Intellij 14 Scala Worksheet to run Spark

Build your own environment by tweaking Atom text editor.
There are various plugins in atom to include a terminal along with code editor. Install one of them and open spark REPL in the terminal. If you prefer, you can add a shortcut to run the selected code in the REPL from editor(like ctrl+enter in Rstudio) Refer: https://atom.io/packages/terminal-plus

Title: rstudio like repl for spark-shell


问:
Import DataSet into SQL Server 2008 Express
I have a very large DataSet containing about 160.000 records. If I loop trough the dataset and import every record, it can take about 20 minutes before the complete dataset is imported into the SQL Server.

Isn't there a faster way for importing the dataset at once in the database?

The dataset is created from a file I process which the user provides, then I have 1 table called lets say "ImportTable" containing about 14 columns. The columns correspond with the columns in the DataSet.

I use Visual Studio 2010 professional with c#.

Thanks in advance!

答:
You should take a close look at the SqlBulkCopy class.

It's a C# component (no external app), it takes a DataSet or DataTable as input, and copies that into SQL Server in a bulk fashion. Should be significantly faster than doing a row-by-agonizing-row (RBAR) insert operation...

Better yet: you don't even need to import your entire data set into memory - you can define a SqlDataReader on your base data, and pass that to SqlBulkCopy to read from the SqlDataReader and bulk insert into SQL Server.


问:
query: return all rows even if the count of the associated rows are 0
i have this query:

```<code>$oe = OE::select([
    'oe.id',
    'oe.id_cartao',
    'oe.nome',
    'oe.email',
    \DB::raw('count(trienios.oe_id) as count')
])->leftjoin('trienios', 'trienios.oe_id', '=', 'oe.id')
->groupBy('trienios.oe_id');
</code>```

which translates to the following query:

```<code>select `oe`.`id`, `oe`.`id_cartao`, `oe`.`nome`, `oe`.`email`, count(trienios.oe_id) as count

from `oe`

left join `trienios` on `trienios`.`oe_id` = `oe`.`id`

group by `trienios`.`oe_id
</code>```

However, if there are no results in the trienios table, the query will only return a single record from the oe table. I want to return all the results from the oe table even if there are no results in the trienios table. How do I do that?

答:
Set group by on primary table

```<code>select `oe`.`id`, `oe`.`id_cartao`, `oe`.`nome`, `oe`.`email`, count(trienios.oe_id) as count from `oe` left join `trienios` on `trienios`.`oe_id` = `oe`.`id` group by `oe`.`id`
</code>```

Body:
i have this query:

$oe = OE::select([
    'oe.id',
    'oe.id_cartao',
    'oe.nome',
    'oe.email',
    \DB::raw('count(trienios.oe_id) as count')
])->leftjoin('trienios', 'trienios.oe_id', '=', 'oe.id')
->groupBy('trienios.oe_id');

which translates to the following query:

select `oe`.`id`, `oe`.`id_cartao`, `oe`.`nome`, `oe`.`email`, count(trienios.oe_id) as count

from `oe`

left join `trienios` on `trienios`.`oe_id` = `oe`.`id`

group by `trienios`.`oe_id

However, if there are no results in the trienios table, the query will only return a single record from the oe table. I want to return all the results from the oe table even if there are no results in the trienios table. How do I do that?

Body:
Set group by on primary table

select `oe`.`id`, `oe`.`id_cartao`, `oe`.`nome`, `oe`.`email`, count(trienios.oe_id) as count from `oe` left join `trienios` on `trienios`.`oe_id` = `oe`.`id` group by `oe`.`id`


问:
java.time.format.DateTimeParseException: Text could not be parsed at index 3
I am using Java 8 to parse the the date and find difference between two dates.

Here is my snippet:

```<code>String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";

DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate  d1 = LocalDate.parse(date1, df);
LocalDate  d2 = LocalDate.parse(date2, df);

Long datediff = ChronoUnit.DAYS.between(d1,d2);
</code>```

When I run I get the error:

java.time.format.DateTimeParseException: Text could not be parsed at index 3

答:
The following code works. The problem is you are using "JAN" instead of "Jan".
DateTimeFormatter does not recognize that it seems. and also change the pattern to
"d-MMM-yyyy".

```<code>  String date1 ="01-Jan-2017";
  String date2 = "02-Feb-2017";

  DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
  LocalDate  d1 = LocalDate.parse(date1, df);
  LocalDate  d2 = LocalDate.parse(date2, df);

  Long datediff = ChronoUnit.DAYS.between(d1,d2);
</code>```

Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/

Body:
I am using Java 8 to parse the the date and find difference between two dates.

Here is my snippet:

String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";

DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate  d1 = LocalDate.parse(date1, df);
LocalDate  d2 = LocalDate.parse(date2, df);

Long datediff = ChronoUnit.DAYS.between(d1,d2);

When I run I get the error:

java.time.format.DateTimeParseException: Text could not be parsed at index 3

Body:
The following code works. The problem is you are using "JAN" instead of "Jan".
DateTimeFormatter does not recognize that it seems. and also change the pattern to
"d-MMM-yyyy".

  String date1 ="01-Jan-2017";
  String date2 = "02-Feb-2017";

  DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
  LocalDate  d1 = LocalDate.parse(date1, df);
  LocalDate  d2 = LocalDate.parse(date2, df);

  Long datediff = ChronoUnit.DAYS.between(d1,d2);

Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/


问:
Django delete without calling signals
I use signals for things that should always be done when an object is deleted, saved, updated, etc. However, there are times when I don't want to call my save signals, so I use

Model.objects.filter(id=instance.id).update(field=value)

instead of the instance's save method:

instance.save()

In the case of deleting objects, there are also times when I don't want to call the delete signals, but I haven't found a way to avoid calling them. Is there a way??

UPDATE:

I'm using django 1.6.2 and calling the delete method like this:

Model.objects.filter(id=instance.id).delete()

on the queryset still still calls the delete signal.

答:
There is unsafe and undocumented way which probably can change between versions and also can lead to unexpected consequences which will be hard to debug.

This is a hack that probably you don't want to use but.... it's possible.

```<code>qs = Model.objects.filter(id=instance.id)
qs.order_by().select_related(None)._raw_delete(qs.db)
</code>```

If you have any related objects to this one it will probably fail with database error because records will not be deleted automatically by Django

Title: Django delete without calling signals

Body:
There is unsafe and undocumented way which probably can change between versions and also can lead to unexpected consequences which will be hard to debug.

This is a hack that probably you don't want to use but.... it's possible.

qs = Model.objects.filter(id=instance.id)
qs.order_by().select_related(None)._raw_delete(qs.db)

If you have any related objects to this one it will probably fail with database error because records will not be deleted automatically by Django


问:
Why //= (defined-or) does not work in same way for array as for scalar?
I have the following code:

```<code>$var //= 1;
@arr //= qw/ 1 2 3 /;
</code>```

But I get error:

Can't modify array dereference in defined or assignment (//=) at ...

Even this @arr ||= qw/ 1 2 3 /; does not work:

Can't modify array dereference in logical or assignment (||=) at ...

But this works as expected:

```<code>@arr = @arr || qw/ 1 2 3 /;

print "@arr"; # 1 2 3
</code>```

答:
See "Assignment Operators" in perldoc perlop:

These combined assignment operators can only operate on scalars...

Body:
I have the following code:

$var //= 1;
@arr //= qw/ 1 2 3 /;

But I get error:

Can't modify array dereference in defined or assignment (//=) at ...

Even this @arr ||= qw/ 1 2 3 /; does not work:

Can't modify array dereference in logical or assignment (||=) at ...

But this works as expected:

@arr = @arr || qw/ 1 2 3 /;

print "@arr"; # 1 2 3


问:
URLSession in Swift 3 - URLAuthenticationChallenge
Below is the snippet for making request.

```<code>        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        let configurationId = String(format: "NetworkManager%d", UInt16(arc4random_uniform(UInt32(UINT16_MAX))))
        let configuration = URLSessionConfiguration.background(withIdentifier: configurationId)
        let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.current)
        let task = session.downloadTask(with: request)
        task.resume()
</code>```

While making this request, the authentication challenge methods as described below are not getting called.

```<code>@nonobjc func urlSession(_ session: Foundation.URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)

@nonobjc func urlSession(_ session: Foundation.URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler:  (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)
</code>```

答:
Try using the following header slightly different from the ones you listed in your question.</p>

```<code>open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    //handle challenge here.
}
</code>```

Body:
Below is the snippet for making request.

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        let configurationId = String(format: "NetworkManager%d", UInt16(arc4random_uniform(UInt32(UINT16_MAX))))
        let configuration = URLSessionConfiguration.background(withIdentifier: configurationId)
        let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.current)
        let task = session.downloadTask(with: request)
        task.resume()

While making this request, the authentication challenge methods as described below are not getting called.

@nonobjc func urlSession(_ session: Foundation.URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)

@nonobjc func urlSession(_ session: Foundation.URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler:  (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)

Body:
Try using the following header slightly different from the ones you listed in your question.

open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    //handle challenge here.
}


问:
find the almost identical cells in a range
i am looking for a formula or something like that to find the most nearest or almost identical values in a range of google spreadsheet.
for example look at the following values of different cells.
3,5,13,18,19,20,21,26,28,52,62,75

I want a result like this group of value (18,19,20,21)
because in that range, only these values has the least difference to each of them.

if it is possible then please help..
Thanks in advance!

答:
Place the values in column A and sort them.  Then in B1 enter:

```<code>=IF(A2-A1<=1,"Good","")
</code>```

and in B2 enter:

```<code>=IF(OR(A3-A2<=1,A2-A1<=1),"Good","")
</code>```

and copy down.

Body:
Place the values in column A and sort them.  Then in B1 enter:

=IF(A2-A1<=1,"Good","")

and in B2 enter:

=IF(OR(A3-A2<=1,A2-A1<=1),"Good","")

and copy down.


问:
jquery swap ul childs between two ul's
I have the following html with two lists, and I want to press a button and swap the ul's, li´s elements between the two

```<code><ul class="list-group" id="lines">
<li class="list-group-item> 1 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
<li class="list-group-item> 3 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>
</code>```

I have tried to accomplish this with the following jquery code

```<code>$("#swaplists").click(function () {

 var $temp1 = $("#lines").children.clone;
 var $temp2 = $("#columns").children.clone;
 clearLinesAndColumns();
 $temp2.appendTo("#lines");
 $temp1.appendTo("#columns");

});
</code>```

the expected result would be

```<code><ul class="list-group" id="lines">
<li class="list-group-item> 3 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
<li class="list-group-item> 1 <i class="fa fa-times" aria-hidden="true"></i></li>
<li class="list-group-item> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>
</code>```

But I get the error

Uncaught TypeError: Cannot read property 'appendTo' of undefined

How can I achieve this functionality with jquery and why is children.clone undefined?

答:
```<code>$("#swaplists").click(function () {

 var $temp1 = $("#lines").children().clone();
 var $temp2 = $("#columns").children().clone();
 clearLinesAndColumns();
 $temp2.appendTo("#lines");
 $temp1.appendTo("#columns");

});
</code>```

You forgot to put '()' after calling 'children' and 'clone'...those are methods.

Title: jquery swap ul childs between two ul's

Body:
I have the following html with two lists, and I want to press a button and swap the ul's, li´s elements between the two

 1

 2

 3

 4

I have tried to accomplish this with the following jquery code

$("#swaplists").click(function () {

 var $temp1 = $("#lines").children.clone;
 var $temp2 = $("#columns").children.clone;
 clearLinesAndColumns();
 $temp2.appendTo("#lines");
 $temp1.appendTo("#columns");

});

the expected result would be

 3

 4

 1

 2

But I get the error

Uncaught TypeError: Cannot read property 'appendTo' of undefined

How can I achieve this functionality with jquery and why is children.clone undefined?

Body:
$("#swaplists").click(function () {

 var $temp1 = $("#lines").children().clone();
 var $temp2 = $("#columns").children().clone();
 clearLinesAndColumns();
 $temp2.appendTo("#lines");
 $temp1.appendTo("#columns");

});

You forgot to put '()' after calling 'children' and 'clone'...those are methods.


问:
c# reading in a text file into datatable
i need to read files that look like this into a datatable:

```<code>A02   BLANK031
B02   F357442
C02   F264977
D02   BLANK037
E02   F272521
F02   E121562
G02   F264972
H02   F332321
A03   E208240
B03   F313854
C03   E229786
D03   E229787
E03   F307584
F03   F357478
</code>```

i have a weird delimitter and some trailing spaces.
how would i read this into a datatable such that the first column will contain 'A02','B02'... and the second column will contain 'BLANK031','F357442',etc..

currently i am doing:

```<code>DataTable dt = new DataTable();
                using (TextReader tr = File.OpenText(batchesAddresses[index]))
                {
                    string line;
                    while ((line = tr.ReadLine()) != null)
                    {

                    string[] items = Regex.Split(line, ' ');
                    if (dt.Columns.Count == 0)
                    {
                        // Create the data columns for the data table based on the number of items
                        // on the first line of the file
                        for (int i = 0; i < items.Length; i++)
                            dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
                    }
                        dt.Rows.Add(items);

                    }
                }
</code>```

but this is not working because i have trailing spaces and multiple spaces between columns

答:
Change your regex to something like: (\w{3})\s+(\w{5,10}).  This means capture 3 word chars (including digits) into group 1, look for one or more whitespace characters, and then capture 5-10 word chars into group 2.

Then do:

```<code>Regex r = new Regex("(\w{3})\s+(\w{5,10})");
Match m = r.Match(line);
string col1 = m.Groups[1].Value;
string col2 = m.Groups[2].Value;
</code>```

Body:
i need to read files that look like this into a datatable:

A02   BLANK031
B02   F357442
C02   F264977
D02   BLANK037
E02   F272521
F02   E121562
G02   F264972
H02   F332321
A03   E208240
B03   F313854
C03   E229786
D03   E229787
E03   F307584
F03   F357478

i have a weird delimitter and some trailing spaces.
how would i read this into a datatable such that the first column will contain 'A02','B02'... and the second column will contain 'BLANK031','F357442',etc..

currently i am doing:

DataTable dt = new DataTable();
                using (TextReader tr = File.OpenText(batchesAddresses[index]))
                {
                    string line;
                    while ((line = tr.ReadLine()) != null)
                    {

                    string[] items = Regex.Split(line, ' ');
                    if (dt.Columns.Count == 0)
                    {
                        // Create the data columns for the data table based on the number of items
                        // on the first line of the file
                        for (int i = 0; i < items.Length; i++)
                            dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
                    }
                        dt.Rows.Add(items);

                    }
                }

but this is not working because i have trailing spaces and multiple spaces between columns

Body:
Change your regex to something like: (\w{3})\s+(\w{5,10}).  This means capture 3 word chars (including digits) into group 1, look for one or more whitespace characters, and then capture 5-10 word chars into group 2.

Then do:

Regex r = new Regex("(\w{3})\s+(\w{5,10})");
Match m = r.Match(line);
string col1 = m.Groups[1].Value;
string col2 = m.Groups[2].Value;


问:
javascript onclick create element (label)
I am currently developing a webapp, draft link: http://webtrickssolutions.in/ayna/new-Building.html#

i have problem with javascript coding, when pressing on "OK" button, it should add a row underneath the filled data "Language" and "Text" / the new row should be Label. for example if i added two times:

English "BuildingName01" (delete icon)
Arabic  "XXXXX05" (delete icon)

and it should remove the English and Arabic from the drop down menu as i cant select the language twice.

current javascript code is:

```<code><script type="text/javascript">
    $(document).ready(function(){

        $('.del').live('click',function(){
            $(this).parent().parent().remove();
        });

        $('.add').live('click',function(){
            $(this).val('Delete');
            $(this).attr('class','del');

            var appendTxt = "<tr><td><select class='form-control form-control-bottom lang' name='input_box_one[]'><option>Language</option><option>English</option><option>Hindi</option></select></td> <td><input type='text' name='input_box_two[]' /></td> <td><input type='button' class='add' value='Ok' /></td></tr>";

            $("#options-table tr:first").before(appendTxt);
        });
    });
</script>
</code>```

答:
If you want to remove the specific element, this can be removed via

```<code>$("#selectBox option[value='English']").remove();
</code>```

However, for this to be dynamic, you would have to first grab the value of the selected index:

```<code>var option = $('#selector :selected').val()
</code>```

Following, remove this using a dynamic selector, like:

```<code>$("#selectBox2 option[value='" + option + "]")
</code>```

EDIT: Updated Post:

I'd suggest that, the further down you go the more complex this object will be to maintain. Therefore, I suggest that instead of dynamically adding the element through a string, like so, you instead generate it using an array. This can be seen in this Fiddle. Obviously, this uses a newer version of jQuery, so can replace the 'On' with the 'Live' method.

This works by firstly creating a new select element:

```<code>var newSelect = $('<select/>');
</code>```

Then, adds each element from the current dropdown as options to this select

```<code>$(this).parent().find("option:not(:selected)").each(function() {
    newSelect.append($('<option/>').html($(this).val()));
});
</code>```

& Finally appending this to the document

```<code>$("#options-table").before(newSelect);
</code>```

Body:
If you want to remove the specific element, this can be removed via

$("#selectBox option[value='English']").remove();

However, for this to be dynamic, you would have to first grab the value of the selected index:

var option = $('#selector :selected').val()

Following, remove this using a dynamic selector, like:

$("#selectBox2 option[value='" + option + "]")

EDIT: Updated Post:

I'd suggest that, the further down you go the more complex this object will be to maintain. Therefore, I suggest that instead of dynamically adding the element through a string, like so, you instead generate it using an array. This can be seen in this Fiddle. Obviously, this uses a newer version of jQuery, so can replace the 'On' with the 'Live' method.

This works by firstly creating a new select element:

var newSelect = $('<select/>');

Then, adds each element from the current dropdown as options to this select

$(this).parent().find("option:not(:selected)").each(function() {
    newSelect.append($('<option/>').html($(this).val()));
});

& Finally appending this to the document

$("#options-table").before(newSelect);


问:
#define function with variable name
I am continually writing something akin to

```<code>std::vector< std::vector< double > > A(N, std::vector< double >(M));
</code>```

and I would like to replace this with something like

```<code>matrix A(N,M);
</code>```

by using a #define directive. I've looked at #define directives and think I can create a function like matrix(A,N,M) that would declare a vector of vectors as follows:

```<code>#define matrix(A, N, M) std::vector< std::vector< double > > A(N, std::vector< double >(M))
</code>```

but I would rather not declare my matrices as matrix(A,N,M), but rather matrix A(N,M). My question is - how do I use the #define directives to account for changing a variable name?

答:
Alternative answer to typedef

using matrix = std::vector< std::vector<double>>;

This form can be more readable, especially with function and array types. E.g. using arr10 = Foo[10] is clearer than typedef Foo arra10[10]. The = sign clearly separates what's being defined and how it's defined.

(Ignoring the whole "matrix is not a vector of vectors" discussion)

Title: #define function with variable name

Body:
I am continually writing something akin to

std::vector< std::vector< double > > A(N, std::vector< double >(M));

and I would like to replace this with something like

matrix A(N,M);

by using a #define directive. I've looked at #define directives and think I can create a function like matrix(A,N,M) that would declare a vector of vectors as follows:

#define matrix(A, N, M) std::vector< std::vector< double > > A(N, std::vector< double >(M))

but I would rather not declare my matrices as matrix(A,N,M), but rather matrix A(N,M). My question is - how do I use the #define directives to account for changing a variable name?


答:
Here is the sample code:

$("#swaplists").click(function() {

  var $temp1 = $("#lines li");
  var $temp2 = $("#columns li");

  $temp2.appendTo("#lines");
  $temp1.appendTo("#columns");

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group" id="lines">
  <li class="list-group-item"> 1 <i class="fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
  <li class="list-group-item"> 3 <i class=" fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<button id="swaplists">SWAP LISTS</button></code>```

Title: jquery swap ul childs between two ul's

Body:
Here is the sample code:

$("#swaplists").click(function() {

  var $temp1 = $("#lines li");
  var $temp2 = $("#columns li");

  $temp2.appendTo("#lines");
  $temp1.appendTo("#columns");

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group" id="lines">
  <li class="list-group-item"> 1 <i class="fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 2 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<ul class="list-group" id="columns">
  <li class="list-group-item"> 3 <i class=" fa fa-times " aria-hidden="true "></i></li>
  <li class="list-group-item"> 4 <i class="fa fa-times" aria-hidden="true"></i></li>
</ul>

<button id="swaplists">SWAP LISTS</button>


问:
SharePoint site hierarchy for company intranet - multiple sites or sub-sites with one root?
I'm the IT Manager at a mid-size manufacturing company.  We are getting our feet wet with SharePoint - so far we're got one blog in production use> It's the CEO's.

We have use cases for a couple of list-based "applications" with some simple workflow that will be implemented by one of our developers.  We also want to give our users (at least the more tech-savvy ones) the ability to create and work with their own departmental sites.

We're concerned, however, that we might be starting something that could quickly get out of control if it's widely adopted (which would be a good thing).  Since we don't really understand all the architectural trade-offs, we could end up with massive amounts of user data in a structure that bites us down the road.

Our biggest question is whether to have multiple sites for each use vs. a single root site from which everything else descends.  Multiple sites would give us flexibility to make changes or develop new features without creating problems for all the users.  However, multiple sites might be harder to back-up, search, and maintain user profiles/security.  A single massive site seems to reverse the cost/benefits.

I'd appreciate any insight on the one vs. many trade-offs, or links to resources that discuss it.  Links to general SharePoint "enterprise best practices" (sorry) would also be appreciated.

Thanks.

答: It purely depends upon your needs and requirements. even having a deferent web applications for deferent site i can provide you one citation taking backup as advantage. You might have few sites where data does not changes frequently like organizational policies, process documents etc. in this case taking regular backups/search crawling does not make sense(although you can opt for differential backup and incremental crawl but still in a week or fortnightly you have to take full backup). hence i would suggest carefully analyze your requirements and then take a decision. Microsoft has provided a good list of checklist and templates for planning purpose. few of the links are provided in madhur's reply and rest you can google upon. </p>


问:
how to achieve synchronization of threads using synchronized method in java?
i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.

```<code>class ABC {

    synchronized public void meth(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}

class SyncMethod implements Runnable {

    ABC a = new ABC();
    Thread t;

    SyncMethod(String s) {
        t = new Thread(this, s);
        t.start();
    }

    public void run() {
        a.meth(t.getName());
    }

    public static void main(String args[]) {
        new SyncMethod("Hello");
        new SyncMethod("Synchronized");
        new SyncMethod("World");
    }
}
</code>```

Current Output :

```<code>        [Hello [Synchronized [World] ] ] ]
</code>```

Desired Output :

```<code>        [Hello]
        [Synchronized]
        [World]
</code>```

答:
i have come with a better solution myself. As @urag says that we need a single object to call the synchronized method while i was creating a new object evrytime thus calling 3 synchronized methods . we can make the object of class ABC static and thus it will not respawn itself and the code will also become shorter.I have checked this works.</p>

```<code>    class ABC
{
    synchronized public void meth(String msg)
    {
        System.out.print("[" + msg);
        try
        {
            Thread.sleep(1000);
        }
        catch(InterruptedException e)
        {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}
class SyncMethod implements Runnable
{
    static ABC a = new ABC();
    Thread t;
    SyncMethod(String s)
    {
        t= new Thread(this,s);
        t.start();
    }
    public void run()
    {
        a.meth(t.getName());
    }
    public static void main(String args[])
    {
        //ABC a = new ABC();
        new SyncMethod("Hello");
        new SyncMethod("World");
        new SyncMethod("Synchronized");
    }
}
</code>```

Body:
i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.

class ABC {

    synchronized public void meth(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}

class SyncMethod implements Runnable {

    ABC a = new ABC();
    Thread t;

    SyncMethod(String s) {
        t = new Thread(this, s);
        t.start();
    }

    public void run() {
        a.meth(t.getName());
    }

    public static void main(String args[]) {
        new SyncMethod("Hello");
        new SyncMethod("Synchronized");
        new SyncMethod("World");
    }
}

Current Output :

        [Hello [Synchronized [World] ] ] ]

Desired Output :

        [Hello]
        [Synchronized]
        [World]

Body:
i have come with a better solution myself. As @urag says that we need a single object to call the synchronized method while i was creating a new object evrytime thus calling 3 synchronized methods . we can make the object of class ABC static and thus it will not respawn itself and the code will also become shorter.I have checked this works.

    class ABC
{
    synchronized public void meth(String msg)
    {
        System.out.print("[" + msg);
        try
        {
            Thread.sleep(1000);
        }
        catch(InterruptedException e)
        {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}
class SyncMethod implements Runnable
{
    static ABC a = new ABC();
    Thread t;
    SyncMethod(String s)
    {
        t= new Thread(this,s);
        t.start();
    }
    public void run()
    {
        a.meth(t.getName());
    }
    public static void main(String args[])
    {
        //ABC a = new ABC();
        new SyncMethod("Hello");
        new SyncMethod("World");
        new SyncMethod("Synchronized");
    }
}


问:
Stop thread with while running
I'm making a keylog and the code of keylog is in a class extends Thread. And I put a boolean running like variable and I have this code :

```<code>public void run() {
    while(running)
        try {
            Config conf = new Config();
            System.setOut(new PrintStream(new File("keylog/output-file.txt")));

            GlobalScreen.registerNativeHook();

            GlobalScreen.getInstance().addNativeKeyListener(new Keylog(conf));

        } catch (FileNotFoundException | NativeHookException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
</code>```

And i have another void method to stop thread

```<code>void stopKeylog() {
    running=false;
}
</code>```

But when, I stop thread, I will see the output txt file and is with bugs.
And when I remove the while(running) the output, the works perfectly.

答:
Few quick inputs if it helps:
1. Make running as volatile
2. Close the PrintStream (not sure if it would help)</p>

Title: Stop thread with while running

Body:
I'm making a keylog and the code of keylog is in a class extends Thread. And I put a boolean running like variable and I have this code :

public void run() {
    while(running)
        try {
            Config conf = new Config();
            System.setOut(new PrintStream(new File("keylog/output-file.txt")));

            GlobalScreen.registerNativeHook();

            GlobalScreen.getInstance().addNativeKeyListener(new Keylog(conf));

        } catch (FileNotFoundException | NativeHookException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

And i have another void method to stop thread

void stopKeylog() {
    running=false;
}

But when, I stop thread, I will see the output txt file and is with bugs.
And when I remove the while(running) the output, the works perfectly.


问:
I want to create an array of words from a txt document in C#.
The Split method returns an error.</p>

```<code>static void Main(string[] args)
    {
        string[] ebook = File.ReadLines("C:\\Users\\Michael\\Downloads\\Documents\\x.txt").ToArray();

        string[] words = ebook.Split(' ');

    }
</code>```

答:
Not File.ReadLines(...).Split(' ') but ReadAllText(...).Split()

```<code>string[] words = File.ReadAllText(path).Split();
</code>```

You can use the Split() to split by every white-space including new-line characters or tabs.

Body:
The Split method returns an error.

static void Main(string[] args)
    {
        string[] ebook = File.ReadLines("C:\\Users\\Michael\\Downloads\\Documents\\x.txt").ToArray();

        string[] words = ebook.Split(' ');

    }

Body:
Not File.ReadLines(...).Split(' ') but ReadAllText(...).Split()

string[] words = File.ReadAllText(path).Split();

You can use the Split() to split by every white-space including new-line characters or tabs.


问:
profiling a method of a class in Python using cProfile?
I'd like to profile a method of a function in Python, using cProfile. I tried the following:

```<code>import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")
</code>```

But it does not work. How can I call a self.method with "run"?

答:
Use the profilehooks decorator

http://pypi.python.org/pypi/profilehooks

ContentLicense: CC BY-SA 4.0

Body:
I'd like to profile a method of a function in Python, using cProfile. I tried the following:

import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")

But it does not work. How can I call a self.method with "run"?


问:
python matplotlib: how to move the scale to the other side of the axis?
I have this weird thing with the scale of the axis showing out of the figure like:

And what I want to have:

How can I move the scale to the other side of the axis?

```<code>x=range(len(ticks))
plt.plot(x,phase1,'r^-',label='$\Delta \phi(U1,I1)$')
plt.plot(x,phase2,'go-',label='$\Delta \phi(U2,I2)$')
plt.plot(x,phase3,'b*-',label='$\Delta \phi(U3,I3)$')
plt.xticks(x,ticks,rotation=45)
plt.xlabel('Messung')
plt.ylabel('$\Delta \phi [^\circ]$')
plt.legend()
plt.show()
</code>```

答:
You can use plt.tick_params() to adjust the behaviour of the ticks, documentation can be found here.

For your example you want the ticks to appear inside the figure. Therefore add

```<code>plt.tick_params(direction="in")
</code>```

to your code. Example:

```<code>x=range(len(ticks))

plt.plot(x,phase1,'r^-',label='$\Delta \phi(U1,I1)$')
plt.plot(x,phase2,'go-',label='$\Delta \phi(U2,I2)$')
plt.plot(x,phase3,'b*-',label='$\Delta \phi(U3,I3)$')

plt.xticks(x,ticks,rotation=45)
plt.xlabel('Messung')
plt.ylabel('$\Delta \phi [^\circ]$')
plt.legend()

plt.tick_params(direction="in") # Set ticks inside the figure

plt.show()
</code>```

You can get the ticks to appear on the top and right side of the figure too as shown in your second screenshot by adding:

```<code>plt.tick_params(direction="in",top="on",right="on")
</code>```

If you wanted to make all figures in your Python script have this behaviour then you can add the following at the top of your script (this might be of interest):

```<code>import matplotlib

matplotlib.rcParams['xtick.direction'] = "in"
matplotlib.rcParams['ytick.direction'] = "in"
</code>```

This will save you having to call plt.tick_params() for each figure, which is helpful if you generate lots of figures.

Body:
I have this weird thing with the scale of the axis showing out of the figure like:

And what I want to have:

How can I move the scale to the other side of the axis?

x=range(len(ticks))
plt.plot(x,phase1,'r^-',label='$\Delta \phi(U1,I1)$')
plt.plot(x,phase2,'go-',label='$\Delta \phi(U2,I2)$')
plt.plot(x,phase3,'b*-',label='$\Delta \phi(U3,I3)$')
plt.xticks(x,ticks,rotation=45)
plt.xlabel('Messung')
plt.ylabel('$\Delta \phi [^\circ]$')
plt.legend()
plt.show()

Body:
You can use plt.tick_params() to adjust the behaviour of the ticks, documentation can be found here.

For your example you want the ticks to appear inside the figure. Therefore add

plt.tick_params(direction="in")

to your code. Example:

x=range(len(ticks))

plt.plot(x,phase1,'r^-',label='$\Delta \phi(U1,I1)$')
plt.plot(x,phase2,'go-',label='$\Delta \phi(U2,I2)$')
plt.plot(x,phase3,'b*-',label='$\Delta \phi(U3,I3)$')

plt.xticks(x,ticks,rotation=45)
plt.xlabel('Messung')
plt.ylabel('$\Delta \phi [^\circ]$')
plt.legend()

plt.tick_params(direction="in") # Set ticks inside the figure

plt.show()

You can get the ticks to appear on the top and right side of the figure too as shown in your second screenshot by adding:

plt.tick_params(direction="in",top="on",right="on")

If you wanted to make all figures in your Python script have this behaviour then you can add the following at the top of your script (this might be of interest):

import matplotlib

matplotlib.rcParams['xtick.direction'] = "in"
matplotlib.rcParams['ytick.direction'] = "in"

This will save you having to call plt.tick_params() for each figure, which is helpful if you generate lots of figures.


问:
How do I set an environment variable using docker service create?
The command line arguments listed here: https://docs.docker.com/engine/reference/commandline/service_create

Does not specify the exact syntax, only -e.

答:
It is explained further down the page: https://docs.docker.com/engine/reference/commandline/service_create/#set-environment-variables--e-env

--env MYVAR=foo


问:
Determining if a list is empty or not
I want to do some if | else stuff in prolog. Below is my code, Prolog will return 'R = false' if my input list is not empty, it will return 'false' if my list is empty. What do I miss?

Code:

```<code>isEmpty([H|T],R) :-
    length([H|T],L),
    ( L > 0 -> R = 'false'
    ;
    L =:= 0 -> R = 'true'
    ).
</code>```

Prolog Output:

```<code>1 ?- isEmpty([],R).
false.

2 ?- isEmpty([1],R).
R = false.

3 ?- isEmpty([1,2,3],R).
R = false.
</code>```

答:
I know it's old thread but still this might be useful for those using SWI-Prolog. Instead of defining their own rules, you can try:

```<code>nth0(0, List, _).
</code>```

It is used to return the first element on the list, which in case of empty list simply fails.

Title: Determining if a list is empty or not

Body:
I want to do some if | else stuff in prolog. Below is my code, Prolog will return 'R = false' if my input list is not empty, it will return 'false' if my list is empty. What do I miss?

Code:

isEmpty([H|T],R) :-
    length([H|T],L),
    ( L > 0 -> R = 'false'
    ;
    L =:= 0 -> R = 'true'
    ).

Prolog Output:

1 ?- isEmpty([],R).
false.

2 ?- isEmpty([1],R).
R = false.

3 ?- isEmpty([1,2,3],R).
R = false.

Body:
I know it's old thread but still this might be useful for those using SWI-Prolog. Instead of defining their own rules, you can try:

nth0(0, List, _).

It is used to return the first element on the list, which in case of empty list simply fails.


问:
Swift sub-modules in Cocoapods
I'm trying to set up the following arrangement of private Cocoapods:

PodA depends on PodB which depends on CommonCrypto.

CommonCrypto is a dylib that ships with iOS but doesn't have a Swift header module. Within PodB I've created a custom module.modulemap with the following contents:

```<code>module CommonCrypto [system] {
    header "/usr/include/CommonCrypto/CommonCrypto.h"
}
</code>```

PodB passes the lint test (pod spec lint PodB.podspec) after adding the following lines:

```<code># Ensure module isn't deleted by CocoaPods
s.preserve_paths = 'path_to/PodB/CommonCrypto'
s.pod_target_xcconfig = { 'HEADER_SEARCH_PATHS' => '$(PODS_ROOT)/path_to/CommonCrypto' }
</code>```

Within PodA, I depend on PodB with s.dependency = 'PodB'. When linting PodA with pod spec lint --sources=myrepo PodA.podspec I get an error compiling any Swift file with import PodB:

```<code>missing required module 'CommonCrypto'
</code>```

How can I go about fixing this? It doesn't matter to me if CommonCrypto is private or public to PodB.

I tried adding export * to module.modulemap but that made no difference.

答:
using $(PODS_TARGET_SRCROOT) instead of $(PODS_ROOT)/podname/ worked for me

```<code>s.source_files = 'Classes/**/*.swift', 'modules/**/*.map'
s.preserve_paths = 'modules/**/*.map'

s.pod_target_xcconfig = {
   'SWIFT_INCLUDE_PATHS[sdk=iphoneos*]'         => '$(PODS_TARGET_SRCROOT)/modules/iphoneos/CommonCrypto',
   'SWIFT_INCLUDE_PATHS[sdk=iphonesimulator*]'  => '$(PODS_TARGET_SRCROOT)/modules/iphonesimulator/CommonCrypto',
}
</code>```

module.map files:
modules/iphoneos/CommonCrypto/module.map:

```<code>module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    export *
}
</code>```

modules/iphonesimulator/CommonCrypto/module.map:

```<code>module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    export *
}
</code>```

Title: Swift sub-modules in Cocoapods

Body:
I'm trying to set up the following arrangement of private Cocoapods:

PodA depends on PodB which depends on CommonCrypto.

CommonCrypto is a dylib that ships with iOS but doesn't have a Swift header module. Within PodB I've created a custom module.modulemap with the following contents:

module CommonCrypto [system] {
    header "/usr/include/CommonCrypto/CommonCrypto.h"
}

PodB passes the lint test (pod spec lint PodB.podspec) after adding the following lines:

# Ensure module isn't deleted by CocoaPods
s.preserve_paths = 'path_to/PodB/CommonCrypto'
s.pod_target_xcconfig = { 'HEADER_SEARCH_PATHS' => '$(PODS_ROOT)/path_to/CommonCrypto' }

Within PodA, I depend on PodB with s.dependency = 'PodB'. When linting PodA with pod spec lint --sources=myrepo PodA.podspec I get an error compiling any Swift file with import PodB:

missing required module 'CommonCrypto'

How can I go about fixing this? It doesn't matter to me if CommonCrypto is private or public to PodB.

I tried adding export * to module.modulemap but that made no difference.

Body:
using $(PODS_TARGET_SRCROOT) instead of $(PODS_ROOT)/podname/ worked for me

s.source_files = 'Classes/**/*.swift', 'modules/**/*.map'
s.preserve_paths = 'modules/**/*.map'

s.pod_target_xcconfig = {
   'SWIFT_INCLUDE_PATHS[sdk=iphoneos*]'         => '$(PODS_TARGET_SRCROOT)/modules/iphoneos/CommonCrypto',
   'SWIFT_INCLUDE_PATHS[sdk=iphonesimulator*]'  => '$(PODS_TARGET_SRCROOT)/modules/iphonesimulator/CommonCrypto',
}

module.map files:
modules/iphoneos/CommonCrypto/module.map:

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    export *
}

modules/iphonesimulator/CommonCrypto/module.map:

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    export *
}


问:
Passing ID Of Dynamic Javascript HTML
I'm trying to pass the element itself, or id. How can I make this work?

```<code>onclick="addYes(this)"
</code>```

```<code>for (var i = 0; i < data.length; i++) {
  tempTable+= '<tr>'+
    '<td  class="cust-data-row"style="height:40px;width:40%;">'+
    data[i].service+
    '</td>'+
    '</td>'+
    '<td  class="cust-data-row-yes" style="height:40px;width:10%;  id="rec_btn_yes_' +i+'"  onclick="addYes(this)" >'+
    'Yes'+
    '</td>'+
    '</tr>';
}

function addYes(button){
  //shows nothing:
  alert(button.id);
  //not working:
  document.getElementById(button.id).addClass("clicked_yes");
  //unrecognized method:
  button.addClass("clicked_yes");
}
</code>```

答:
Take a look in this snippet with pure javascript:

var tempTable = "<button id='theID' onclick='addYes(this)'>retrieve id</button>";

document.body.innerHTML += tempTable;

function addYes(button){
alert(button.id);
//As @SatPal commented
button.classList.add("clicked_yes");
}  ```

Title: Passing ID Of Dynamic Javascript HTML

Body:
I'm trying to pass the element itself, or id. How can I make this work?

onclick="addYes(this)"

for (var i = 0; i < data.length; i++) {
  tempTable+= '
'+
    ''+
    data[i].service+
    '	'+
    '	'+
    ''+
    'Yes'+
    '	'+
    '
';
}

function addYes(button){
  //shows nothing:
  alert(button.id);
  //not working:
  document.getElementById(button.id).addClass("clicked_yes");
  //unrecognized method:
  button.addClass("clicked_yes");
}


问:
How to update a variable outside a function in corona sdk?
How do I change the variable outside a function(in my case it is an eventListener)? I have a goal, which is a circle and I want its radius to change when the score is over 10. How do I update the variable to check what the radius is?</p>

```<code> local goal
 local goalRadius = 40

 local function checkScore()
   if(score>10)then
      goalRadius = 20
      --UPDATE THE VARIABLE?
 end

goal = display.newCircle(0,0,goalRadius)
goal:addEventListener("touch", checkScore)
</code>```

答:
What I did to solve this proble was this: I used removeSelf() to delete the goal and then I recreated it.</p>

```<code> local goal
 local goalRadius = 40

 local function checkScore()
  if(score>10)then
       goal:removeSelf()
       goalRadius = 20
       goal = display.newCircle(0,0,goalRadius)
  end
 end

 goal = display.newCircle(0,0,goalRadius)
 goal:addEventListener("touch", checkScore)
</code>```

Body:
How do I change the variable outside a function(in my case it is an eventListener)? I have a goal, which is a circle and I want its radius to change when the score is over 10. How do I update the variable to check what the radius is?

 local goal
 local goalRadius = 40

 local function checkScore()
   if(score>10)then
      goalRadius = 20
      --UPDATE THE VARIABLE?
 end

goal = display.newCircle(0,0,goalRadius)
goal:addEventListener("touch", checkScore)

Body:
What I did to solve this proble was this: I used removeSelf() to delete the goal and then I recreated it.

 local goal
 local goalRadius = 40

 local function checkScore()
  if(score>10)then
       goal:removeSelf()
       goalRadius = 20
       goal = display.newCircle(0,0,goalRadius)
  end
 end

 goal = display.newCircle(0,0,goalRadius)
 goal:addEventListener("touch", checkScore)