问:
Attach file to email using sendgrid
I'm using sendgrid mailer, and I'm fail to attach csv file to mail function.
Below is code for composing mail...

$resumeName = $_FILES['resume']['name'];

$resumePath = $_FILES['resume']['tmp_name'];

Need to download this file in sender mail...

```<code>  public static function sendMailwithAttachment($mail_type, $mail_variable = array(), $subject, $from, $to, $resumeName, $resumePath) {

    $CI = & get_instance();

    if ($mail_type !== NULL) {
        $CI->db->select('tpl');
        $CI->db->from('tblMailTypes');
        $CI->db->where('id', $mail_type);
        $query = $CI->db->get();

        $mailIdres = $query->result_array();
        if (!empty($mailIdres)) {
            $message = $mailIdres[0]['tpl'];
            if (!empty($mail_variable)) {
                foreach ($mail_variable as $key => $val) {
                    $message = str_ireplace($key, $val, $message); // select message format from table
                }
            }
        }
    }

    $from = new SendGrid\Email(null, $from);

    $to = new SendGrid\Email(null, $to);

    $content = new SendGrid\Content("text/html", $message);
    exit();

    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $apiKey = 'ABCD..................HHHHFFFRRDSE'; // Sendgrid API key
    $sg = new \SendGrid($apiKey);

   addAttachment($resumePath, $resumeName);

   $response = $sg->client->mail()->send()->post($mail);
}
</code>```

Anyone please help

答:
This code working perfectly...</p>

```<code>public static function sendEMailwithAttachment($mail_type, $mail_variable = array(), $subject, $from, $mailto,$username, $fileName, $filePath){

       // If you are using Composer (recommended)
require 'vendor/autoload.php';

 // If you are not using Composer
 // require("path/to/sendgrid-php/sendgrid-php.php");

    $CI = & get_instance();

    if ($mail_type !== NULL) {
        $CI->db->select('tpl');
        $CI->db->from('tblMailTypes');
        $CI->db->where('id', $mail_type);
        $query = $CI->db->get();

        $mailIdres = $query->result_array();
        if (!empty($mailIdres)) {
            $message = $mailIdres[0]['tpl'];
            if (!empty($mail_variable)) {
                foreach ($mail_variable as $key => $val) {
                    $message = str_ireplace($key, $val, $message);
                }
            }
        }
    }

 $from = new SendGrid\Email("User", $from);

 $to = new SendGrid\Email($username,$mailto);
 $content = new SendGrid\Content("text/html", $message);
 $file = $filePath;
 $file_encoded = base64_encode(file_get_contents($file));
 $attachment = new SendGrid\Attachment();
 $attachment->setContent($file_encoded);
 $attachment->setType("application/text");
 $attachment->setDisposition("attachment");
 $attachment->setFilename($fileName);

 $mail = new SendGrid\Mail($from, $subject, $to, $content);
 $mail->addAttachment($attachment);

 $apiKey = 'ABCD..................HHHHFFFRRDSE'; // Sendgrid API key

 $sg = new \SendGrid($apiKey);

 $response = $sg->client->mail()->send()->post($mail);

// If you want response

//echo $response->statusCode();
//echo $response->headers();
//echo $response->body();
}
</code>```

Title: Attach file to email using sendgrid

Body:
I'm using sendgrid mailer, and I'm fail to attach csv file to mail function.
Below is code for composing mail...

$resumeName = $_FILES['resume']['name'];

$resumePath = $_FILES['resume']['tmp_name'];

Need to download this file in sender mail...

  public static function sendMailwithAttachment($mail_type, $mail_variable = array(), $subject, $from, $to, $resumeName, $resumePath) {

    $CI = & get_instance();

    if ($mail_type !== NULL) {
        $CI->db->select('tpl');
        $CI->db->from('tblMailTypes');
        $CI->db->where('id', $mail_type);
        $query = $CI->db->get();

        $mailIdres = $query->result_array();
        if (!empty($mailIdres)) {
            $message = $mailIdres[0]['tpl'];
            if (!empty($mail_variable)) {
                foreach ($mail_variable as $key => $val) {
                    $message = str_ireplace($key, $val, $message); // select message format from table
                }
            }
        }
    }

    $from = new SendGrid\Email(null, $from);

    $to = new SendGrid\Email(null, $to);

    $content = new SendGrid\Content("text/html", $message);
    exit();

    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $apiKey = 'ABCD..................HHHHFFFRRDSE'; // Sendgrid API key
    $sg = new \SendGrid($apiKey);

   addAttachment($resumePath, $resumeName);

   $response = $sg->client->mail()->send()->post($mail);
}

Anyone please help

Body:
This code working perfectly...

public static function sendEMailwithAttachment($mail_type, $mail_variable = array(), $subject, $from, $mailto,$username, $fileName, $filePath){

       // If you are using Composer (recommended)
require 'vendor/autoload.php';

 // If you are not using Composer
 // require("path/to/sendgrid-php/sendgrid-php.php");

    $CI = & get_instance();

    if ($mail_type !== NULL) {
        $CI->db->select('tpl');
        $CI->db->from('tblMailTypes');
        $CI->db->where('id', $mail_type);
        $query = $CI->db->get();

        $mailIdres = $query->result_array();
        if (!empty($mailIdres)) {
            $message = $mailIdres[0]['tpl'];
            if (!empty($mail_variable)) {
                foreach ($mail_variable as $key => $val) {
                    $message = str_ireplace($key, $val, $message);
                }
            }
        }
    }

 $from = new SendGrid\Email("User", $from);

 $to = new SendGrid\Email($username,$mailto);
 $content = new SendGrid\Content("text/html", $message);
 $file = $filePath;
 $file_encoded = base64_encode(file_get_contents($file));
 $attachment = new SendGrid\Attachment();
 $attachment->setContent($file_encoded);
 $attachment->setType("application/text");
 $attachment->setDisposition("attachment");
 $attachment->setFilename($fileName);

 $mail = new SendGrid\Mail($from, $subject, $to, $content);
 $mail->addAttachment($attachment);

 $apiKey = 'ABCD..................HHHHFFFRRDSE'; // Sendgrid API key

 $sg = new \SendGrid($apiKey);

 $response = $sg->client->mail()->send()->post($mail);

// If you want response

//echo $response->statusCode();
//echo $response->headers();
//echo $response->body();
}


来源: stackexchange

问:
ListView virtualization requires a valid ListViewItem to be provided by the RetrieveVirtualItem event or in the OnRetrieveVirtualItem method
Can someone clear me where I am wrong in this code... I know there is some problem in listView1_RetrieveVirtualItem method but I couldn't correct it. I am getting this error:

ListView virtualization requires a valid ListViewItem to be provided by the RetrieveVirtualItem event or in the OnRetrieveVirtualItem method.

Here is my code:

```<code> public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        _fileInfoCollection = new Queue<ListViewFileInfo>();
    }

    private void GetFileInformation(string drive)
    {
        _fileInfoCollection.Clear();
        var directory = new DirectoryInfo(drive);
        var files = directory.GetFiles("*.*", SearchOption.TopDirectoryOnly);

        foreach (var file in files)
        {
            _fileInfoCollection.Enqueue(new ListViewFileInfo() { FileName = file.Name, FilePath = file.FullName });
        }
    }

    private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
    {
        if (_fileInfoCollection.Count > 0)
        {
            ListViewFileInfo fileInfo = _fileInfoCollection.Dequeue();
            var listViewItem = new ListViewItem();
            listViewItem.Text = fileInfo.FileName;

            var listViewSubItem = new ListViewItem.ListViewSubItem();
            listViewSubItem.Text = fileInfo.FilePath;
            listViewItem.SubItems.Add(listViewSubItem);
            e.Item = listViewItem;
        }
    }

    private void comboBoxDrive_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetFileInformation(comboBoxDrive.Text);
    }

    private Queue<ListViewFileInfo> _fileInfoCollection;

}
</code>```

答:
I have had this issue a few times, and for anyone who is using the ObjectListView  (FastObjectListView) open source library like I am, or is just using a Virtual ListView with a datasource I found that the issue was not with the list or the data itself, it was with the source of the data.

It is hard to diagnose from the error you are given when using a virtual list, but when I changed my FastObjectListView to an ObjectListView (basically removing the virtual functionality) I was able to see the actual error causing the exception and it was that a view that had once existed no longer existed on my entity framework model.

Hope this helps someone as it had me scratching my head and googling the hell out of that useless error message.

ContentLicense: CC BY-SA 3.0

Body:
Can someone clear me where I am wrong in this code... I know there is some problem in listView1_RetrieveVirtualItem method but I couldn't correct it. I am getting this error:

ListView virtualization requires a valid ListViewItem to be provided by the RetrieveVirtualItem event or in the OnRetrieveVirtualItem method.

Here is my code:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        _fileInfoCollection = new Queue<ListViewFileInfo>();
    }

    private void GetFileInformation(string drive)
    {
        _fileInfoCollection.Clear();
        var directory = new DirectoryInfo(drive);
        var files = directory.GetFiles("*.*", SearchOption.TopDirectoryOnly);

        foreach (var file in files)
        {
            _fileInfoCollection.Enqueue(new ListViewFileInfo() { FileName = file.Name, FilePath = file.FullName });
        }
    }

    private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
    {
        if (_fileInfoCollection.Count > 0)
        {
            ListViewFileInfo fileInfo = _fileInfoCollection.Dequeue();
            var listViewItem = new ListViewItem();
            listViewItem.Text = fileInfo.FileName;

            var listViewSubItem = new ListViewItem.ListViewSubItem();
            listViewSubItem.Text = fileInfo.FilePath;
            listViewItem.SubItems.Add(listViewSubItem);
            e.Item = listViewItem;
        }
    }

    private void comboBoxDrive_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetFileInformation(comboBoxDrive.Text);
    }

    private Queue<ListViewFileInfo> _fileInfoCollection;

}


问:
Sorting array of structs (missing Len method)
I have two structs defined as below:

```<code>// DuplicatedAd format
type DuplicatedAd struct {
    // Ad Identifier
    AdID int `form:"ad_id" json:"ad_id,omitempty" xml:"ad_id"`
    // Parameters of an Ad, can be empty
    AdParams string `form:"ad_params" json:"ad_params,omitempty" xml:"ad_params"`
    // Body of the Ad
    Body string `form:"body" json:"body,omitempty" xml:"body"`
    // Body Duplicate Percentage
    BodyScore float64 `form:"body_score" json:"body_score,omitempty" xml:"body_score"`
    // Category of the Ad
    Category int `form:"category" json:"category,omitempty" xml:"category"`
    // The ad uploaded main image
    Image string `form:"image,omitempty" json:"image,omitempty" xml:"image,omitempty"`
    // Ad Listing ID
    ListID int `form:"list_id" json:"list_id,omitempty" xml:"list_id"`
    // Listing time for the ad
    ListTime string `form:"list_time" json:"list_time,omitempty" xml:"list_time"`
    // the ad Phone number
    Phone string `form:"phone,omitempty" json:"phone,omitempty" xml:"phone,omitempty"`
    // Region of the Ad
    Region int `form:"region" json:"region,omitempty" xml:"region"`
    // Ad Status
    Status string `form:"status" json:"status,omitempty" xml:"status"`
    // Subject of the Ad
    Subject string `form:"subject" json:"subject,omitempty" xml:"subject"`
    // Subject Duplicate Percentage
    SubjectScore float64 `form:"subject_score" json:"subject_score,omitempty" xml:"subject_score"`
    // Type of the Ad
    Type string `form:"type" json:"type,omitempty" xml:"type"`
    // Total Score
    TotalScore float64 `form:"total_score" json:"total_score,omitempty" xml:"total_score"`
}

// CpResponse format
type CpResponse struct {
    // Number of doublets
    Count int `json:"count"`
    // The Doublet Ads to show
    Duplicated []DuplicatedAd `json:"duplicated"`
}
</code>```

i'm defining a variable var DuplicatedAds = CpResponse{}and in a loop i'm appending some results to it as follow:

```<code>DuplicatedAds.Duplicated = append(DuplicatedAds.Duplicated, t)
DuplicatedAds.Count = len(DuplicatedAds.Duplicated)
</code>```

i wish that the DuplicatedAds.Duplicated be sorted by TotalScore.

i'm new to golang, so after a little research i found out that i must implement theses three functions before i can sort

```<code>func (slice DuplicatedAd) Len() int {
    return len(slice)
}

func (slice DuplicatedAd) Less(i, j int) bool {
    return slice[i].TotalScore < slice[j].TotalScore
}

func (slice DuplicatedAd) Swap(i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}
</code>```

but when i try to compile i get this errors:

```<code>./duplicates.go:165: cannot use DuplicatedAds.Duplicated (type []DuplicatedAd) as type sort.Interface in argument to sort.Sort:
    []DuplicatedAd does not implement sort.Interface (missing Len method)
./types.go:68: invalid argument slice (type DuplicatedAd) for len
./types.go:72: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:72: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
</code>```

How could i have an CpResponse object which his Duplicated array is sorted by DuplicatedAd.TotalScore ?

答:
Starting from Go 1.8, you can use the following function to sort your slice:

```<code>sort.Slice(DuplicatedAds.Duplicated, func(i int, j int) bool {
    return DuplicatedAds.Duplicated[i].TotalScore < DuplicatedAds.Duplicated[j].TotalScore
})
</code>```

You don't need to define those three functions up there anymore (Len, Less and Swap). Notice how we used the same implementation of Len as a parameter of sort.Slice.

Body:
I have two structs defined as below:

// DuplicatedAd format
type DuplicatedAd struct {
    // Ad Identifier
    AdID int `form:"ad_id" json:"ad_id,omitempty" xml:"ad_id"`
    // Parameters of an Ad, can be empty
    AdParams string `form:"ad_params" json:"ad_params,omitempty" xml:"ad_params"`
    // Body of the Ad
    Body string `form:"body" json:"body,omitempty" xml:"body"`
    // Body Duplicate Percentage
    BodyScore float64 `form:"body_score" json:"body_score,omitempty" xml:"body_score"`
    // Category of the Ad
    Category int `form:"category" json:"category,omitempty" xml:"category"`
    // The ad uploaded main image
    Image string `form:"image,omitempty" json:"image,omitempty" xml:"image,omitempty"`
    // Ad Listing ID
    ListID int `form:"list_id" json:"list_id,omitempty" xml:"list_id"`
    // Listing time for the ad
    ListTime string `form:"list_time" json:"list_time,omitempty" xml:"list_time"`
    // the ad Phone number
    Phone string `form:"phone,omitempty" json:"phone,omitempty" xml:"phone,omitempty"`
    // Region of the Ad
    Region int `form:"region" json:"region,omitempty" xml:"region"`
    // Ad Status
    Status string `form:"status" json:"status,omitempty" xml:"status"`
    // Subject of the Ad
    Subject string `form:"subject" json:"subject,omitempty" xml:"subject"`
    // Subject Duplicate Percentage
    SubjectScore float64 `form:"subject_score" json:"subject_score,omitempty" xml:"subject_score"`
    // Type of the Ad
    Type string `form:"type" json:"type,omitempty" xml:"type"`
    // Total Score
    TotalScore float64 `form:"total_score" json:"total_score,omitempty" xml:"total_score"`
}

// CpResponse format
type CpResponse struct {
    // Number of doublets
    Count int `json:"count"`
    // The Doublet Ads to show
    Duplicated []DuplicatedAd `json:"duplicated"`
}

i'm defining a variable var DuplicatedAds = CpResponse{}and in a loop i'm appending some results to it as follow:

DuplicatedAds.Duplicated = append(DuplicatedAds.Duplicated, t)
DuplicatedAds.Count = len(DuplicatedAds.Duplicated)

i wish that the DuplicatedAds.Duplicated be sorted by TotalScore.

i'm new to golang, so after a little research i found out that i must implement theses three functions before i can sort

func (slice DuplicatedAd) Len() int {
    return len(slice)
}

func (slice DuplicatedAd) Less(i, j int) bool {
    return slice[i].TotalScore < slice[j].TotalScore
}

func (slice DuplicatedAd) Swap(i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}

but when i try to compile i get this errors:

./duplicates.go:165: cannot use DuplicatedAds.Duplicated (type []DuplicatedAd) as type sort.Interface in argument to sort.Sort:
    []DuplicatedAd does not implement sort.Interface (missing Len method)
./types.go:68: invalid argument slice (type DuplicatedAd) for len
./types.go:72: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:72: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)

How could i have an CpResponse object which his Duplicated array is sorted by DuplicatedAd.TotalScore ?

Body:
Starting from Go 1.8, you can use the following function to sort your slice:

sort.Slice(DuplicatedAds.Duplicated, func(i int, j int) bool {
    return DuplicatedAds.Duplicated[i].TotalScore < DuplicatedAds.Duplicated[j].TotalScore
})

You don't need to define those three functions up there anymore (Len, Less and Swap). Notice how we used the same implementation of Len as a parameter of sort.Slice.


问:
Is it a good idea to use HP Quality Center for Continuous Integration?
We need to compile our code after check - ins, be notified if compile fails, run tests, be notified of test results and publish our application (publish a website or create an msi file for a desktop app) on a daily basis.

We are using SVN and were considering using TeamCity or CruiseControl.NET for continuous integration server for our .net projects which have msunit tests.

My project manager came up with HP Quality Center and Quick Test Professional (it is already purchased) and suggested using them for issue tracking (currently we are using Jira) and continuous integration.

Does it make sense?

答: Not a good idea, I've done a POC for QC and Borland tools (for HP), and although possible, there are too many area where the synchronization has to be perfect, and the slow response time of QC sometime due to network etc to trigger right file, get result of compilation and publish is a bit shaky. Again technically via API it is completely feasible.</p>

OwnerDisplayName: buyutec

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Motti


问:
angular2 with restful service

I am trying RESTful service with my Angular2 application.
It is working when I give local json url (/app/config.json). But it is not working when I try with below url.

URL : http://localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get

The above url will return json value as below,

{
  "title": "SingerName",
  "singer": "Singer123",
  "id": "1",
  "name": "Hero123"
}
```

<p><strong>app.module</strong></p>

<pre class="lang-ts prettyprint-override"><code>@NgModule({
  declarations: [  AppComponent,HeroListComponent,HeroDetailComponent],
  imports: [BrowserModule,HttpModule,routing],  bootstrap: [AppComponent]
})
</code>```

HeroService.ts

getHeroes(){
  var headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this._http.request("localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/…) .map((res:Response) => res.json());
}
```

<p><strong>HeroListComponent</strong></p>

<pre class="lang-ts prettyprint-override"><code>@Component({
   selector: 'my-hero-detail',
   template: `
      <h2>Hero List Component</h2>
      <ul *ngFor="let hero of heroes">
         {{hero}}
        <li>{{hero.id}}</li>
        <li>{{hero.name}}</li>
     </ul>`
})
export class HeroListComponent implements  OnInit {
  heroes = [];

  constructor(private _heroService:HeroService) {}

  ngOnInit(){
    this._heroService.getHeroes().
       .subscribe(response =>this.heroes = response);
      }
  }
</code>```

答:
as echonax said don't use relative paths and  set header like this :</p>

```<code>let options = new RequestOptions({ headers: headers });

return this._http.get("/assets/herolist.json", options ).map((res:Response) => res.json());
</code>```

Title: angular2 with restful service

Body:
I am trying RESTful service with my Angular2 application.
It is working when I give local json url (/app/config.json). But it is not working when I try with below url.

URL : http://localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get

The above url will return json value as below,

{
  "title": "SingerName",
  "singer": "Singer123",
  "id": "1",
  "name": "Hero123"
}

app.module

@NgModule({
  declarations: [  AppComponent,HeroListComponent,HeroDetailComponent],
  imports: [BrowserModule,HttpModule,routing],  bootstrap: [AppComponent]
})

HeroService.ts

getHeroes(){
  var headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this._http.request("localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/…) .map((res:Response) => res.json());
}

HeroListComponent

@Component({
   selector: 'my-hero-detail',
   template: `

Hero List Component

         {{hero}}

{{hero.id}}

{{hero.name}}

`
})
export class HeroListComponent implements  OnInit {
  heroes = [];

  constructor(private _heroService:HeroService) {}

  ngOnInit(){
    this._heroService.getHeroes().
       .subscribe(response =>this.heroes = response);
      }
  }

Body:
as echonax said don't use relative paths and  set header like this :

let options = new RequestOptions({ headers: headers });

return this._http.get("/assets/herolist.json", options ).map((res:Response) => res.json());


问:
Simple click event not working in JS
I have created a very simple fiddle in JsFiddle. To my surprise it is not working. Please let me know if I am mistaking anything.

HTML-

```<code><button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>
</code>```

JS-

```<code>function test1(){
    alert("1");
}
</code>```

I want to show a simple alert on button click but it is not showing up.

Please click here to see this simple fiddle.

答:
If you take a look at your browsers web console you can see an Uncaught ReferenceError is thrown. It tells you that function test1 is not defined.

In this answer the same error is discussed.
The problem is, that the javascript file is linked into the html header and called before the html code is initialized.
The answer suggest to use jquery and its corresponding ready function.

If you want to do plain javascript you can solve this issue by directly embedding your code into your html using a script tag.

Take a look at the following snippet.

<button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>
```

Title: Simple click event not working in JS

Body:
I have created a very simple fiddle in JsFiddle. To my surprise it is not working. Please let me know if I am mistaking anything.

HTML-

<button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>

JS-

function test1(){
    alert("1");
}

I want to show a simple alert on button click but it is not showing up.

Please click here to see this simple fiddle.

Body:
If you take a look at your browsers web console you can see an Uncaught ReferenceError is thrown. It tells you that function test1 is not defined.

In this answer the same error is discussed.
The problem is, that the javascript file is linked into the html header and called before the html code is initialized.
The answer suggest to use jquery and its corresponding ready function.

If you want to do plain javascript you can solve this issue by directly embedding your code into your html using a script tag.

Take a look at the following snippet.

<button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>
<script>
function test1(){
 alert("1");
}
</script>


问:
Link Not redirecting
I have a navbar and the links are not working in it..
But when i go to the source code(cntrl+u) and then click on the link it redirects me properly.
Also when i remove the "class="menu__link"" it works well but does not provide me with the required css.

```<code><section class="section section--menu" id="Valentine">
    <nav class="menu menu--valentine" style="position: fixed; top: 0px; right: 10px; width: 100%; float: right; background-color: black">
      <ul class="menu__list">
        <li class="menu__item menu__item--current"><a href="#" class="menu__link">Home</a></li>
        <li class="menu__item"><a href="{% url 'speakers' %}" class="menu__link">Speakers</a></li>
        <li class="menu__item"><a href="{% url 'partners' %}" class="menu__link">Partners</a></li>
        <li class="menu__item"><a href="#" class="menu__link">Blog</a></li>
        <li class="menu__item"><a href="#contact" class="menu__link">Contact</a></li>
      </ul>
    </nav>
  </section>
</code>```

Here's my css for the menu.

```<code>.section--menu {
 position: relative;
 overflow: ;
 }

.menu {
line-height: 1;
margin: 0 auto 3em;
}
.menu__list {
position: relative;
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
margin: 0;
padding: 0;
float: right;
list-style: none;
}

.menu__item {
display: block;
margin: 1em 0;
}

.menu__link {
font-size: 1.05em;
font-weight: bold;
display: block;
padding: 1em;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
 }

.menu__link:hover,
.menu__link:focus {
outline: none;
}

/* Valentine */
.menu--valentine .menu__item {
position: relative;
margin: 0 1em;
}

.menu--valentine .menu__link {
position: relative;
display: block;
min-width: 105px;
text-align: center;
color: #b5b5b5;
-webkit-transition: color 0.3s;
transition: color 0.3s;
}

.menu--valentine .menu__link:hover,
.menu--valentine .menu__link:focus {
color: #e62b1e;
}

.menu--valentine .menu__item--current .menu__link {
color: #e62b1e;
}

.menu--valentine .menu__item::before,
.menu--valentine .menu__item::after,
.menu--valentine .menu__link::before,
.menu--valentine .menu__link::after {
content: '';
position: absolute;
background: #e62b1e;
-webkit-transform-origin: 350% 350%;
transform-origin: 350% 350%;
-webkit-transition: -webkit-transform 0.5s;
transition: transform 0.5s;
-webkit-transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
}

.menu--valentine .menu__item::before,
.menu--valentine .menu__item::after {
top: 0;
width: 2px;
height: 100%;
-webkit-transform: scale3d(1, 0, 1);
transform: scale3d(1, 0, 1);
}

/* left line */
.menu--valentine .menu__item::before {
left: 0;
-webkit-transition-delay: 0.05s;
transition-delay: 0.05s;
}

/* right line */
.menu--valentine .menu__item::after {
right: 0;
-webkit-transition-delay: 0.15s;
transition-delay: 0.15s;
}

.menu--valentine .menu__link::before,
.menu--valentine .menu__link::after {
left: 0;
width: 100%;
height: 2px;
-webkit-transform: scale3d(0, 1, 1);
transform: scale3d(0, 1, 1);
}

/* top line */
.menu--valentine .menu__link::before {
top: 0;
-webkit-transition-delay: 0.1s;
transition-delay: 0.1s;
}

/* bottom line */
.menu--valentine .menu__link::after {
 bottom: 0;
 }

 .menu--valentine .menu__item--current::before,
 .menu--valentine .menu__item--current::after,
 .menu--valentine .menu__item--current .menu__link::before,
 .menu--valentine .menu__item--current .menu__link::after {
 -webkit-transform: scale3d(1, 1, 1);
 transform: scale3d(1, 1, 1);
 }
</code>```

The JS for the Template is:

```<code><script>
(function() {
  [].slice.call(document.querySelectorAll('.menu')).forEach(function(menu) {
    var menuItems = menu.querySelectorAll('.menu__link'),
      setCurrent = function(ev) {
        ev.preventDefault();

        var item = ev.target.parentNode; // li

        // return if already current
        if (classie.has(item, 'menu__item--current')) {
          return false;
        }
        // remove current
        classie.remove(menu.querySelector('.menu__item--current'), 'menu__item--current');
        // set current
        classie.add(item, 'menu__item--current');
      };

    [].slice.call(menuItems).forEach(function(el) {
      el.addEventListener('click', setCurrent);
    });
  });

  [].slice.call(document.querySelectorAll('.link-copy')).forEach(function(link) {
    link.setAttribute('data-clipboard-text', location.protocol + '//' + location.host + location.pathname + '#' + link.parentNode.id);
    new Clipboard(link);
    link.addEventListener('click', function() {
      classie.add(link, 'link-copy--animate');
      setTimeout(function() {
        classie.remove(link, 'link-copy--animate');
      }, 300);
    });
  });
})(window);
</code>```

When the javascript is removed, the links work but again the transition is lost.
Thanks in advance.

答:
remove this css user-select

```<code>.menu__link {
font-size: 1.05em;
font-weight: bold;
display: block;
padding: 1em;
cursor: pointer;
/*-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;*/
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
 }
</code>```

Title: Link Not redirecting

Body:
I have a navbar and the links are not working in it..
But when i go to the source code(cntrl+u) and then click on the link it redirects me properly.
Also when i remove the "class="menu__link"" it works well but does not provide me with the required css.

Home

Speakers

Partners

Blog

Contact

Here's my css for the menu.

.section--menu {
 position: relative;
 overflow: ;
 }

.menu {
line-height: 1;
margin: 0 auto 3em;
}
.menu__list {
position: relative;
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
margin: 0;
padding: 0;
float: right;
list-style: none;
}

.menu__item {
display: block;
margin: 1em 0;
}

.menu__link {
font-size: 1.05em;
font-weight: bold;
display: block;
padding: 1em;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
 }

.menu__link:hover,
.menu__link:focus {
outline: none;
}

/* Valentine */
.menu--valentine .menu__item {
position: relative;
margin: 0 1em;
}

.menu--valentine .menu__link {
position: relative;
display: block;
min-width: 105px;
text-align: center;
color: #b5b5b5;
-webkit-transition: color 0.3s;
transition: color 0.3s;
}

.menu--valentine .menu__link:hover,
.menu--valentine .menu__link:focus {
color: #e62b1e;
}

.menu--valentine .menu__item--current .menu__link {
color: #e62b1e;
}

.menu--valentine .menu__item::before,
.menu--valentine .menu__item::after,
.menu--valentine .menu__link::before,
.menu--valentine .menu__link::after {
content: '';
position: absolute;
background: #e62b1e;
-webkit-transform-origin: 350% 350%;
transform-origin: 350% 350%;
-webkit-transition: -webkit-transform 0.5s;
transition: transform 0.5s;
-webkit-transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
}

.menu--valentine .menu__item::before,
.menu--valentine .menu__item::after {
top: 0;
width: 2px;
height: 100%;
-webkit-transform: scale3d(1, 0, 1);
transform: scale3d(1, 0, 1);
}

/* left line */
.menu--valentine .menu__item::before {
left: 0;
-webkit-transition-delay: 0.05s;
transition-delay: 0.05s;
}

/* right line */
.menu--valentine .menu__item::after {
right: 0;
-webkit-transition-delay: 0.15s;
transition-delay: 0.15s;
}

.menu--valentine .menu__link::before,
.menu--valentine .menu__link::after {
left: 0;
width: 100%;
height: 2px;
-webkit-transform: scale3d(0, 1, 1);
transform: scale3d(0, 1, 1);
}

/* top line */
.menu--valentine .menu__link::before {
top: 0;
-webkit-transition-delay: 0.1s;
transition-delay: 0.1s;
}

/* bottom line */
.menu--valentine .menu__link::after {
 bottom: 0;
 }

 .menu--valentine .menu__item--current::before,
 .menu--valentine .menu__item--current::after,
 .menu--valentine .menu__item--current .menu__link::before,
 .menu--valentine .menu__item--current .menu__link::after {
 -webkit-transform: scale3d(1, 1, 1);
 transform: scale3d(1, 1, 1);
 }

The JS for the Template is:

Body:
remove this css user-select

.menu__link {
font-size: 1.05em;
font-weight: bold;
display: block;
padding: 1em;
cursor: pointer;
/*-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;*/
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
 }


答: You can use _.maxBy from lodash, (max and maxBy)it compares date type without the need of transfor them with .getTime().</p>

Title: Nested _.max() with lodash

Body:
I am trying to get max and min values of arrays values inside objects array which looks like this:

[
    {
        id: 1,
        enabled: false,
        layer: 'Mood',
        color: '#f16c63',
        points: [
            {date: '2013-01-02', value: 20},
            {date: '2013-02-02', value: 15},
            {date: '2013-03-12', value: 24},
            {date: '2013-03-23', value: 18},
            {date: '2013-03-24', value: 22},
            {date: '2013-04-09', value: 12},
            {date: '2013-06-13', value: 16},
            {date: '2013-06-14', value: 20},
        ]
    },
    {
        id: 2,
        enabled: true,
        layer: 'Performance',
        color: '#698bfc',
        points: [
            {date: '2013-01-02', value: 15},
            {date: '2013-02-02', value: 24},
            {date: '2013-03-12', value: 29},
            {date: '2013-03-23', value: 21},
            {date: '2013-03-24', value: 20},
            {date: '2013-04-09', value: 17},
            {date: '2013-06-13', value: 25},
            {date: '2013-06-14', value: 21},
        ]
    },
    {
        id: 3,
        enabled: false,
        layer: 'Fatigue',
        color: '#e1fc6a',
        points: [
            {date: '2013-01-02', value: 32},
            {date: '2013-02-02', value: 27},
            {date: '2013-03-12', value: 30},
            {date: '2013-03-23', value: 31},
            {date: '2013-03-24', value: 27},
            {date: '2013-04-09', value: 15},
            {date: '2013-06-13', value: 20},
            {date: '2013-06-14', value: 18},
        ]
    },
    {
        id: 4,
        enabled: true,
        layer: 'Hunger',
        color: '#63adf1',
        points: [
            {date: '2013-01-02', value: 12},
            {date: '2013-02-02', value: 15},
            {date: '2013-03-12', value: 13},
            {date: '2013-03-23', value: 17},
            {date: '2013-03-24', value: 10},
            {date: '2013-04-09', value: 14},
            {date: '2013-06-13', value: 12},
            {date: '2013-06-14', value: 11},
        ]
    },
]

I need to get the max and the min values from the points arrays.
Seems like I can do something like this for max and similar for min values:

                   var maxDate = _.max(dataset, function (area) {
                   return _.max(area.points, function (point) {
                       console.log(new Date(point.date).getTime())
                       return new Date(point.date).getTime()
                   })

               });

But for some reason this returns me -Infinity. Is it legit at all to use nested _.max() runs? I used this approach with D3.js library which worked just fine.

Please advise.


问:
Tokenize by using regular expressions (parenthesis)
I have the following text:

I don't like to eat Cici's food (it is true)

I need to tokenize it to

['i', 'don't', 'like', 'to', 'eat', 'Cici's', 'food', '(', 'it', 'is', 'true', ')']

I have found out that the following regex expression (['()\w]+|\.) splits like this:

['i', 'don't', 'like', 'to', 'eat', 'Cici's', 'food', '(it', 'is', 'true)']

How do I take the parenthesis out of the token and make it to an own token?

Thanks for ideas.

答:
You should separate singular char tokens (the brackets in this particular case) from the chars which represent a token in series:

```<code>([().]|['\w]+)
</code>```

Demo: https://regex101.com/r/RQfYhL/2

ContentLicense: CC BY-SA 4.0

Body:
You should separate singular char tokens (the brackets in this particular case) from the chars which represent a token in series:

([().]|['\w]+)

Demo: https://regex101.com/r/RQfYhL/2


问:
img width relative to containing div

Original Question

What is the most efficient way to calculate the width of an image relative to it's containing div in css?

I have the following snippet which sets #image1.width to a percentage that is relative to the width of its parent. I'm using a percentage because I need the image to scale proportionately to the parent when the screen is resized.

div {
  position: relative;
  display: block;
  width: 100%;
}

#image1 {
  position: absolute;
  left: 10%;
  top: 10%;
  width: 29.43%;
  height: auto;
}

#under {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img id="image1" src="http://placehold.it/206x115">
  <img id="under" src="http://placehold.it/700x300/ff00f0/ffffff">
</div></code>```

It is currently working as intended, except that I have to manually calculate the width percentage for every single image. i.e.

```<code>#image1 dimensions == 206x115
#under dimensions == 700x300
new #image1.width % == #image1.width / #under.width == 206/700 == ~29.43%
</code>```

What I want to know is if there id a calc() method or similar I can implement to ease/streamline this process?

I was going to use width: calc(100% / 700) however this obviously will not work when the screen size changes.

Goals

To re-iterate, it is imperative that the #under image scales with the screen size and the #image remains proportionate.

I want the natural image ratios preserved with one another (i.e. an image that is one quarter the size of the other will remain as such at all browser widths).

Note: The html can be reconfigured in any way to achieve this.

Target browsers: Chrome, Firefox, Edge.

Post Bounty Review

Comment on @Obsidian Age's answer (end of first bounty 31.03.17):

Unfortunately @Obsidian Age's answer is not correct - it is close but not quite and I just wanted to clarify this here... Below is a snippet from his answer... Note that I think it is a good answer, just clarifying why it has not been accepted:

```<code>:root {
  --width: 90vw; // Must be viewport-driven
}

#image1 {
  width: calc(var(--width) / 3); // The 3 can be replaced with any float
}
</code>```

Setting --width: 90vw what happens if body or div have a max-width set? This is also very hard to calculate for all devices when factoring in viewport-scaling.

#image1 { width:calc(var(--width) / 3); } This equates to calc(90vw / 3) which is 30vw which would equate to 30% of the images width. But how do we work out the number to divide by? Well it's back to where we started...  width:calc(var(--width) * calc(206/700*100)); And this is why I have not accepted this answer.

答:
One thing that might work, if you are willing to use bootstrap (https://getbootstrap.com/examples/grid/):

```<code><!-- parent -->
<div class="row">
  <div class="col-md-6">
    <img src="">
    <!-- this is 50% of the screen for min 992px, a full line otherwise -->
  </div>
  <div class="col-md-3">
    <img src="">
    <!-- this is 25% of the screen for min 992px, a full line otherwise-->
  </div>

  <div class=col-md-3>
    <img src="">
    <!-- this is 25% of the screen for min 992px, a full line otherwise -->
  </div>
</div>
</code>```

You can group these as you want/need, just remember that the numbers have to add to 12 (in my example, 6+3+3). You can achieve a 100% width effect using col-md-12. Also, the md infix is just one of several options of cutoff between putting everything on the same line and stacking elements. You can check out http://getbootstrap.com/css/#grid for more details, as well as a couple of examples.

Title: img width relative to containing div

Body:
Original Question

What is the most efficient way to calculate the width of an image relative to it's containing div in css?

I have the following snippet which sets #image1.width to a percentage that is relative to the width of its parent. I'm using a percentage because I need the image to scale proportionately to the parent when the screen is resized.

div {
  position: relative;
  display: block;
  width: 100%;
}

#image1 {
  position: absolute;
  left: 10%;
  top: 10%;
  width: 29.43%;
  height: auto;
}

#under {
  width: 100%;
}

It is currently working as intended, except that I have to manually calculate the width percentage for every single image. i.e.

#image1 dimensions == 206x115
#under dimensions == 700x300
new #image1.width % == #image1.width / #under.width == 206/700 == ~29.43%

What I want to know is if there id a calc() method or similar I can implement to ease/streamline this process?

I was going to use width: calc(100% / 700) however this obviously will not work when the screen size changes.

Goals

To re-iterate, it is imperative that the #under image scales with the screen size and the #image remains proportionate.

I want the natural image ratios preserved with one another (i.e. an image that is one quarter the size of the other will remain as such at all browser widths).

Note: The html can be reconfigured in any way to achieve this.

Target browsers: Chrome, Firefox, Edge.

Post Bounty Review

Comment on @Obsidian Age's answer (end of first bounty 31.03.17):

Unfortunately @Obsidian Age's answer is not correct - it is close but not quite and I just wanted to clarify this here... Below is a snippet from his answer... Note that I think it is a good answer, just clarifying why it has not been accepted:

:root {
  --width: 90vw; // Must be viewport-driven
}

#image1 {
  width: calc(var(--width) / 3); // The 3 can be replaced with any float
}

Setting --width: 90vw what happens if body or div have a max-width set? This is also very hard to calculate for all devices when factoring in viewport-scaling.

#image1 { width:calc(var(--width) / 3); } This equates to calc(90vw / 3) which is 30vw which would equate to 30% of the images width. But how do we work out the number to divide by? Well it's back to where we started...  width:calc(var(--width) * calc(206/700*100)); And this is why I have not accepted this answer.

Body:
One thing that might work, if you are willing to use bootstrap (https://getbootstrap.com/examples/grid/):

<!-- parent -->
<div class="row">
  <div class="col-md-6">
    <img src="">
    <!-- this is 50% of the screen for min 992px, a full line otherwise -->
  </div>
  <div class="col-md-3">
    <img src="">
    <!-- this is 25% of the screen for min 992px, a full line otherwise-->
  </div>

  <div class=col-md-3>
    <img src="">
    <!-- this is 25% of the screen for min 992px, a full line otherwise -->
  </div>
</div>

You can group these as you want/need, just remember that the numbers have to add to 12 (in my example, 6+3+3). You can achieve a 100% width effect using col-md-12. Also, the md infix is just one of several options of cutoff between putting everything on the same line and stacking elements. You can check out http://getbootstrap.com/css/#grid for more details, as well as a couple of examples.


问:
Unable to build to iPad after renewing provisioning profile
I recently renewed a provisioning profile for an iPad app I am working on and now I am unable to build the app to the iPad.

First I renewed the profile in ADC, downloaded it and then dragged it to xCode. I then deleted the expired profile. Now when I attempt to build I get "Error from Debugger: The program being debugged is not being run." and I can't figure out why.

The app was working fine before I had to renew the profile. Also, I have already deleted completely from the iPad and tried to rebuild.

答: If i run into that, i usually do a clean build, try again, restart my iPad, try again, and then restart my mac, and try again. so far it has always started working again at one stage or another during this process.</p>


问:
fopen php positional file line
I have a problem reading a .ret or .txt file while using the function below it deletes line space from the file. Except that this file is positional I will do a routine to search for information based on your positioning.

```<code>$ponteiro = fopen('arquivoretorno\retorno.ret','rb');
//$vetor = array();
while (!feof($ponteiro)) {

        $linha = fgets($ponteiro,9999);

        $tipo_registro = substr($linha, 7, 1);
        echo $linha;
        //echo $tipo_registro;
        die();
        IF ($tipo_registro == 0) {
          $codbanco = substr($linha, 1, 3); //Código do Banco na Compensação: "085"
          $lote = substr($linha, 4, 4); //Lote de Serviço: "0000"
          $inpessoa = substr($linha, 18, 1); //Tipo de Inscrição da Empresa
          $nmcnpjcpf = substr($linha, 19, 14); //Número de Inscrição da Empresa
          $nmconvenio = substr($linha, 33, 20); //Código do Convênio na Cooperativa
          $agencia = substr($linha, 53, 5); //Agência da sede da Cooperativa
          $div_agencia = substr($linha, 58, 1); //Dígito Verificador da Agência
          $numcontacorrente = substr($linha, 59, 12); //Número da Conta Corrente
          $dv_contacorrente = substr($linha, 71, 1); //Dígito Verificador da Conta
          $codremessa = substr($linha, 143, 1); //Código Remessa / Retorno
          } ElseIf ($tipo_registro == 3) {
             $segmento = substr($linha, 14, 1);    //Cód. Segmento do Registro Detalhe

             If ($segmento == 'T') {
              $vlnumbol = substr($linha, 38, 20);  //Identificação do Título
              $inpessoacliente = substr($linha, 133, 1);   //Tipo de Inscrição
              $nmcnpjcpfcliente = substr($linha, 134, 15); //Número de Inscrição
              $vltitoriginal = number_format(substr($linha, 82, 15),2,',','.') ; //Valor do Título
             } ElseIf ($tipo_registro == 'U' ) {

            }
          }

}
fclose ($ponteiro);
</code>```

enter image description here

Thanks

答:
Use <code>```</code> tag for printing the data. Something like this:</p>

```<code> echo "```";
 echo $linha;
 echo "```";
</code>```

<p>OR</p>

```<code>$linha = str_replace(' ', ' ', $linha);
echo $linda;
</code>```

Title: fopen php positional file line

Body:
I have a problem reading a .ret or .txt file while using the function below it deletes line space from the file. Except that this file is positional I will do a routine to search for information based on your positioning.

$ponteiro = fopen('arquivoretorno\retorno.ret','rb');
//$vetor = array();
while (!feof($ponteiro)) {

        $linha = fgets($ponteiro,9999);

        $tipo_registro = substr($linha, 7, 1);
        echo $linha;
        //echo $tipo_registro;
        die();
        IF ($tipo_registro == 0) {
          $codbanco = substr($linha, 1, 3); //Código do Banco na Compensação: "085"
          $lote = substr($linha, 4, 4); //Lote de Serviço: "0000"
          $inpessoa = substr($linha, 18, 1); //Tipo de Inscrição da Empresa
          $nmcnpjcpf = substr($linha, 19, 14); //Número de Inscrição da Empresa
          $nmconvenio = substr($linha, 33, 20); //Código do Convênio na Cooperativa
          $agencia = substr($linha, 53, 5); //Agência da sede da Cooperativa
          $div_agencia = substr($linha, 58, 1); //Dígito Verificador da Agência
          $numcontacorrente = substr($linha, 59, 12); //Número da Conta Corrente
          $dv_contacorrente = substr($linha, 71, 1); //Dígito Verificador da Conta
          $codremessa = substr($linha, 143, 1); //Código Remessa / Retorno
          } ElseIf ($tipo_registro == 3) {
             $segmento = substr($linha, 14, 1);    //Cód. Segmento do Registro Detalhe

             If ($segmento == 'T') {
              $vlnumbol = substr($linha, 38, 20);  //Identificação do Título
              $inpessoacliente = substr($linha, 133, 1);   //Tipo de Inscrição
              $nmcnpjcpfcliente = substr($linha, 134, 15); //Número de Inscrição
              $vltitoriginal = number_format(substr($linha, 82, 15),2,',','.') ; //Valor do Título
             } ElseIf ($tipo_registro == 'U' ) {

            }
          }

}
fclose ($ponteiro);

enter image description here

Thanks

Body:
Use <pre> tag for printing the data. Something like this:

 echo "<pre>";
 echo $linha;
 echo "</pre>";

OR

$linha = str_replace(' ', '&nbsp;', $linha);
echo $linda;


问:
(PYTHON) How to get sub elements (Selenium)
so I'm really new to python and I wanna get my number of friends I got on a site named roblox for the sake of learning. This is where my code is right now:

```<code> from selenium import webdriver
 ff = webdriver.FireFox()
 ff.get("https://www.roblox.com/home")
 element = driver.find_element_by_class("col-xs-12 section home-friends"[0])
</code>```

where I am currently

I want to get the text "Friends (2)"

any ways of doing that?

答:
You cannot use compound class names with find_element_by_class_name() (not just ..by_class() but ..by_class_name() ! ), but you still can use it in CSS selector, like

```<code>ff.find_element_by_css_selector(".col-xs-12.section.home-friends")`
</code>```

If you need to exctract "Friends (2)", try:

```<code>elem_text = ff.find_element_by_css_selector("div.col-xs-12.section.home-friends h3").text
</code>```

Body:
so I'm really new to python and I wanna get my number of friends I got on a site named roblox for the sake of learning. This is where my code is right now:

 from selenium import webdriver
 ff = webdriver.FireFox()
 ff.get("https://www.roblox.com/home")
 element = driver.find_element_by_class("col-xs-12 section home-friends"[0])

where I am currently

I want to get the text "Friends (2)"

any ways of doing that?

Body:
You cannot use compound class names with find_element_by_class_name() (not just ..by_class() but ..by_class_name() ! ), but you still can use it in CSS selector, like

ff.find_element_by_css_selector(".col-xs-12.section.home-friends")`

If you need to exctract "Friends (2)", try:

elem_text = ff.find_element_by_css_selector("div.col-xs-12.section.home-friends h3").text


问:
iOS Location Updates not trigerred consistently in background mode
Requirement:
To Trigger Location update Callback after every second when the app is in background.

Problem:
Location Callbacks are not triggered after every second. Instead we get them inconsistently sometimes after 1 second, sometimes after 4 second and even with gap of 40-50 seconds.

Current Implementation:

```<code>setActivityType = CLActivityTypeOther
setAllowsBackgroundLocationUpdates = YES
setDesiredAccuracy = kCLLocationAccuracyBestForNavigation
setDistanceFilter = kCLDistanceFilterNone
setPausesLocationUpdatesAutomatically = false
</code>```

plist configuration also done for background location updates.

Please suggest what more can be done to achieve solution for this problem?

答:
Try out below code for background location updation when a significant location change is occured:</p>

```<code>#pragma mark - CLLocationManager

- (void)startContinuosLocationUpdate
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.anotherLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.anotherLocationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.anotherLocationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.anotherLocationManager startUpdatingLocation];
    }
}

- (void)stopContinuosLocationUpdate
{
    [self.anotherLocationManager stopUpdatingLocation];
}

- (void)startMonitoringLocation
{
    if (_anotherLocationManager)
        [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    self.anotherLocationManager = [[CLLocationManager alloc]init];
    _anotherLocationManager.delegate = self;
    _anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    _anotherLocationManager.activityType = CLActivityTypeOtherNavigation;

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        [_anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
    }
    else if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}

- (void)restartMonitoringLocation
{
    [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        [_anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
    }
    else if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}
</code>```

Body:
Requirement:
To Trigger Location update Callback after every second when the app is in background.

Problem:
Location Callbacks are not triggered after every second. Instead we get them inconsistently sometimes after 1 second, sometimes after 4 second and even with gap of 40-50 seconds.

Current Implementation:

setActivityType = CLActivityTypeOther
setAllowsBackgroundLocationUpdates = YES
setDesiredAccuracy = kCLLocationAccuracyBestForNavigation
setDistanceFilter = kCLDistanceFilterNone
setPausesLocationUpdatesAutomatically = false

plist configuration also done for background location updates.

Please suggest what more can be done to achieve solution for this problem?

Body:
Try out below code for background location updation when a significant location change is occured:

#pragma mark - CLLocationManager

- (void)startContinuosLocationUpdate
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.anotherLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.anotherLocationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.anotherLocationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.anotherLocationManager startUpdatingLocation];
    }
}

- (void)stopContinuosLocationUpdate
{
    [self.anotherLocationManager stopUpdatingLocation];
}

- (void)startMonitoringLocation
{
    if (_anotherLocationManager)
        [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    self.anotherLocationManager = [[CLLocationManager alloc]init];
    _anotherLocationManager.delegate = self;
    _anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    _anotherLocationManager.activityType = CLActivityTypeOtherNavigation;

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        [_anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
    }
    else if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}

- (void)restartMonitoringLocation
{
    [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        [_anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
    }
    else if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}


问:
BDD behave Python need to create a World map to hold values
I'm not too familiar with Python but I have setup a BDD framework using Python behave, I now want to create a World map class that holds data and is retrievable throughout all scenarios.

For instance I will have a world class where I can use:

```<code>World w

w.key.add('key', api.response)
</code>```

In one scenario and in another I can then use:

```<code>World w

key = w.key.get('key').
</code>```

Edit:

Or if there is a built in way of using context or similar in behave where the attributes are saved and retrievable throughout all scenarios that would be good.

Like lettuce where you can use world http://lettuce.it/tutorial/simple.html

I've tried this between scenarios but it doesn't seem to be picking it up

```<code>class World(dict):
    def __setitem__(self, key, item):
        self.__dict__[key] = item
        print(item)

    def __getitem__(self, key):
        return self.__dict__[key]
</code>```

Setting the item in one step in scenario A: w.setitem('key', response)

Getting the item in another step in scenario B: w.getitem('key',)

This shows me an error though:

```<code>Traceback (most recent call last):
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1456, in run
    match.run(runner.context)
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1903, in run
    self.func(context, *args, **kwargs)
  File "steps\get_account.py", line 14, in step_impl
    print(w.__getitem__('appToken'))
  File "C:Project\steps\world.py", line 8, in __getitem__
    return self.__dict__[key]
KeyError: 'key'
</code>```

It appears that the World does not hold values here between steps that are run.

Edit:

I'm unsure how to use environment.py but can see it has a way of running code before the steps. How can I allow my call to a soap client within environment.py to be called and then pass this to a particular step?

Edit:

I have made the request in environment.py and hardcoded the values, how can I pass variables to environment.py and back?

答:
Have you tried the
simple approach, using global var, for instance:

```<code>def before_all(context):
    global response
    response = api.response

def before_scenario(context, scenario):
    global response
    w.key.add('key', response)
</code>```

Guess feature can be accessed from context, for instance:

```<code>def before_feature(context, feature):
    feature.response = api.response

def before_scenario(context, scenario):
    w.key.add('key', context.feature.response)
</code>```

You are looking for:

Class variable: A variable that is shared by all instances of a class.

Your code in Q uses Class Instance variable.

Read about: python_classes_objects

For instance:

```<code>class World(dict):
    __class_var = {}

    def __setitem__(self, key, item):
        World.__class_var[key] = item

    def __getitem__(self, key):
        return World.__class_var[key]

# Scenario A
A = World()
A['key'] = 'test'
print('A[\'key\']=%s' % A['key'] )
del A

# Scenario B
B = World()
print('B[\'key\']=%s' % B['key'] )
</code>```

Output:

```<code>A['key']=test
B['key']=test
</code>```

Tested with Python:3.4.2

Come back and Flag your Question as answered if this is working for you or comment why not.

Body:
I'm not too familiar with Python but I have setup a BDD framework using Python behave, I now want to create a World map class that holds data and is retrievable throughout all scenarios.

For instance I will have a world class where I can use:

World w

w.key.add('key', api.response)

In one scenario and in another I can then use:

World w

key = w.key.get('key').

Edit:

Or if there is a built in way of using context or similar in behave where the attributes are saved and retrievable throughout all scenarios that would be good.

Like lettuce where you can use world http://lettuce.it/tutorial/simple.html

I've tried this between scenarios but it doesn't seem to be picking it up

class World(dict):
    def __setitem__(self, key, item):
        self.__dict__[key] = item
        print(item)

    def __getitem__(self, key):
        return self.__dict__[key]

Setting the item in one step in scenario A: w.setitem('key', response)

Getting the item in another step in scenario B: w.getitem('key',)

This shows me an error though:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1456, in run
    match.run(runner.context)
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1903, in run
    self.func(context, *args, **kwargs)
  File "steps\get_account.py", line 14, in step_impl
    print(w.__getitem__('appToken'))
  File "C:Project\steps\world.py", line 8, in __getitem__
    return self.__dict__[key]
KeyError: 'key'

It appears that the World does not hold values here between steps that are run.

Edit:

I'm unsure how to use environment.py but can see it has a way of running code before the steps. How can I allow my call to a soap client within environment.py to be called and then pass this to a particular step?

Edit:

I have made the request in environment.py and hardcoded the values, how can I pass variables to environment.py and back?

Body:
Have you tried the
simple approach, using global var, for instance:

def before_all(context):
    global response
    response = api.response

def before_scenario(context, scenario):
    global response
    w.key.add('key', response)

Guess feature can be accessed from context, for instance:

def before_feature(context, feature):
    feature.response = api.response

def before_scenario(context, scenario):
    w.key.add('key', context.feature.response)

You are looking for:

Class variable: A variable that is shared by all instances of a class.

Your code in Q uses Class Instance variable.

Read about: python_classes_objects

For instance:

class World(dict):
    __class_var = {}

    def __setitem__(self, key, item):
        World.__class_var[key] = item

    def __getitem__(self, key):
        return World.__class_var[key]

# Scenario A
A = World()
A['key'] = 'test'
print('A[\'key\']=%s' % A['key'] )
del A

# Scenario B
B = World()
print('B[\'key\']=%s' % B['key'] )

Output:

A['key']=test
B['key']=test

Tested with Python:3.4.2

Come back and Flag your Question as answered if this is working for you or comment why not.


问:
Optimising Java Script code
I have this JavaScript code to add and remove some classes. Below is the code. Can anybody help me to optimize this code?

```<code>  $(".showTR").click(function () {
    if (!$(this).parent().parent('tr').next('tr').hasClass('Row')) {
        if (!$(this).parent().parent('tr').next('tr').next('tr').hasClass('Row')) {
            if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').hasClass('Row')) {
                if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').hasClass('Row')) {
                    if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').hasClass('Row')) {
                        if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').next('tr').hasClass('Row')) {

                        } else {
                            $(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').next('tr').removeClass('Row')
                            $(this).hide();
                        }
                    }
                    else {
                        $(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').removeClass('Row');
                    }
                } else {
                    $(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').removeClass('Row');
                }

            } else {
                $(this).parent().parent('tr').next('tr').next('tr').next('tr').removeClass('Row');
            }
        } else {
            $(this).parent().parent('tr').next('tr').next('tr').removeClass('Row');
        }
    }
    else {
        $(this).parent().parent('tr').next('tr').removeClass('Row');
    }

});
</code>```

The code tries to detect tables next tr has class Row or not. If not then it goes to next tr, if yes it removes class Row from next tr then goes to next tr and so on ...

答:
Since HTML code is not available, you can try something like this:

Approach 1

Navigate to parent tr, For this you can use .closest('tr') or .parents('tr')

Now get the list of all next trs using .nextAll('tr')

Loop over them and check every value. If it has class, remove it and update a flag to not affect other trs.

If it was last tr, also hide .showTR

$(".showTR").click(function() {
  var self = this;
  var hasUpdated = false;
  var trs = $(this).parents('tr').nextAll("tr");
  $.each(trs, function(i, tr) {
    if (!hasUpdated) {
      var $tr = $(tr);
      hasUpdated = $tr.hasClass('Row') && $tr.removeClass('Row') && true;
      if (i === trs.length - 1) {
        $(self).hide()
      }
    }
  })
});
```

<hr>

<p><strong>Approach 2</strong></p>

<ul>
<li>Get first sibling <code>tr</code> to parent <code>tr</code> that has class "Row".</li>
<li>Remove class from it.</li>
<li>If it is last child, hide <code>.showTR</code></li>
</ul>

<pre class="lang-js prettyprint-override"><code>$(".showTR").click(function() {
  var tr = $(this).parents('tr').next("tr.Row:first");
  if(tr.length){
    tr.removeClass("Row");
    if(tr.is(':last-child'))
      $(this).hide()
  }
});
</code>```

Title: Optimising Java Script code

Body:
I have this JavaScript code to add and remove some classes. Below is the code. Can anybody help me to optimize this code?

  $(".showTR").click(function () {
    if (!$(this).parent().parent('tr').next('tr').hasClass('Row')) {
        if (!$(this).parent().parent('tr').next('tr').next('tr').hasClass('Row')) {
            if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').hasClass('Row')) {
                if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').hasClass('Row')) {
                    if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').hasClass('Row')) {
                        if (!$(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').next('tr').hasClass('Row')) {

                        } else {
                            $(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').next('tr').removeClass('Row')
                            $(this).hide();
                        }
                    }
                    else {
                        $(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').next('tr').removeClass('Row');
                    }
                } else {
                    $(this).parent().parent('tr').next('tr').next('tr').next('tr').next('tr').removeClass('Row');
                }

            } else {
                $(this).parent().parent('tr').next('tr').next('tr').next('tr').removeClass('Row');
            }
        } else {
            $(this).parent().parent('tr').next('tr').next('tr').removeClass('Row');
        }
    }
    else {
        $(this).parent().parent('tr').next('tr').removeClass('Row');
    }

});

The code tries to detect tables next tr has class Row or not. If not then it goes to next tr, if yes it removes class Row from next tr then goes to next tr and so on ...

Body:
Since HTML code is not available, you can try something like this:

Approach 1

Navigate to parent tr, For this you can use .closest('tr') or .parents('tr')

Now get the list of all next trs using .nextAll('tr')

Loop over them and check every value. If it has class, remove it and update a flag to not affect other trs.

If it was last tr, also hide .showTR

$(".showTR").click(function() {
  var self = this;
  var hasUpdated = false;
  var trs = $(this).parents('tr').nextAll("tr");
  $.each(trs, function(i, tr) {
    if (!hasUpdated) {
      var $tr = $(tr);
      hasUpdated = $tr.hasClass('Row') && $tr.removeClass('Row') && true;
      if (i === trs.length - 1) {
        $(self).hide()
      }
    }
  })
});

Approach 2

Get first sibling tr to parent tr that has class "Row".

Remove class from it.

If it is last child, hide .showTR

$(".showTR").click(function() {
  var tr = $(this).parents('tr').next("tr.Row:first");
  if(tr.length){
    tr.removeClass("Row");
    if(tr.is(':last-child'))
      $(this).hide()
  }
});


问:
how to get the date from string in C#
I have a string like

```<code> string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");
</code>```

want the output only 2017-03-10

答:
Modify your code like below

```<code>string startdatestring = "2017-03-10T07:19:28.907";
//1st way - Convert.ToDatetime works properly
//DateTime firstdate = Convert.ToDateTime(startdatestring);
//2nd way - DateTime.Parse also works perfect
//DateTime firstdate = DateTime.Parse(startdatestring);
//3rd way - DateTime.ParseExact also works perfect
DateTime firstdate = DateTime.ParseExact(startdatestring,
                                 "yyyy-MM-ddTHH:mm:ss.fff",
                                 CultureInfo.InvariantCulture);
var firstDateString = firstdate.ToString("yyyy-MM-dd");
Console.WriteLine(firstDateString);
</code>```

OUTPUT

2017-03-10

Title: how to get the date from string in C#

Body:
I have a string like

 string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");

want the output only 2017-03-10

Body:
Modify your code like below

string startdatestring = "2017-03-10T07:19:28.907";
//1st way - Convert.ToDatetime works properly
//DateTime firstdate = Convert.ToDateTime(startdatestring);
//2nd way - DateTime.Parse also works perfect
//DateTime firstdate = DateTime.Parse(startdatestring);
//3rd way - DateTime.ParseExact also works perfect
DateTime firstdate = DateTime.ParseExact(startdatestring,
                                 "yyyy-MM-ddTHH:mm:ss.fff",
                                 CultureInfo.InvariantCulture);
var firstDateString = firstdate.ToString("yyyy-MM-dd");
Console.WriteLine(firstDateString);

OUTPUT

2017-03-10


问:
Angular2 CLI error "@angular/compiler-cli" package was not properly installed
I'm working an Angular 2 project. Now trying to install Angular CLI within the current project with the following

```<code>npm install --save-dev @angular/cli@latest
npm install
</code>```

Problem is when running ng serve I receive error

```<code>The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/myng2project/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/myng2project/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
</code>```

答:
After update angular-cli I got the same error and I fixed it by call npm install -g angular-cli at project dir. After than update angular-cli.json, change

```<code>"environments": {
  "source": "environments/environment.ts",
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}
</code>```

to

```<code>"environmentSource": "environments/environment.ts",
"environments": {
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}
</code>```

Body:
I'm working an Angular 2 project. Now trying to install Angular CLI within the current project with the following

npm install --save-dev @angular/cli@latest
npm install

Problem is when running ng serve I receive error

The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/myng2project/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/myng2project/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

Body:
After update angular-cli I got the same error and I fixed it by call npm install -g angular-cli at project dir. After than update angular-cli.json, change

"environments": {
  "source": "environments/environment.ts",
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}

to

"environmentSource": "environments/environment.ts",
"environments": {
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}


问:
R pamk use of clara
I am wondering how to choose the number of samples when using pamk

pamk <- pamk(d, usepam=F)

This way I use clara instead of pam however when I use clara samples = 5 is default, but i change it

clara = clara(d, k=6, samples = 1000)

How do I use pamk to find optimal number of clusters whilst specifying how many samples is used when computing clara?

答:
If I'm not mistaking, there's a ... argument to pfc::pamk where you can pass arguments pased on to clara. So in your case, that would mean

```<code>pamk(d, usepam = FALSE, k = 6, samples = 1000)
</code>```

See also page 95 of the manual or ?pamk.

Title: R pamk use of clara

Body:
If I'm not mistaking, there's a ... argument to pfc::pamk where you can pass arguments pased on to clara. So in your case, that would mean

pamk(d, usepam = FALSE, k = 6, samples = 1000)

See also page 95 of the manual or ?pamk.


问:
EF7 migration generator is ignoring context parameter
I have recently migrated my EF7 project from DotNet Core 1.0.0 to Version 1.1.0, now I have trouble with creating the database migrations.

In my project I have multiple contexts, the tool dotnet-ef is providing a command line parameter to distinct between these contexts in order to create a separate migration for each context.

When I try to create the migrations for the context "AuditLogContext" with the command

```<code>dotnet ef migrations add Initial --context 'Some.Namespace.AuditLogContext' --output-dir './Migrations/AuditLogMigrations'
</code>```

then it fails, telling me

The name 'Initial' is used by an existing migration.

when I'm trying to create the migration with another name, say Initial2, the migration get created but for the wrong context.

In the folder

./Migrations/AuditLogMigrations

are new files named

20170212122451_Initial2.cs

20170212122451_Initial2.Designer.cs

CoreContextModelSnapshot.cs

I expect the file AuditLogContextModelSnapshot.cs instead.

Does anybody have solved this issue before?

答:
I found the reason for this problem.

I have multiple contexts in my project, every context expects parameters. So migrations builder expects a factory for every context.

In my case one class, implements all factories, now there is a bug that the concrete order of the interfaces is used to determine which migrations are created.

```<code>public class Program : IDbContextFactory<CoreContext>, IDbContextFactory<AuditLogContext>, IDbContextFactory<LockContext>
</code>```

This snippet will create migrations for the CoreContext

```<code>public class Program :  IDbContextFactory<AuditLogContext>, IDbContextFactory<CoreContext>,IDbContextFactory<LockContext>
</code>```

and the snippet will create migrations for the AuditLogContext.

It's a bit annoying but if you know how to create the migrations it's ok.

Body:
I have recently migrated my EF7 project from DotNet Core 1.0.0 to Version 1.1.0, now I have trouble with creating the database migrations.

In my project I have multiple contexts, the tool dotnet-ef is providing a command line parameter to distinct between these contexts in order to create a separate migration for each context.

When I try to create the migrations for the context "AuditLogContext" with the command

dotnet ef migrations add Initial --context 'Some.Namespace.AuditLogContext' --output-dir './Migrations/AuditLogMigrations'

then it fails, telling me

The name 'Initial' is used by an existing migration.

when I'm trying to create the migration with another name, say Initial2, the migration get created but for the wrong context.

In the folder

./Migrations/AuditLogMigrations

are new files named

20170212122451_Initial2.cs

20170212122451_Initial2.Designer.cs

CoreContextModelSnapshot.cs

I expect the file AuditLogContextModelSnapshot.cs instead.

Does anybody have solved this issue before?

Body:
I found the reason for this problem.

I have multiple contexts in my project, every context expects parameters. So migrations builder expects a factory for every context.

In my case one class, implements all factories, now there is a bug that the concrete order of the interfaces is used to determine which migrations are created.

public class Program : IDbContextFactory<CoreContext>, IDbContextFactory<AuditLogContext>, IDbContextFactory<LockContext>

This snippet will create migrations for the CoreContext

public class Program :  IDbContextFactory<AuditLogContext>, IDbContextFactory<CoreContext>,IDbContextFactory<LockContext>

and the snippet will create migrations for the AuditLogContext.

It's a bit annoying but if you know how to create the migrations it's ok.


问:
win32: check if window is minimized
How can one check whether a window is minimized using the win32 api?</p>

答: use the IsIconic function.</p>

Title: win32: check if window is minimized

Body: use the IsIconic function.


问:
How to find a location around another place by time and distance search in google maps?
I have a situation, where i have certain location (y) is in the database (lat and lng) now i want to search a place ( lets say x) and need to search locations nearby (x) by time or distance (like 10min or 10km also (driving or walking)) to (x).

So get all the y's near x (by time or distance).

Is there a clean or simple way to do that.
Thanks :)

答:
Found it!!
Can be done using google maps

direction api
  and
  matrix api

https://developers.google.com/maps/documentation/directions/

https://developers.google.com/maps/documentation/distance-matrix

one or more locations separated by the pipe character (|), in the form
  of an address, latitude/longitude coordinates, or a place ID:


问:
Java: how to compare two strings in order to obtain the portions where they differ?
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

```<code>String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
</code>```

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

```<code>private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}
</code>```

Calling getAllSubsequences on these two strings:

```<code>String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
</code>```

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

答:
I already flagged a duplicate question above whose answer uses Longest Common Subsequence for 2 Strings.

So you can apply it recursively and on each new recursion, use a placeholder where this LCS was found so that you can mark the parts that differ. In the end, when no more common sequences exist, you will have to split each String by the placeholder and get the required parts.

UPDATE 1: If I think better now, this recursion part might not lead to an optimal solution (from the total execution time point of view), since you will iterate over the Strings multiple times. But there might be a way to retrieve all sequences from one iteration by reusing (a reduced version of) the memoization table, check this implementation and this more detailed one.

UPDATE 2: I have managed to implement the recursive version (not optimal), based on this code:

```<code>public class LongestCommonSequence {

    private final char[] firstStr;
    private final char[] secondStr;
    private int[][] LCS;
    private String[][] solution;
    private int max = -1, maxI = -1, maxJ = -1;
    private static final Character SEPARATOR = '|';

    public LongestCommonSequence(char[] firstStr, char[] secondStr) {
        this.firstStr = firstStr;
        this.secondStr = secondStr;
        LCS = new int[firstStr.length + 1][secondStr.length + 1];
        solution = new String[firstStr.length + 1][secondStr.length + 1];
    }

    public String find() {

        for (int i = 0; i <= secondStr.length; i++) {
            LCS[0][i] = 0;
            if(i > 0) {
                solution[0][i] = "   " + secondStr[i - 1];
            }
        }

        for (int i = 0; i <= firstStr.length; i++) {
            LCS[i][0] = 0;
            if(i > 0) {
                solution[i][0] = "   " + firstStr[i - 1];
            }
        }

        solution[0][0] = "NONE";

        for (int i = 1; i <= firstStr.length; i++) {
            for (int j = 1; j <= secondStr.length; j++) {
                if (firstStr[i - 1] == secondStr[j - 1] && firstStr[i - 1] != SEPARATOR) {
                    LCS[i][j] = LCS[i - 1][j - 1] + 1;
                    solution[i][j] = "diag";
                } else {
                    LCS[i][j] = 0;
                    solution[i][j] = "none";
                }
                if(LCS[i][j] > max) {
                    max = LCS[i][j];
                    maxI = i;
                    maxJ = j;
                }
            }
        }

        System.out.println("Path values:");
        for (int i = 0; i <= firstStr.length; i++) {
            for (int j = 0; j <= secondStr.length; j++) {
                System.out.print(" " + LCS[i][j]);
            }
            System.out.println();
        }

        System.out.println();
        System.out.println("Path recovery:");
        for (int i = 0; i <= firstStr.length; i++) {
            for (int j = 0; j <= secondStr.length; j++) {
                System.out.print(" " + solution[i][j]);
            }
            System.out.println();
        }
        System.out.println();
        System.out.println("max:" + max + " maxI:" + maxI + " maxJ:" + maxJ);

        return printSolution(maxI, maxJ);
    }

    public String printSolution(int i, int j) {
        String answer = "";
        while(i - 1 >= 0 && j - 1 >= 0 && LCS[i][j] != 0) {
            answer = firstStr[i - 1] + answer;
            i--;
            j--;
        }
        System.out.println("Current max solution: " + answer);
        return answer;
    }

    public static void main(String[] args) {
        String firstStr = "x4.printString(\\\"Bianca.()\\\").y1();";
        String secondStr = "sb.printString(\\\"Bianca.()\\\").length();";
        String maxSubstr;
        LongestCommonSequence lcs;
        do {
            lcs = new LongestCommonSequence(firstStr.toCharArray(), secondStr.toCharArray());
            maxSubstr = lcs.find();
            if(maxSubstr.length() != 0) {
                firstStr = firstStr.replace(maxSubstr, "" + LongestCommonSequence.SEPARATOR);
                secondStr = secondStr.replace(maxSubstr, "" + LongestCommonSequence.SEPARATOR);
            }
        }
        while(maxSubstr.length() != 0);

        System.out.println();
        System.out.println("first:" + firstStr + " second: " + secondStr);

        System.out.println("First array: ");
        String[] firstArray = firstStr.split("\\" + SEPARATOR);
        String[] secondArray = secondStr.split("\\" + SEPARATOR);
        for(String s: firstArray) {
            System.out.println(s);
        }
        System.out.println();
        System.out.println("Second array: ");
        for(String s: secondArray) {
            System.out.println(s);
        }
    }
}
</code>```

Body:
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}

Calling getAllSubsequences on these two strings:

String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

Body:
I already flagged a duplicate question above whose answer uses Longest Common Subsequence for 2 Strings.

So you can apply it recursively and on each new recursion, use a placeholder where this LCS was found so that you can mark the parts that differ. In the end, when no more common sequences exist, you will have to split each String by the placeholder and get the required parts.

UPDATE 1: If I think better now, this recursion part might not lead to an optimal solution (from the total execution time point of view), since you will iterate over the Strings multiple times. But there might be a way to retrieve all sequences from one iteration by reusing (a reduced version of) the memoization table, check this implementation and this more detailed one.

UPDATE 2: I have managed to implement the recursive version (not optimal), based on this code:

public class LongestCommonSequence {

    private final char[] firstStr;
    private final char[] secondStr;
    private int[][] LCS;
    private String[][] solution;
    private int max = -1, maxI = -1, maxJ = -1;
    private static final Character SEPARATOR = '|';

    public LongestCommonSequence(char[] firstStr, char[] secondStr) {
        this.firstStr = firstStr;
        this.secondStr = secondStr;
        LCS = new int[firstStr.length + 1][secondStr.length + 1];
        solution = new String[firstStr.length + 1][secondStr.length + 1];
    }

    public String find() {

        for (int i = 0; i <= secondStr.length; i++) {
            LCS[0][i] = 0;
            if(i > 0) {
                solution[0][i] = "   " + secondStr[i - 1];
            }
        }

        for (int i = 0; i <= firstStr.length; i++) {
            LCS[i][0] = 0;
            if(i > 0) {
                solution[i][0] = "   " + firstStr[i - 1];
            }
        }

        solution[0][0] = "NONE";

        for (int i = 1; i <= firstStr.length; i++) {
            for (int j = 1; j <= secondStr.length; j++) {
                if (firstStr[i - 1] == secondStr[j - 1] && firstStr[i - 1] != SEPARATOR) {
                    LCS[i][j] = LCS[i - 1][j - 1] + 1;
                    solution[i][j] = "diag";
                } else {
                    LCS[i][j] = 0;
                    solution[i][j] = "none";
                }
                if(LCS[i][j] > max) {
                    max = LCS[i][j];
                    maxI = i;
                    maxJ = j;
                }
            }
        }

        System.out.println("Path values:");
        for (int i = 0; i <= firstStr.length; i++) {
            for (int j = 0; j <= secondStr.length; j++) {
                System.out.print(" " + LCS[i][j]);
            }
            System.out.println();
        }

        System.out.println();
        System.out.println("Path recovery:");
        for (int i = 0; i <= firstStr.length; i++) {
            for (int j = 0; j <= secondStr.length; j++) {
                System.out.print(" " + solution[i][j]);
            }
            System.out.println();
        }
        System.out.println();
        System.out.println("max:" + max + " maxI:" + maxI + " maxJ:" + maxJ);

        return printSolution(maxI, maxJ);
    }

    public String printSolution(int i, int j) {
        String answer = "";
        while(i - 1 >= 0 && j - 1 >= 0 && LCS[i][j] != 0) {
            answer = firstStr[i - 1] + answer;
            i--;
            j--;
        }
        System.out.println("Current max solution: " + answer);
        return answer;
    }

    public static void main(String[] args) {
        String firstStr = "x4.printString(\\\"Bianca.()\\\").y1();";
        String secondStr = "sb.printString(\\\"Bianca.()\\\").length();";
        String maxSubstr;
        LongestCommonSequence lcs;
        do {
            lcs = new LongestCommonSequence(firstStr.toCharArray(), secondStr.toCharArray());
            maxSubstr = lcs.find();
            if(maxSubstr.length() != 0) {
                firstStr = firstStr.replace(maxSubstr, "" + LongestCommonSequence.SEPARATOR);
                secondStr = secondStr.replace(maxSubstr, "" + LongestCommonSequence.SEPARATOR);
            }
        }
        while(maxSubstr.length() != 0);

        System.out.println();
        System.out.println("first:" + firstStr + " second: " + secondStr);

        System.out.println("First array: ");
        String[] firstArray = firstStr.split("\\" + SEPARATOR);
        String[] secondArray = secondStr.split("\\" + SEPARATOR);
        for(String s: firstArray) {
            System.out.println(s);
        }
        System.out.println();
        System.out.println("Second array: ");
        for(String s: secondArray) {
            System.out.println(s);
        }
    }
}


问:
Replacing certain combination of characters
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

```<code>string.replaceAll("[A-Z]+". ", "");
</code>```

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

答:
Without looking your code it is hard to tell the problem. but from my experience this is the common problem which generally we make in our initial days:

```<code>String string = "A. Test String";
string.replaceAll("^[A-Z]\\. ", "");
System.out.println(string);
</code>```

String is an immutable class in Java. what it means once you have create a object it can not be changed. so here when we do replaceAll in existing String it simply create a new String Object. that you need to assign to a new variable or overwrite existing value something like below :

```<code>String string = "A. Test String";
string  = string.replaceAll("^[A-Z]\\. ", "");
System.out.println(string);
</code>```

Body:
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

string.replaceAll("[A-Z]+". ", "");

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

Body:
Without looking your code it is hard to tell the problem. but from my experience this is the common problem which generally we make in our initial days:

String string = "A. Test String";
string.replaceAll("^[A-Z]\\. ", "");
System.out.println(string);

String is an immutable class in Java. what it means once you have create a object it can not be changed. so here when we do replaceAll in existing String it simply create a new String Object. that you need to assign to a new variable or overwrite existing value something like below :

String string = "A. Test String";
string  = string.replaceAll("^[A-Z]\\. ", "");
System.out.println(string);


问:
Simple click event not working in JS
I have created a very simple fiddle in JsFiddle. To my surprise it is not working. Please let me know if I am mistaking anything.

HTML-

```<code><button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>
</code>```

JS-

```<code>function test1(){
    alert("1");
}
</code>```

I want to show a simple alert on button click but it is not showing up.

Please click here to see this simple fiddle.

答:
Write the function inside the script tag as shown in this jsfiddle.</p>

```<code><button onclick="test1()">
  Push
 </button>
 <input type="button" value="Click" onclick="test1()"/>
<script>
function test1(){
    alert("1");
}
</script>
</code>```

Title: Simple click event not working in JS

Body:
I have created a very simple fiddle in JsFiddle. To my surprise it is not working. Please let me know if I am mistaking anything.

HTML-

<button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>

JS-

function test1(){
    alert("1");
}

I want to show a simple alert on button click but it is not showing up.

Please click here to see this simple fiddle.

Body:
Write the function inside the script tag as shown in this jsfiddle.

<button onclick="test1()">
  Push
 </button>
 <input type="button" value="Click" onclick="test1()"/>
<script>
function test1(){
    alert("1");
}
</script>