问:
Open DBs in parallel using VBA
I have an Access database which is used to calculate performance scores for a large number of people for each day of the week.

Due to the size of the dataset the procedure runs quite slowly. As a potential way to speed this up I am considering a process that would have 5 separate databases that each calculate the scores for one day.

I have written the below VBA code that just opens all of these DBs (Once each DB is open it has it's own autoExec macro that will kick off it's own procedure).

```<code>Sub DBloop()
 Dim dbArr As Variant
 Dim i As Integer

 dbArr = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

 For i = 0 To UBound(dbArr)
     openDBs CStr(dbArr(i))
 Next
End Sub

Sub openDBs(dbname As String)
 Dim acc As Access.Application
 Dim DBpath As String
 Dim strDbName As String

 DBpath = "H:\Performance Test\"
 strDbName = DBpath & dbname & ".accdb"

 Set acc = New Access.Application
 acc.Visible = True
 acc.OpenCurrentDatabase strDbName, False
End Sub
</code>```

Unfortunately, what is happening is that as each DB is opened, the initial procedure is waiting for the autoExec macro of that DB to complete before opening the next one. Does anyone know if there is a workaround for this?

答:
There are many ways to make sure you don't synchronously open a database.

One of the most simple ones is the following:

```<code>Application.FollowHyperlink strDbName
</code>```

(no need to create a new Access application object).

Another way is to make the code in your AutoExec macro execute asynchronously. The technique I use for that is the following:

Create a hidden form

Set it's timer to 1

Execute the code, and close the form on the timer

Further ways include things as using Shell or the WScript.Shell object.

Title: Open DBs in parallel using VBA

Body:
I have an Access database which is used to calculate performance scores for a large number of people for each day of the week.

Due to the size of the dataset the procedure runs quite slowly. As a potential way to speed this up I am considering a process that would have 5 separate databases that each calculate the scores for one day.

I have written the below VBA code that just opens all of these DBs (Once each DB is open it has it's own autoExec macro that will kick off it's own procedure).

Sub DBloop()
 Dim dbArr As Variant
 Dim i As Integer

 dbArr = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

 For i = 0 To UBound(dbArr)
     openDBs CStr(dbArr(i))
 Next
End Sub

Sub openDBs(dbname As String)
 Dim acc As Access.Application
 Dim DBpath As String
 Dim strDbName As String

 DBpath = "H:\Performance Test\"
 strDbName = DBpath & dbname & ".accdb"

 Set acc = New Access.Application
 acc.Visible = True
 acc.OpenCurrentDatabase strDbName, False
End Sub

Unfortunately, what is happening is that as each DB is opened, the initial procedure is waiting for the autoExec macro of that DB to complete before opening the next one. Does anyone know if there is a workaround for this?

Body:
There are many ways to make sure you don't synchronously open a database.

One of the most simple ones is the following:

Application.FollowHyperlink strDbName

(no need to create a new Access application object).

Another way is to make the code in your AutoExec macro execute asynchronously. The technique I use for that is the following:

Create a hidden form

Set it's timer to 1

Execute the code, and close the form on the timer

Further ways include things as using Shell or the WScript.Shell object.


来源: stackexchange

问:
How do I make buttons go across horizontal vs. stacking & make them 50% (2 by 2) on mobile?
I am trying to achieve the following look for desktop & mobile -

Here is what I have so far -

    .container {
        display: flex;
        flex-direction:row;
        margin: 0 auto;
        width: 100%;
        max-width: 1170px;
        flex-wrap: wrap;
        height:100vh;
    }

    .button {
        letter-spacing: 1px;
        justify-content: space-between;
        flex: 1 0 auto;
        align-items: flex-start;
    }
    /* ---- Intro ---- */

    #intro {
        background: #ff6400;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4em 0;
    }

    #intro .cta {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;
    }

    #intro .cta .splash {
        display: none;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='intro'>
    <div class='cta container'>
        <div class="herosvg-container"><img src="http://svgshare.com/i/407.svg" width="100%"></div>
        <p>Delectus illum corporis laundantium illo repudiandae et doloemque.</p>
         <span>SHOP NOW</span>
         <span>SHOP NOW</span>
         <span>SHOP NOW</span>
         <span>SHOP NOW</span>
    </div>
</div></code>```

I'd like to avoid running into the issue where the buttons might overlap the svg, or vise versa. Also I'd like the ability to control the width of buttons and svg separately while being able to say "i want to float the svg and buttons to the left or right of the hero."

If you have any ideas or can point me to the right direction you would be a life saver.

Thanks!

答:
Wrap the links in their own container. You'll find it much simpler to display them as you require using flexbox on that container.

Media queries do the rest.

Full Page - Buttons to side

Small Page - Buttons underneath in row

Mobile - Button underneath in wrapping rows

A quick example:

.container {
  display: flex;
  width: 80%;
  margin: auto;
}

img {
  max-width: 100%;
}

.button-wrap {
  padding: 1em;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

@media (max-width: 699px) {
  .container {
    flex-direction: column;
  }
  .button-wrap {
    padding: 1em 0;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  button {
    flex: 0 0 20%;
  }
}

@media (max-width: 400px) {
  button {
    flex: 0 0 40%;
    margin-bottom: 1em;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="hero"><img src="http://www.placebacon.net/1200/300" alt=""></div>
  <div class="button-wrap">
    <button>Button 1</button>
    <button>Button 2</button>
    <button>Button 3</button>
    <button>Button 4</button>
  </div>
</div></code>```

Codepen Example

ContentLicense: CC BY-SA 3.0

Body:
I am trying to achieve the following look for desktop & mobile -

Here is what I have so far -

    .container {
        display: flex;
        flex-direction:row;
        margin: 0 auto;
        width: 100%;
        max-width: 1170px;
        flex-wrap: wrap;
        height:100vh;
    }

    .button {
        letter-spacing: 1px;
        justify-content: space-between;
        flex: 1 0 auto;
        align-items: flex-start;
    }
    /* ---- Intro ---- */

    #intro {
        background: #ff6400;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4em 0;
    }

    #intro .cta {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;
    }

    #intro .cta .splash {
        display: none;
    }

Delectus illum corporis laundantium illo repudiandae et doloemque.

         SHOP NOW
         SHOP NOW
         SHOP NOW
         SHOP NOW

I'd like to avoid running into the issue where the buttons might overlap the svg, or vise versa. Also I'd like the ability to control the width of buttons and svg separately while being able to say "i want to float the svg and buttons to the left or right of the hero."

If you have any ideas or can point me to the right direction you would be a life saver.

Thanks!

Body:
Wrap the links in their own container. You'll find it much simpler to display them as you require using flexbox on that container.

Media queries do the rest.

Full Page - Buttons to side

Small Page - Buttons underneath in row

Mobile - Button underneath in wrapping rows

A quick example:

.container {
  display: flex;
  width: 80%;
  margin: auto;
}

img {
  max-width: 100%;
}

.button-wrap {
  padding: 1em;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

@media (max-width: 699px) {
  .container {
    flex-direction: column;
  }
  .button-wrap {
    padding: 1em 0;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  button {
    flex: 0 0 20%;
  }
}

@media (max-width: 400px) {
  button {
    flex: 0 0 40%;
    margin-bottom: 1em;
  }
}

<div class="container">
  <div class="hero"><img src="http://www.placebacon.net/1200/300" alt=""></div>
  <div class="button-wrap">
    <button>Button 1</button>
    <button>Button 2</button>
    <button>Button 3</button>
    <button>Button 4</button>
  </div>
</div>

Codepen Example


问:
What are Sockets afterall? Why can't we use sockets instead of HTTP?
Are sockets just a connection between 2 machines?

And if sockets can be established why do we even use HTTP connection?

答:
Lets say that socket is just a stream between 2 remote systems which uses TCP/IP or maybe UPD lower level protocols for transport data. And HTTP is the higher level protocol which specifies HOW systems are communicating.

Small example: air is a transport level for voice, but you need words (an upper level protocol) for communication with other ppl.

But better for you to read here: http://en.wikipedia.org/wiki/OSI_model

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
How to place a file directly in HDFS without using local by directly download a file from a webpage?
I need some help. I am downloading a file from a webpage using python code and placing it in local file system and then transferring it into HDFS using put command and then performing operations on it.

But there might be some situations where the file size will be very large  and downloading into Local File System is not a right procedure. So I want the file to be directly be downloaded into HDFS with out using the local file system at all.

Can any one suggest me some methods which one would be the best method to proceed?
If there are any errors in my question please correct me.

答:
You can pipe it directly from a download to avoid writing it to disk, e.g.:

```<code>curl server.com/my/file | hdfs dfs -put - destination/file
</code>```

The - parameter to -put tells it to read from stdin (see the documentation).

This will still route the download through your local machine, though, just not through your local file system. If you want to download the file without using your local machine at all, you can write a map-only MapReduce job whose tasks accept e.g. an input file containing a list of files to be downloaded and then download them and stream out the results. Note that this will require your cluster to have open access to the internet which is generally not desirable.

Body:
You can pipe it directly from a download to avoid writing it to disk, e.g.:

curl server.com/my/file | hdfs dfs -put - destination/file

The - parameter to -put tells it to read from stdin (see the documentation).

This will still route the download through your local machine, though, just not through your local file system. If you want to download the file without using your local machine at all, you can write a map-only MapReduce job whose tasks accept e.g. an input file containing a list of files to be downloaded and then download them and stream out the results. Note that this will require your cluster to have open access to the internet which is generally not desirable.


问:
Unable to get @Input() to work inside the constructor
I created two components, a parent and a child.

The parent has a member variable called applications:

```<code>import { Component, OnInit } from '@angular/core';
import { CoreService } from 'app/core.service';
import { Application } from 'app/models/application.model';

@Component({
  selector: 'app-applicationbrowser',
  templateUrl: './applicationbrowser.component.html',
  styleUrls: ['./applicationbrowser.component.css'],
  providers: [CoreService]
})
export class ApplicationbrowserComponent {
  applications: Application[] = [
    new Application(1, false, "beef"),
    new Application(2, false, "teef"),
    new Application(3, false, "feef")
  ];
  constructor() {

  }
}
</code>```

and uses the child component in its template:

```<code><div>
  <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem>
</div>
</code>```

I assumed that this gets called for each application in my applications variable.

But the child component only ever has an 'undefined' item variable:

```<code>  @Input()
   item: any;
  constructor() {
    debugger;
    console.log(this.item); //item is always undefined....
  }
</code>```

What am I doing wrong?

答:
@Input data is available in ngOnInit, not the constructor.

```<code>@Component({
  ...
})
export class SomeChildComponent implements OnInit {
  @Input() item: any;
  constructor(){}

  ngOnInit() {
    console.log(this.item);
  }
}
</code>```

Body:
I created two components, a parent and a child.

The parent has a member variable called applications:

import { Component, OnInit } from '@angular/core';
import { CoreService } from 'app/core.service';
import { Application } from 'app/models/application.model';

@Component({
  selector: 'app-applicationbrowser',
  templateUrl: './applicationbrowser.component.html',
  styleUrls: ['./applicationbrowser.component.css'],
  providers: [CoreService]
})
export class ApplicationbrowserComponent {
  applications: Application[] = [
    new Application(1, false, "beef"),
    new Application(2, false, "teef"),
    new Application(3, false, "feef")
  ];
  constructor() {

  }
}

and uses the child component in its template:

  <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem>

I assumed that this gets called for each application in my applications variable.

But the child component only ever has an 'undefined' item variable:

  @Input()
   item: any;
  constructor() {
    debugger;
    console.log(this.item); //item is always undefined....
  }

What am I doing wrong?

Body:
@Input data is available in ngOnInit, not the constructor.

@Component({
  ...
})
export class SomeChildComponent implements OnInit {
  @Input() item: any;
  constructor(){}

  ngOnInit() {
    console.log(this.item);
  }
}


问:
SSRS Performance
I Have created an SSRS Report for retrieving 55000 records using a Stored Procedure. When
executing from the Stored Proc it is taking just 3 seconds but when executing from SSRS report it is taking more than one minute. How can I solve this problem?</p>

答:
I had a similar problem: a query that returns 4,000 rows and runs in 1 second on it's own was taking so long in SSRS that it timed out.

It turned out that the issue was caused by the way SSRS was handling a multi-valued parameter. Interestingly, if the user selected multiple values, the report rendered quickly (~1 second), but if only a single value was selected, the report took several minutes to render.

Here is the original query that was taking more than 100x longer to render than it should:

```<code>SELECT ...
FROM   ...
WHERE  filename IN (@file);
-- @file is an SSRS multi-value parameter passed directly to the query
</code>```

I suspect the issue was that SSRS was bringing in the entire source table (over 1 million rows) and then performing a client-side filter.

To fix this, I ended up passing the parameter into the query through an expression, so that I could control the filter myself. That is, in the "DataSet Properties" window, on the "Parameters" screen, I replaced the parameter value with this expression:

```<code>=JOIN(Parameters!file.Value,",")
</code>```

... (I also gave the result a new name: filelist) and then I updated the query to look like this:

```<code>SELECT ...
FROM   ...
WHERE  ',' + @filelist + ',' LIKE '%,' + FILENAME + ',%';
-- @filelist is passed to the query as the following expression:
-- =JOIN(Parameters!file.Value,",")
</code>```

I would guess that moving the query to a stored procedure would also be an effective way to alleviate the problem (because SSRS basically does the same JOIN before passing a multi-value parameter to a stored procedure). But in my case it was a little simpler to handle it all within the report.

Finally, I should note that the LIKE operator is maybe not the most efficient way to filter on a list of items, but it's certainly much simpler to code than a split-string approach, and the report now runs in about a second, so splitting the string didn't seem worth the extra effort.

OwnerDisplayName: Sinshith

Title: SSRS Performance

Body:
I had a similar problem: a query that returns 4,000 rows and runs in 1 second on it's own was taking so long in SSRS that it timed out.

It turned out that the issue was caused by the way SSRS was handling a multi-valued parameter. Interestingly, if the user selected multiple values, the report rendered quickly (~1 second), but if only a single value was selected, the report took several minutes to render.

Here is the original query that was taking more than 100x longer to render than it should:

SELECT ...
FROM   ...
WHERE  filename IN (@file);
-- @file is an SSRS multi-value parameter passed directly to the query

I suspect the issue was that SSRS was bringing in the entire source table (over 1 million rows) and then performing a client-side filter.

To fix this, I ended up passing the parameter into the query through an expression, so that I could control the filter myself. That is, in the "DataSet Properties" window, on the "Parameters" screen, I replaced the parameter value with this expression:

=JOIN(Parameters!file.Value,",")

... (I also gave the result a new name: filelist) and then I updated the query to look like this:

SELECT ...
FROM   ...
WHERE  ',' + @filelist + ',' LIKE '%,' + FILENAME + ',%';
-- @filelist is passed to the query as the following expression:
-- =JOIN(Parameters!file.Value,",")

I would guess that moving the query to a stored procedure would also be an effective way to alleviate the problem (because SSRS basically does the same JOIN before passing a multi-value parameter to a stored procedure). But in my case it was a little simpler to handle it all within the report.

Finally, I should note that the LIKE operator is maybe not the most efficient way to filter on a list of items, but it's certainly much simpler to code than a split-string approach, and the report now runs in about a second, so splitting the string didn't seem worth the extra effort.


问:
Search Entire Excell Column for a value that is not always present, if not present create a new value
i have been trying to find  some help reading a spinet of code i am writing for a larger project. I am looking to identify a string in a column of excel. This string may not always be present in the column, in that case i need to be able to create a new string.

I have created a small macro to test this, currently I have the number 1:20 in column A. The code is searching for "37", and shouldn't be able to find it.
if the value is found display a msg box to confirm its been found or if it isn't found displays a msg box to say its not been found. If I was searching for "2" the Code works perfectly. I run into issues when the values is not present and "LastPLocation" has no value
Eventually I will need to create a variable and assign it a value eg. a string which says "Not present" or a number "0"

The variables names are taken from the main project, so you can change them.

```<code>Sub test()

Dim LastPLocation As String

Dim NewLastPLocation as String

LastPLocation = Range("A:A").Find(what:="37", after:=Range("A1"), searchdirection:=xlPrevious).Row

If LastPLocation Is Nothing Then

MsgBox ("No Last P")

NewLastPLocation = 0

Else

MsgBox (LastPLocation)

NewLastPLocation = LastPLocation + 1

MsgBox (NewLastPLocation)

End If

End Sub
</code>```

Thank you for any help that you are able to give.

答:
Instead of setting the lastPLocation as a String, use Range:

```<code>Sub test()
Dim LastPLocation As Range
Dim NewLastPLocation As String

Set LastPLocation = Range("A:A").Find(what:="37", after:=Range("A1"), searchdirection:=xlPrevious)

If LastPLocation Is Nothing Then
    MsgBox ("No Last P")
    ' Do things here when the value is NOT found
    NewLastPLocation = 0
Else
    ' Do things here when the value IS found
    MsgBox (LastPLocation.Row)
    NewLastPLocation = LastPLocation.Row + 1
End If

MsgBox (NewLastPLocation)

End Sub
</code>```

Body:
i have been trying to find  some help reading a spinet of code i am writing for a larger project. I am looking to identify a string in a column of excel. This string may not always be present in the column, in that case i need to be able to create a new string.

I have created a small macro to test this, currently I have the number 1:20 in column A. The code is searching for "37", and shouldn't be able to find it.
if the value is found display a msg box to confirm its been found or if it isn't found displays a msg box to say its not been found. If I was searching for "2" the Code works perfectly. I run into issues when the values is not present and "LastPLocation" has no value
Eventually I will need to create a variable and assign it a value eg. a string which says "Not present" or a number "0"

The variables names are taken from the main project, so you can change them.

Sub test()

Dim LastPLocation As String

Dim NewLastPLocation as String

LastPLocation = Range("A:A").Find(what:="37", after:=Range("A1"), searchdirection:=xlPrevious).Row

If LastPLocation Is Nothing Then

MsgBox ("No Last P")

NewLastPLocation = 0

Else

MsgBox (LastPLocation)

NewLastPLocation = LastPLocation + 1

MsgBox (NewLastPLocation)

End If

End Sub

Thank you for any help that you are able to give.

Body:
Instead of setting the lastPLocation as a String, use Range:

Sub test()
Dim LastPLocation As Range
Dim NewLastPLocation As String

Set LastPLocation = Range("A:A").Find(what:="37", after:=Range("A1"), searchdirection:=xlPrevious)

If LastPLocation Is Nothing Then
    MsgBox ("No Last P")
    ' Do things here when the value is NOT found
    NewLastPLocation = 0
Else
    ' Do things here when the value IS found
    MsgBox (LastPLocation.Row)
    NewLastPLocation = LastPLocation.Row + 1
End If

MsgBox (NewLastPLocation)

End Sub


问:
How to show data into textboxes
MY VIEW::

```<code> foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
            {

 foreach (TSM.Models.TimeSheetData itemm in ViewBag.HoursData)
 {
 foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
                {

     <td><input class="txtTaskHours date@(Date.AddDays(i).ToString("MMddyyy"))"
                style="width:50px;" value="@itemm.Hours" type="number"
                id="@(itm.ID.ToString() + ':' + Date.AddDays(i).ToString("MMddyyy"))" />
     </td>
 }
</code>```

My Controller:

```<code>var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
             equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
             && ts.EndDate == thisWeekEnd select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();
var TMSSS = (string.Join(",", query.Select(x => x.ToString())));
ViewBag.HoursData = TMSSS;
return PartialView("~/Views/TimeSheet/_TimeSheet.cshtml", ViewBag);
</code>```

I want to show data into the Textbox. To show data, I am using ViewBag by using foreach loop to show hours in the Textbox.

My Textbox data is saved in json.
This is my json value :

```<code>"TaskHours" : [{
                 "ID":"f2886ec7-47d3-e711-9666-000c297c9306:12042017",
                 "Value":"25"
               }]
</code>```

答:
Just remove the string.Join rows:

```<code>var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
             equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
             && ts.EndDate == thisWeekEnd select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();
// var TMSSS = (string.Join(",", query.Select(x => x.ToString())));
// ViewBag.HoursData = TMSSS;
ViewBag.HoursData = query;
return PartialView("~/Views/TimeSheet/_TimeSheet.cshtml", ViewBag);
</code>```

Your controller assigns a string to ViewBag.HoursData and your View expects an IEnumerable<TSM.Models.TimeSheetData> which could be your query variable.

UPDATE

Sorry, my bad. Didn't see that you're selecting a dynamic object in your LINQ. You'll need to create a new wrapper class where to place the values from your LINQ.

```<code>public class MyWrap {
public int Hours {get;set;}
public DateTime Date {get;set;}
public int TaskId {get;set;}
}
</code>```

And then modificate the LINQ:

```<code>&& ts.EndDate == thisWeekEnd select new MyWrap { Hours = tsdHours, Date = tsd.Date, TaskId = ts.TaskID}).ToList()
</code>```

And finally in your View:

```<code>foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
            {

 foreach (TSM.Models.MyWrap itemm in ViewBag.HoursData)
 {
</code>```

Title: How to show data into textboxes

Body:
MY VIEW::

 foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
            {

 foreach (TSM.Models.TimeSheetData itemm in ViewBag.HoursData)
 {
 foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
                {

     <input class="txtTaskHours date@(Date.AddDays(i).ToString("MMddyyy"))"
                style="width:50px;" value="@itemm.Hours" type="number"
                id="@(itm.ID.ToString() + ':' + Date.AddDays(i).ToString("MMddyyy"))" />

 }

My Controller:

var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
             equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
             && ts.EndDate == thisWeekEnd select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();
var TMSSS = (string.Join(",", query.Select(x => x.ToString())));
ViewBag.HoursData = TMSSS;
return PartialView("~/Views/TimeSheet/_TimeSheet.cshtml", ViewBag);

I want to show data into the Textbox. To show data, I am using ViewBag by using foreach loop to show hours in the Textbox.

My Textbox data is saved in json.
This is my json value :

"TaskHours" : [{
                 "ID":"f2886ec7-47d3-e711-9666-000c297c9306:12042017",
                 "Value":"25"
               }]

Body:
Just remove the string.Join rows:

var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
             equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
             && ts.EndDate == thisWeekEnd select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();
// var TMSSS = (string.Join(",", query.Select(x => x.ToString())));
// ViewBag.HoursData = TMSSS;
ViewBag.HoursData = query;
return PartialView("~/Views/TimeSheet/_TimeSheet.cshtml", ViewBag);

Your controller assigns a string to ViewBag.HoursData and your View expects an IEnumerable<TSM.Models.TimeSheetData> which could be your query variable.

UPDATE

Sorry, my bad. Didn't see that you're selecting a dynamic object in your LINQ. You'll need to create a new wrapper class where to place the values from your LINQ.

public class MyWrap {
public int Hours {get;set;}
public DateTime Date {get;set;}
public int TaskId {get;set;}
}

And then modificate the LINQ:

&& ts.EndDate == thisWeekEnd select new MyWrap { Hours = tsdHours, Date = tsd.Date, TaskId = ts.TaskID}).ToList()

And finally in your View:

foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
            {

 foreach (TSM.Models.MyWrap itemm in ViewBag.HoursData)
 {


问:
MVC: Should the view always receive arrays instead of objects?
I am wondering if the View should be passed objects or should they only receive arrays. I am using an ORM Framework. So in the Project View Page, can I pass the view a project object and let it render out project's todoLists and todos.

So currently in my view I have code like:

```<code>foreach ($this->project->getTodoLists() as $todoList) {
  // render lists
  foreach ($todoList->getTodos() as $todo) {
    // render todos
  }
}
</code>```

Is this ok? I think with doctrine's lazy loading, it runs SQL when get*() is called. Does it matter here?

Or should I in my controller parse out every required info into pure arrays?

I am using PHP, Zend Framework 1.11, Doctrine 2 ORM. But it doesn't really matter what I use in my opinion

答:
One pro for using non-lazy datatypes (ie arrays) for view rending is that there is nothing to fail. For example if an object's value is read and triggers a function to be called that ends up failing (issue with db, out of memory, etc), the view rendering can corrupted (IE error messages in the HTML document). When you pass an array to the view, it doesn't matter what data is accessed or in what order since it's pre-rendered.

While this issue can be mostly overcome by output buffering, something (such as fatal errors) can't be caught and will leak onto the page.

Of course in a language like PHP, laziness can help reduce memory spikes (since it's alloc'ed as it's needed and then rendered) and CPU usage (if you don't end up evaluating all the objects).

In the end it comes down to how complex you want your views to be. Simple Data Structure -> Simple View, and via versa.

Body:
I am wondering if the View should be passed objects or should they only receive arrays. I am using an ORM Framework. So in the Project View Page, can I pass the view a project object and let it render out project's todoLists and todos.

So currently in my view I have code like:

foreach ($this->project->getTodoLists() as $todoList) {
  // render lists
  foreach ($todoList->getTodos() as $todo) {
    // render todos
  }
}

Is this ok? I think with doctrine's lazy loading, it runs SQL when get*() is called. Does it matter here?

Or should I in my controller parse out every required info into pure arrays?

I am using PHP, Zend Framework 1.11, Doctrine 2 ORM. But it doesn't really matter what I use in my opinion


问:
Excel VBA: Concatenate lists with differing number of rows
So, this should be an interesting one...

I have 2 separate reports that provide customer satisfaction information on tickets (if I was able to get the data in 1 list, then this issue would not exist...).  Each list provides information including, most importantly, the ticket number.  One list provides a customer comment, while the other list provides a customer satisfaction score on a 1-5 scale.

A simple concatenate matching ticket numbers would be fairly easy, however, the database designer failed to make the customer comment field mandatory, so approximately 50% of the tickets have no comment.

I have both sheets with the past 60 days of information, however the one with scores is nearly double the size in row number.  What I need to do is combine the lists using first the score sheet, since it will include every ticket, then adding in the comment sheet, matching the comments with their respective tickets.

I am not even sure how to start this code, and I am not looking for finished code, only suggestions on direction.

Pseudo code would be something like:

Clear useless columns in each sheet

Sort each sheet by ticket creation date (or ticket number)

Copy survey comment sheet into survey score sheet, leaving a blank column or two in the middle.

Assuming that column A and column G include the ticket numbers, sort so that the values match up, and the rows with no survey comment value are blank for column G

Any direction is much appreciated!

答:
Something along the following will do what you want:</p>

```<code>Sub foo()
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find how many rows on Sheet1
LastRow2 = Sheet2.Cells(Rows.Count, "A").End(xlUp).Row 'Find how many rows on Sheet2
For i = 2 To LastRow 'loop from row 2 to last row
Sheet1.Cells(i, 3).FormulaR1C1 = "=VLOOKUP(RC[-1],Sheet2!R1:R1048576,2,FALSE)"
'enter the Vlookup formula on column number 3, change this number to suit your needs, also change the 2 before FALSE to the column number you wish to bring into Sheet1
Next i
End Sub
</code>```

Body:
Something along the following will do what you want:

Sub foo()
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find how many rows on Sheet1
LastRow2 = Sheet2.Cells(Rows.Count, "A").End(xlUp).Row 'Find how many rows on Sheet2
For i = 2 To LastRow 'loop from row 2 to last row
Sheet1.Cells(i, 3).FormulaR1C1 = "=VLOOKUP(RC[-1],Sheet2!R1:R1048576,2,FALSE)"
'enter the Vlookup formula on column number 3, change this number to suit your needs, also change the 2 before FALSE to the column number you wish to bring into Sheet1
Next i
End Sub


问:
Anchoring a text to the middle of a page
I've searched online for the answer to this question and I know it is possible to do this, but I just can't figure it out with what's out there.

Background: I'm creating a frequently asked questions segment where one can click the question and be directed to the answer on the same page. I also have the questions split into categories.

Although I have been able to achieve this with basic href concepts, I would like for the answer to the question to be displayed on the middle of the page and not right below of the margin of the top of the page once the user clicks the questions that's anchored.

Hopefully, I was able to paint a somewhat picture of what I mean. Now, I will show you what I have in terms of syntax.

I definitely do believe there are multiple ways in which I could've created the code using style, class, or other attributes, but I don't hold a strong coding background :(. Therefore, I went with what I was able to pick up from W3School stuff XD.

If someone can help me out, I'd very much appreciate it since it'd make the FAQ section a lot cooler to use.

Here are images explaining the scenario a little better as well.

Question Section
Answer Section

```<code>         <p>
         <strong>Color Questions</strong>
         <br/>
         <a href="#A">What is the door's color?</a>
         <br />
         <a href="#B">What is the window's color?</a>
         </p>
         <p>
         <strong>Shape Questions</strong>
         <br/>
         <a href="#C">What is the shape of a ball?</a>
         <br/>
         <a href="#D">What is the shape of a box?</a>
         </p>
         <h3>Answers</h3>
         <p>
         <strong>Color Questions</strong>
         </p>
         <p>
         <strong>
         <a id="A"></a>What is the door's color?
         </strong>
         <br />The door's color is blue.
         </p>
         <p>
         <strong>
         <a id="B"></a>What is the window's color?</strong>
         <br />The windows's color is red.
         </p>
         <p>
         <strong>
         Shape Questions</strong>
         </p>
         <p>
         <strong>
         <a id="C"></a>What is the shape of a ball?
         </strong>
         <br />A ball has the shape of a sphere.
         </p>
         <p>
         <strong>
         <a id="D"></a>What is the shape of a box?
         </strong>
         <br />A box has the shape of a cube.
         </p>
</code>```

答: if you want to put your text in middle you can use and put your text in this tag but it is obsolete right now,there are better methods to do this.you can use margin and paddingand set your text in great position also you can use position.check the w3schools.com for more details.its helpful.

Body:
I've searched online for the answer to this question and I know it is possible to do this, but I just can't figure it out with what's out there.

Background: I'm creating a frequently asked questions segment where one can click the question and be directed to the answer on the same page. I also have the questions split into categories.

Although I have been able to achieve this with basic href concepts, I would like for the answer to the question to be displayed on the middle of the page and not right below of the margin of the top of the page once the user clicks the questions that's anchored.

Hopefully, I was able to paint a somewhat picture of what I mean. Now, I will show you what I have in terms of syntax.

I definitely do believe there are multiple ways in which I could've created the code using style, class, or other attributes, but I don't hold a strong coding background :(. Therefore, I went with what I was able to pick up from W3School stuff XD.

If someone can help me out, I'd very much appreciate it since it'd make the FAQ section a lot cooler to use.

Here are images explaining the scenario a little better as well.

Question Section
Answer Section

         Color Questions

         What is the door's color?

         What is the window's color?

         Shape Questions

         What is the shape of a ball?

         What is the shape of a box?

Answers

         Color Questions

         What is the door's color?

The door's color is blue.

         What is the window's color?

The windows's color is red.

         Shape Questions

         What is the shape of a ball?

A ball has the shape of a sphere.

         What is the shape of a box?

A box has the shape of a cube.

Body: if you want to put your text in middle you can use <center>and put your text in this tag but it is obsolete right now,there are better methods to do this.you can use margin and paddingand set your text in great position also you can use position.check the w3schools.com for more details.its helpful.


问:
Can we exclude match with few strings in oracle regexp_like()?
Background Knowledge:

We can't use (?!) to exclude, since, regexp_like() doesn't support negative lookahead.

I don't want to exclude using 'NOT REGEXP_LIKE()'

[^] can negate a single character only but not a string

Question:

Interested to know if we have any alternative to change the regular expression itself being passed to oracle regexp_like().

Example scenario to explain:

Regexp - "STANDARD.*TIME" when used in regexp_like() would match all time zones containing both words STANDARD and TIME. Say I want to exclude 'INDIAN STANDARD TIME', 'ATLANTIC STANDARD TIME', 'IRISH STANDARD TIME' from the matched time zones

答:
I would be interested to know why using 'NOT' is out of the question.  But if you are looking for a regex solution for the fun of it, I don't think REGEXP_LIKE is going to work as the Oracle flavor does not support negative look-aheads.  However, thinking outside of the box a little, and knowing that REGEX_REPLACE returns NULL if the pattern is not found, you could do something like this (although just because you can does not mean you should and I would use NOT with REGEXP_LIKE):

```<code>SQL> with tbl(str) as (
     select 'INDIAN STANDARD TIME' from dual union all
     select 'ATLANTIC STANDARD TIME' from dual union all
     select 'IRISH STANDARD TIME' from dual union all
     select 'EASTERN STANDARD TIME' from dual union all
     select 'PST STANDARD TIME' from dual union all
     select 'CST STANDARD TIME' from dual
   )
   select str
   from tbl
   where str = regexp_replace(str, '^(INDIAN|ATLANTIC|IRISH) STANDARD.*TIME', 'DO NOT WANT THESE');

STR
----------------------
EASTERN STANDARD TIME
PST STANDARD TIME
CST STANDARD TIME

SQL>
</code>```

So this replaces the strings you don't want then compares them.  Since the match is not found the select does not return them.  Still not as clean as:

```<code>select str
from tbl
where NOT regexp_like(str, '^(INDIAN|ATLANTIC|IRISH) STANDARD.*TIME');
</code>```

Body:
I would be interested to know why using 'NOT' is out of the question.  But if you are looking for a regex solution for the fun of it, I don't think REGEXP_LIKE is going to work as the Oracle flavor does not support negative look-aheads.  However, thinking outside of the box a little, and knowing that REGEX_REPLACE returns NULL if the pattern is not found, you could do something like this (although just because you can does not mean you should and I would use NOT with REGEXP_LIKE):

SQL> with tbl(str) as (
     select 'INDIAN STANDARD TIME' from dual union all
     select 'ATLANTIC STANDARD TIME' from dual union all
     select 'IRISH STANDARD TIME' from dual union all
     select 'EASTERN STANDARD TIME' from dual union all
     select 'PST STANDARD TIME' from dual union all
     select 'CST STANDARD TIME' from dual
   )
   select str
   from tbl
   where str = regexp_replace(str, '^(INDIAN|ATLANTIC|IRISH) STANDARD.*TIME', 'DO NOT WANT THESE');

STR
----------------------
EASTERN STANDARD TIME
PST STANDARD TIME
CST STANDARD TIME

SQL>

So this replaces the strings you don't want then compares them.  Since the match is not found the select does not return them.  Still not as clean as:

select str
from tbl
where NOT regexp_like(str, '^(INDIAN|ATLANTIC|IRISH) STANDARD.*TIME');


问:
Check for word match count in random letters
I have a string of 500 random letters and a 10,000 dictionary word list.

I want to check the letters for word matches.

If there are 5 matches or greater I want it to return the list of matched words.

However this foreach and Contains.() doesn't seem to work correctly or return correct matches. It is also returning partial matches and single letters.

```<code>// 500 Random Letters
string letters = "bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio"

// Dictionary Words List
string[] words = File.ReadAllText(@"C:\dictionarywords.txt").Split('\n');

// Word Matches List
List<string> matches = new List<string>();

// Check for Word matches in Letters
foreach (var x in words)
{
    // Add to list if match
    if (letters.Contains(x))
    {
        matches.Add(x);
    }
}

// Return Matched Words if 5 or greater
if (matches.Count() >= 5)
{
    textBox.Text = string.Join("\n", matches);
}
</code>```

Examples

Word matches found by eye:

lid

hot

gum

hose

hat

Code Match Returns:

my

up

so

c

et

ms

am

me

s

x

n

b

...

答: Your code is working as intended. It IS finding those words, but it's also finding additional words. I'd suggest taking out the words you don't want to show up in a search. For example, a lot of people use this in a profanity filter. So if a sentence contains a curse word, it omits the word because it found it in the dictionary of curse words. Give it a try with a much smaller list with words you've put in yourself and test the results. Try changing those words to other words?</p>

Body:
I have a string of 500 random letters and a 10,000 dictionary word list.

I want to check the letters for word matches.

If there are 5 matches or greater I want it to return the list of matched words.

However this foreach and Contains.() doesn't seem to work correctly or return correct matches. It is also returning partial matches and single letters.

// 500 Random Letters
string letters = "bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio"

// Dictionary Words List
string[] words = File.ReadAllText(@"C:\dictionarywords.txt").Split('\n');

// Word Matches List
List<string> matches = new List<string>();

// Check for Word matches in Letters
foreach (var x in words)
{
    // Add to list if match
    if (letters.Contains(x))
    {
        matches.Add(x);
    }
}

// Return Matched Words if 5 or greater
if (matches.Count() >= 5)
{
    textBox.Text = string.Join("\n", matches);
}

Examples

Word matches found by eye:

lid

hot

gum

hose

hat

Code Match Returns:

my

up

so

c

et

ms

am

me

s

x

n

b

...


问:
How to force tomcat to reload recently compiled class/war files
We have a set of running servlets on a tomcat engine. When we compile a java file and build the war, tomcat takes an indeterminate amount of time to reload it. Sometimes 3 seconds, sometimes 30, etc. Current workaround is to stop tomcat and restart it using a shell script. We set up the autodeploy and reloadable flag to true but it is not working reliably. Any idea how to make this happen? Pointers appreciated, too. This is about tomcat v6.0.20 on ubuntu.

Here is an extract of our conf/server.xml file:

```<code><Engine name="Catalina" defaultHost="localhost">

  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
         resourceName="UserDatabase"/>

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true"
        xmlValidation="false" xmlNamespaceAware="false">

    <DefaultContext reloadable="true">
    </DefaultContext>

    <!-- SingleSignOn valve, share authentication between web applications
         Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->

  </Host>
</Engine>
</code>```

答:
One possibility is to send an appropriate request to the Tomcat Manager App; e.g. something like this:</p>

```<code>http://localhost:8080/manager/text/reload?path=/examples
</code>```

Body:
We have a set of running servlets on a tomcat engine. When we compile a java file and build the war, tomcat takes an indeterminate amount of time to reload it. Sometimes 3 seconds, sometimes 30, etc. Current workaround is to stop tomcat and restart it using a shell script. We set up the autodeploy and reloadable flag to true but it is not working reliably. Any idea how to make this happen? Pointers appreciated, too. This is about tomcat v6.0.20 on ubuntu.

Here is an extract of our conf/server.xml file:

<Engine name="Catalina" defaultHost="localhost">

  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
         resourceName="UserDatabase"/>

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true"
        xmlValidation="false" xmlNamespaceAware="false">

    <DefaultContext reloadable="true">
    </DefaultContext>

  </Host>
</Engine>

Body:
One possibility is to send an appropriate request to the Tomcat Manager App; e.g. something like this:

http://localhost:8080/manager/text/reload?path=/examples


答:
From http://www.cpearson.com/excel/ShellAndWait.aspx

The VBA Shell function can be used to start an external program or perform any operation for which you would normally use the Run item on the Windows start menu.

  The Shell function starts the command text and then immediately returns control back to the calling VBA code -- it does not wait for the command used in Shell to terminate.

If this is what you want, use Shell.

```<code>' example Access 2010 32bit
Const ACCESS_PATH = """C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE"""

Shell ACCESS_PATH & " """ & strDbName & """"
</code>```

Title: Open DBs in parallel using VBA

Body:
I have an Access database which is used to calculate performance scores for a large number of people for each day of the week.

Due to the size of the dataset the procedure runs quite slowly. As a potential way to speed this up I am considering a process that would have 5 separate databases that each calculate the scores for one day.

I have written the below VBA code that just opens all of these DBs (Once each DB is open it has it's own autoExec macro that will kick off it's own procedure).

Sub DBloop()
 Dim dbArr As Variant
 Dim i As Integer

 dbArr = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

 For i = 0 To UBound(dbArr)
     openDBs CStr(dbArr(i))
 Next
End Sub

Sub openDBs(dbname As String)
 Dim acc As Access.Application
 Dim DBpath As String
 Dim strDbName As String

 DBpath = "H:\Performance Test\"
 strDbName = DBpath & dbname & ".accdb"

 Set acc = New Access.Application
 acc.Visible = True
 acc.OpenCurrentDatabase strDbName, False
End Sub

Unfortunately, what is happening is that as each DB is opened, the initial procedure is waiting for the autoExec macro of that DB to complete before opening the next one. Does anyone know if there is a workaround for this?

Body:
From http://www.cpearson.com/excel/ShellAndWait.aspx

The VBA Shell function can be used to start an external program or perform any operation for which you would normally use the Run item on the Windows start menu.

  The Shell function starts the command text and then immediately returns control back to the calling VBA code -- it does not wait for the command used in Shell to terminate.

If this is what you want, use Shell.

' example Access 2010 32bit
Const ACCESS_PATH = """C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE"""

Shell ACCESS_PATH & " """ & strDbName & """"


问:
How do I check if an input is an integer or not in python?
So I am trying for my program to print the message "That is not an integer!" if the user inputs something that is not an integer basically, I thought this was how you would do that but apparently isn't, could anyone tell me what I am doing wrong please?</p>

```<code>user_number = input()
if type(user_number) != int:
  print("That's not an integer number.")
</code>```

答:
You could try to convert the input to integer with try/except:

```<code>user_number = input()

try:
    int(user_number)
except:
    print("That's not an integer number.")
</code>```

Body:
So I am trying for my program to print the message "That is not an integer!" if the user inputs something that is not an integer basically, I thought this was how you would do that but apparently isn't, could anyone tell me what I am doing wrong please?

user_number = input()
if type(user_number) != int:
  print("That's not an integer number.")

Body:
You could try to convert the input to integer with try/except:

user_number = input()

try:
    int(user_number)
except:
    print("That's not an integer number.")


问:
Rename columns in Shiny dashboard datatable
I have a datatable in my Shiny app. By default, the column names are the column names of the data set.
I want to change the column names of the display, without touching the data set itself.

I found this documentation which is exactly what I need, but I'm not sure how to convert this to R syntax.

This is the current way I render the table:

```<code>output$score_data_table <- renderDataTable({
    selectedArea_overview_TC()},
    options = list(orderClasses = TRUE,
                   lengthMenu = list(c(15,25,50,100,-1), c('15','25','50','100','All')),
                   pageLength = 15,
                   order=list(1, 'desc'))
)
</code>```

I've tried adding the columnDefs option in several ways but nothing worked.

Any hint would be greatly appreciated!

答:
I fell in the same trap. The documentation you actually need is columns.title.

```<code>output$score_data_table <- renderDataTable({
  selectedArea_overview_TC()
  },
  options = list(orderClasses = TRUE,
                 lengthMenu = list(c(15,25,50,100,-1), c('15','25','50','100','All')),
                 pageLength = 15,
                 order=list(1, 'desc')
                 columns = list(
                   list(title = 'newnameforcol1'),
                   NULL, # skip column 2
                   list(title = 'newnameforcol3'),
                 )
  )
)
</code>```

Title might work with columnDefs as well. I'm not sure.

Body:
I have a datatable in my Shiny app. By default, the column names are the column names of the data set.
I want to change the column names of the display, without touching the data set itself.

I found this documentation which is exactly what I need, but I'm not sure how to convert this to R syntax.

This is the current way I render the table:

output$score_data_table <- renderDataTable({
    selectedArea_overview_TC()},
    options = list(orderClasses = TRUE,
                   lengthMenu = list(c(15,25,50,100,-1), c('15','25','50','100','All')),
                   pageLength = 15,
                   order=list(1, 'desc'))
)

I've tried adding the columnDefs option in several ways but nothing worked.

Any hint would be greatly appreciated!

Body:
I fell in the same trap. The documentation you actually need is columns.title.

output$score_data_table <- renderDataTable({
  selectedArea_overview_TC()
  },
  options = list(orderClasses = TRUE,
                 lengthMenu = list(c(15,25,50,100,-1), c('15','25','50','100','All')),
                 pageLength = 15,
                 order=list(1, 'desc')
                 columns = list(
                   list(title = 'newnameforcol1'),
                   NULL, # skip column 2
                   list(title = 'newnameforcol3'),
                 )
  )
)

Title might work with columnDefs as well. I'm not sure.


问:
Maven2 Eclipse integration
There seem to be two rival  Eclipse plugins for integrating with Maven:
m2Eclipse
and
q4e.

Has anyone recently evaluated or used these plugins?

Why would I choose one or the other?

答:
My 2cents,

I am using eclipse for some months now with m2eclipse integration. It's easy to use and straight forward. Once you associate your project to maven and update the dependencies using m2eclipse, any change to pom.xml are reflected to entire project, even Java version definition causes it to be compiled in right JRE (if you have it installed, and properly configured into eclipse.)

Another advantage I found is the maven plug-ins are easy to use integrated with eclipse (jetty being my best example, again, properly configured you can easily integrate maven, jetty-plug-in and Eclipse Debugger)

Compilation, packaging and all other maven features are equally easy to use with a couple clicks or shortcuts.

About q4e I have been reading a lot of good stuff about it and seems the next versions will do a lot more than m2eclipse, with a better dependency management and even visual graphs (!) but the general opinion is that m2eclipse is still better than q4e but q4e is getting better each new version and maybe will surpass m2eclipse soon.

OwnerDisplayName: David

Title: Maven2 Eclipse integration

OwnerDisplayName: Fernando Barrocal


问:
How to properly mock and unit test
I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.

I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.

I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

It feels like the code is just testing that the mocking framework is working.

In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.

```<code>    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }
</code>```

答:
You are right: the simplicity of the service makes these tests uninteresting. It is not until you get more business logic in the service, that you will gain value from the tests.

You might consider some tests like these:

```<code>CreateUser_fails_if_email_is_invalid()
CreateUser_fails_if_username_is_empty()
</code>```

Another comment: it looks like a code-smell, that your methods return booleans to indicate success or failure. You might have a good reason to do it, but usually you should let the exceptions propagate out. It also makes it harder to write good tests, since you will have problems detecting whether your method failed for the "right reason", f.x. you might write the CreateUser_fails_if_email_is_invalid()-test like this:

```<code>[Test]
public void CreateUser_fails_if_email_is_invalid()
{
    bool result = userSvc.CreateUser(userWithInvalidEmailAddress);
    Assert.That(result, Is.False);
}
</code>```

and it would probably work with your existing code. Using the TDD Red-Green-Refactor-cycle would mitigate this problem, but it would be even better to be able to actually detect that the method failed because of the invalid email, and not because of another problem.

OwnerDisplayName: Ben Robbins

Title: How to properly mock and unit test

Body:
I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.

I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.

I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

It feels like the code is just testing that the mocking framework is working.

In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.

    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }

Body:
You are right: the simplicity of the service makes these tests uninteresting. It is not until you get more business logic in the service, that you will gain value from the tests.

You might consider some tests like these:

CreateUser_fails_if_email_is_invalid()
CreateUser_fails_if_username_is_empty()

Another comment: it looks like a code-smell, that your methods return booleans to indicate success or failure. You might have a good reason to do it, but usually you should let the exceptions propagate out. It also makes it harder to write good tests, since you will have problems detecting whether your method failed for the "right reason", f.x. you might write the CreateUser_fails_if_email_is_invalid()-test like this:

[Test]
public void CreateUser_fails_if_email_is_invalid()
{
    bool result = userSvc.CreateUser(userWithInvalidEmailAddress);
    Assert.That(result, Is.False);
}

and it would probably work with your existing code. Using the TDD Red-Green-Refactor-cycle would mitigate this problem, but it would be even better to be able to actually detect that the method failed because of the invalid email, and not because of another problem.

OwnerDisplayName: Rasmus Faber

LastEditorDisplayName: Rasmus Faber


问:
Android - how to get ListView to line up underneath Text View
I am attempting to put a ListView beneath a Text View in an Android App. However, the first line of the ListView shows up on the same line as the TextView. How do I get this to move underneath?

Here is the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <TextView android:id="@+id/android:question"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dummy_question" />
    <ListView android:id="@+id/android:list"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView android:id="@+id/android:empty"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no_notes"/>

</LinearLayout>
</code>```

答:
The problem is only that in linearlayout put:

android:orientation=vertical

Body:
I am attempting to put a ListView beneath a Text View in an Android App. However, the first line of the ListView shows up on the same line as the TextView. How do I get this to move underneath?

Here is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <TextView android:id="@+id/android:question"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dummy_question" />
    <ListView android:id="@+id/android:list"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView android:id="@+id/android:empty"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no_notes"/>

</LinearLayout>


问:
Connect ASP NET CORE 2.0 With Oracle
When I try connect ASP NET CORE 2.0 to Oracle using the System.Data.Oracle Nugget, I receive an error. I understand that the issue is about OCI.dll.

答: I did find one solution for that, this error happens because Oracle is not installed in Windows OS. The nugget work when Oracle client (11 or 12) is installed on local, the 'OCI.dll' is copy to local and fix the issue. But in Apple not work, (I do not know how to install Oracle in apple)</p>

Title: Connect ASP NET CORE 2.0 With Oracle


问:
The GROUP BY clause must be used with aggregate functions?
GROUP BY clause  need an aggregate ?</p>

答:
No, an aggregate query doesn't need a GROUP BY clause. But if no such clause is present the query only generates a single result row, aggregating the entire table.

It's sort of like there was an implicit GROUP BY 'nothing' clause inserted by the DBMS if you don't provide your own.

Body: GROUP BY clause  need an aggregate ?


问:
Fit text perfectly inside a div (height and width) without affecting the size of the div
I apologise in advance as I know this question has come up many times before but I just can't seem to find the right solution (and believe me I've tried a few!)

Basically it's the old "Fit text perfectly inside a div without affecting the size of the div". And unless I'm a complete numpty, I believe CSS has no way of doing this. So what I mean basically is rather than doing something like:

```<code>#someDiv {
font-size: 12px;
}
</code>```

or...

```<code>#someDiv {
font-size: 1em;
}
</code>```

...I want to be able to do something like this:

```<code>#someDiv {
font-size: fluid;
}
</code>```

...meaning that whatever text this div contains, scale it to fit perfectly from left to right and top to bottom with no overflow or whitespace.

After trawling through countless websites looking for this CSS solution, I've now accepted that CSS isn't capable of this ...so, enter jQuery.

I've found several jQuery solutions online but they will only scale the text to fit the width, but I want it to scale to the height as well. So effectively I want to say to jQuery:

"jQuery, find $(this) div and whatever text is inside it I want you to scale it so that it fills the entire height and width of the div as tightly as possible".

In case I haven't explained myself very well, I've attached a graphic explaining the problem I'm facing and the solution I'm looking for.

Any help would be much appreciated. Thank you.

答:
Here's a slightly modified version of the given answers.

Requirements :

The class containing text has the "resize" class.

it contains height and width (%, px, whatever...)

What changes in this version ?

I added resizing ( by binding the event resize to the function) autoSizeText. This is far from ideal, but if we don't resize a lot, it should be ok.

In previous versions, text is only getting smaller. Now it tries to find the biggest font without going outside the div.

Note:

I don't claim the code is production ready. But if you find something you can enhance, please share it with the community.

var autoSizeText = function () {
    var el, elements, _i, _len;
    elements = $('.resize');
    if (elements.length < 0) {
        return;
    }
    for (_i = 0, _len = elements.length; _i < _len; _i++) {
        el = elements[_i];
        dichoFit = function (el) {

            diminishText = function () {
                var elNewFontSize;
                elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';

                return $(el).css('font-size', elNewFontSize);
            };
            augmentText = function () {
                var elNewFontSize;
                elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) + 1) + 'px';

                return $(el).css('font-size', elNewFontSize);
            };

            diminishText();
            while (el.scrollHeight < el.offsetHeight) {
                augmentText();
            }
            augmentText();
            while (el.scrollHeight > el.offsetHeight) {
                diminishText();
            }

        }
        dichoFit(el);
    }
};

$(document).ready(function () {
    autoSizeText();
    $(window).resize(function resizeText(){
        autoSizeText()
    })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sizable{
 width: 50vw;
 height: 50vh;
 border: 2px solid darkred;
}</code>```

  I am a sizable div and I have explicit width and height.

```

Body:
I apologise in advance as I know this question has come up many times before but I just can't seem to find the right solution (and believe me I've tried a few!)

Basically it's the old "Fit text perfectly inside a div without affecting the size of the div". And unless I'm a complete numpty, I believe CSS has no way of doing this. So what I mean basically is rather than doing something like:

#someDiv {
font-size: 12px;
}

or...

#someDiv {
font-size: 1em;
}

...I want to be able to do something like this:

#someDiv {
font-size: fluid;
}

...meaning that whatever text this div contains, scale it to fit perfectly from left to right and top to bottom with no overflow or whitespace.

After trawling through countless websites looking for this CSS solution, I've now accepted that CSS isn't capable of this ...so, enter jQuery.

I've found several jQuery solutions online but they will only scale the text to fit the width, but I want it to scale to the height as well. So effectively I want to say to jQuery:

"jQuery, find $(this) div and whatever text is inside it I want you to scale it so that it fills the entire height and width of the div as tightly as possible".

In case I haven't explained myself very well, I've attached a graphic explaining the problem I'm facing and the solution I'm looking for.

Any help would be much appreciated. Thank you.

Body:
Here's a slightly modified version of the given answers.

Requirements :

The class containing text has the "resize" class.

it contains height and width (%, px, whatever...)

What changes in this version ?

I added resizing ( by binding the event resize to the function) autoSizeText. This is far from ideal, but if we don't resize a lot, it should be ok.

In previous versions, text is only getting smaller. Now it tries to find the biggest font without going outside the div.

Note:

I don't claim the code is production ready. But if you find something you can enhance, please share it with the community.

var autoSizeText = function () {
    var el, elements, _i, _len;
    elements = $('.resize');
    if (elements.length < 0) {
        return;
    }
    for (_i = 0, _len = elements.length; _i < _len; _i++) {
        el = elements[_i];
        dichoFit = function (el) {

            diminishText = function () {
                var elNewFontSize;
                elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';

                return $(el).css('font-size', elNewFontSize);
            };
            augmentText = function () {
                var elNewFontSize;
                elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) + 1) + 'px';

                return $(el).css('font-size', elNewFontSize);
            };

            diminishText();
            while (el.scrollHeight < el.offsetHeight) {
                augmentText();
            }
            augmentText();
            while (el.scrollHeight > el.offsetHeight) {
                diminishText();
            }

        }
        dichoFit(el);
    }
};

$(document).ready(function () {
    autoSizeText();
    $(window).resize(function resizeText(){
        autoSizeText()
    })
});

.sizable{
 width: 50vw;
 height: 50vh;
 border: 2px solid darkred;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div class='sizable resize'>
  I am a sizable div and I have explicit width and height.
</div>


问:
rc.exe no longer found in VS 2015 Command Prompt
I just installed Windows 10 Creators Update (version 10.0.15063).

I have multiple versions of Visual Studio installed (2012, 2013, 2015 and 2017). I installed VS 2017 only a couple weeks ago.

Problem

CMake (version 3.8.1) no longer finds the C/C++ compiler when run inside a "VS2015 x64 Native Command Prompt" (it does work properly when run inside a VS 2017 command prompt).

Reproduction

Content of CMakeLists.txt:

project (test)
add_executable (test test.cpp)
```

<p>(Content of <code>test.cpp</code> is irrelevant.)</p>

<p>CMake invocation, in a VS2015 x64 Native Command Prompt:</p>

<pre class="lang-none prettyprint-override"><code>> mkdir build
> cd build
> cmake -G "Visual Studio 14 2015 Win64" ..
</code>```

CMake output:

-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:1 (project):
  No CMAKE_C_COMPILER could be found.

CMake Error at CMakeLists.txt:1 (project):
  No CMAKE_CXX_COMPILER could be found.

-- Configuring incomplete, errors occurred!
See also "D:/dev/cmaketest/build/CMakeFiles/CMakeOutput.log".
See also "D:/dev/cmaketest/build/CMakeFiles/CMakeError.log".
```

<h3>Analysis</h3>

<p>The reason of the failure is clear when looking at <code>CMakeFiles/CMakeError.log</code>:</p>

<pre class="lang-none prettyprint-override"><code>ClCompile:
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64\CL.exe /c /nologo /W0 /WX- /Od /D _MBCS /Gm- /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Zc:inline /Fo"Debug\\" /Fd"Debug\vc140.pdb" /Gd /TC /errorReport:queue CMakeCCompilerId.c
  CMakeCCompilerId.c
Link:
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64\link.exe /ERRORREPORT:QUEUE /OUT:".\CompilerIdC.exe" /INCREMENTAL:NO /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /PDB:".\CompilerIdC.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:".\CompilerIdC.lib" /MACHINE:X64 Debug\CMakeCCompilerId.obj
LINK : fatal error LNK1158: cannot run 'rc.exe' [D:\dev\cmaketest\build\CMakeFiles\3.8.1\CompilerIdC\CompilerIdC.vcxproj]
</code>```

rc.exe (Resource Compiler) is not found. Indeed, in the same VS 2015 command prompt:

> where rc.exe
INFO: Could not find files for the given pattern(s).
```

<p>While it <em>is</em> found in a VS 2013 command prompt:</p>

<pre class="lang-none prettyprint-override"><code>> where rc.exe
C:\Program Files (x86)\Windows Kits\8.1\bin\x64\rc.exe
C:\Program Files (x86)\Windows Kits\8.1\bin\x86\rc.exe
</code>```

and a VS 2017 command prompt:

> where rc.exe
C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64\rc.exe
```

<p>Checking the content of the <code>PATH</code> environment variables in various VS command prompts:</p>

<ul>
<li><p>Inside a VS 2013 command prompt, <code>PATH</code> contains</p>

<pre class="lang-none prettyprint-override"><code>C:\Program Files (x86)\Windows Kits\8.1\bin\x64
</code>```

Inside a VS 2017 command prompt, PATH contains

C:\Program Files (x86)\Windows Kits\10\bin\x64
C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64
```</li>
<li><p>But inside a VS 2015 command prompt, <code>PATH</code> only contains</p>

<pre class="lang-none prettyprint-override"><code>C:\Program Files (x86)\Windows Kits\10\bin\x64
</code>```

which does not contain rc.exe.

Questions

Is this a known issue or is it specific to my system?

What could Windows 10 Creators Update possibly install, uninstall or alter in the system (perhaps something related to Windows SDKs) that would trigger this problem?

What is a clean way to resolve this?

Edit: Installed VS 2017 components:

答:
For whatever reason the built-in Tools (1.4.1) and Windows 10 SDK (10.0.14393) installer didn't work for me:

C:\Program Files (x86)\Windows Kits\10\bin\x86 got populated mid-install (success!)

...then de-populated (sorrow!)

And eventually the installer returned error -2147023293/0x80048646.

The "Windows 10 SDK (ver. 10.0.14393.795)" installer from the Windows SDK and emulator archive worked though: C:\Program Files (x86)\Windows Kits\10\bin\x86 gets and stays populated, including rc.exe.

Windows 7 x64, Visual Studio Professional 2015 Update 3.

Body:
I just installed Windows 10 Creators Update (version 10.0.15063).

I have multiple versions of Visual Studio installed (2012, 2013, 2015 and 2017). I installed VS 2017 only a couple weeks ago.

Problem

CMake (version 3.8.1) no longer finds the C/C++ compiler when run inside a "VS2015 x64 Native Command Prompt" (it does work properly when run inside a VS 2017 command prompt).

Reproduction

Content of CMakeLists.txt:

project (test)
add_executable (test test.cpp)

(Content of test.cpp is irrelevant.)

CMake invocation, in a VS2015 x64 Native Command Prompt:

> mkdir build
> cd build
> cmake -G "Visual Studio 14 2015 Win64" ..

CMake output:

-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:1 (project):
  No CMAKE_C_COMPILER could be found.

CMake Error at CMakeLists.txt:1 (project):
  No CMAKE_CXX_COMPILER could be found.

-- Configuring incomplete, errors occurred!
See also "D:/dev/cmaketest/build/CMakeFiles/CMakeOutput.log".
See also "D:/dev/cmaketest/build/CMakeFiles/CMakeError.log".

Analysis

The reason of the failure is clear when looking at CMakeFiles/CMakeError.log:

ClCompile:
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64\CL.exe /c /nologo /W0 /WX- /Od /D _MBCS /Gm- /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Zc:inline /Fo"Debug\\" /Fd"Debug\vc140.pdb" /Gd /TC /errorReport:queue CMakeCCompilerId.c
  CMakeCCompilerId.c
Link:
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64\link.exe /ERRORREPORT:QUEUE /OUT:".\CompilerIdC.exe" /INCREMENTAL:NO /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /PDB:".\CompilerIdC.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:".\CompilerIdC.lib" /MACHINE:X64 Debug\CMakeCCompilerId.obj
LINK : fatal error LNK1158: cannot run 'rc.exe' [D:\dev\cmaketest\build\CMakeFiles\3.8.1\CompilerIdC\CompilerIdC.vcxproj]

rc.exe (Resource Compiler) is not found. Indeed, in the same VS 2015 command prompt:

> where rc.exe
INFO: Could not find files for the given pattern(s).

While it is found in a VS 2013 command prompt:

> where rc.exe
C:\Program Files (x86)\Windows Kits\8.1\bin\x64\rc.exe
C:\Program Files (x86)\Windows Kits\8.1\bin\x86\rc.exe

and a VS 2017 command prompt:

> where rc.exe
C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64\rc.exe

Checking the content of the PATH environment variables in various VS command prompts:

Inside a VS 2013 command prompt, PATH contains

C:\Program Files (x86)\Windows Kits\8.1\bin\x64

Inside a VS 2017 command prompt, PATH contains

C:\Program Files (x86)\Windows Kits\10\bin\x64
C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64

But inside a VS 2015 command prompt, PATH only contains

C:\Program Files (x86)\Windows Kits\10\bin\x64

which does not contain rc.exe.

Questions

Is this a known issue or is it specific to my system?

What could Windows 10 Creators Update possibly install, uninstall or alter in the system (perhaps something related to Windows SDKs) that would trigger this problem?

What is a clean way to resolve this?

Edit: Installed VS 2017 components:


问:
Yii2 - Stop Field validation if calendar is open
I have a Yii2 active form which includes a field with datepicker. My form is using following attributes:

```<code><?php $form = ActiveForm::begin([
            'id' => 'campaign-form',
            'enableClientValidation' => true,
            'fieldConfig' => [
                'options' => ['class' => 'gg-create-group'],
                'labelOptions' => ['class' => null],
            ],
            'options' => [
                'autocomplete' => 'off',
                'enctype' => 'multipart/form-data',
            ],
        ]);
        ?>
</code>```

I have a field using jquery datepicker, the issue is each time I click on the arrows to navigate through the months in the calendar, client validation is triggered an a error is shown:

I need to stop the error message if the calendar is open and I am using the calendar navigation.

I know I can turn off client validation using:

```<code>enableClientValidation => false
</code>```

But I want to keep client validation. I am wondering if Yii javascript script: $yiiform has an option to do that?

答:
I found a solution. I can use validationOnBlur, if I set it to false on specific field it fixes the issue.</p>

```<code><?php echo $form->field($model, 'client_end_date',
['validateOnBlur' => false])->textInput(['readonly' => 'readonly']); ?>
</code>```

Body:
I have a Yii2 active form which includes a field with datepicker. My form is using following attributes:

<?php $form = ActiveForm::begin([
            'id' => 'campaign-form',
            'enableClientValidation' => true,
            'fieldConfig' => [
                'options' => ['class' => 'gg-create-group'],
                'labelOptions' => ['class' => null],
            ],
            'options' => [
                'autocomplete' => 'off',
                'enctype' => 'multipart/form-data',
            ],
        ]);
        ?>

I have a field using jquery datepicker, the issue is each time I click on the arrows to navigate through the months in the calendar, client validation is triggered an a error is shown:

I need to stop the error message if the calendar is open and I am using the calendar navigation.

I know I can turn off client validation using:

enableClientValidation => false

But I want to keep client validation. I am wondering if Yii javascript script: $yiiform has an option to do that?

Body:
I found a solution. I can use validationOnBlur, if I set it to false on specific field it fixes the issue.

<?php echo $form->field($model, 'client_end_date',
['validateOnBlur' => false])->textInput(['readonly' => 'readonly']); ?>


问:
How do you find out which version of GTK+ is installed on Ubuntu?
I need to determine which version of GTK+ is installed on Ubuntu

Man does not seem to help

答:
This will get the version of the GTK libraries for GTK 2, 3, and 4.

```<code>dpkg -l | egrep "libgtk(2.0-0|-3-0|-4)"
</code>```

As major versions are parallel installable, you may have several of them on your system, which is my case, so the above command returns this on my Ubuntu Trusty system:

```<code>ii  libgtk-3-0:amd64                                      3.10.8-0ubuntu1.6                                   amd64        GTK+ graphical user interface library
ii  libgtk2.0-0:amd64                                     2.24.23-0ubuntu1.4                                  amd64        GTK+ graphical user interface library
</code>```

This means I have GTK+ 2.24.23 and 3.10.8 installed.

If what you want is the version of the development files, use:

pkg-config --modversion gtk+-2.0 for GTK 2

pkg-config --modversion gtk+-3.0 for GTK 3

pkg-config --modversion gtk4 for GTK 4

(This changed because the + from GTK+ was dropped a while ago.)

OwnerDisplayName: Craig Angus

LastEditorDisplayName: Craig Angus

Body:
This will get the version of the GTK libraries for GTK 2, 3, and 4.

dpkg -l | egrep "libgtk(2.0-0|-3-0|-4)"

As major versions are parallel installable, you may have several of them on your system, which is my case, so the above command returns this on my Ubuntu Trusty system:

ii  libgtk-3-0:amd64                                      3.10.8-0ubuntu1.6                                   amd64        GTK+ graphical user interface library
ii  libgtk2.0-0:amd64                                     2.24.23-0ubuntu1.4                                  amd64        GTK+ graphical user interface library

This means I have GTK+ 2.24.23 and 3.10.8 installed.

If what you want is the version of the development files, use:

pkg-config --modversion gtk+-2.0 for GTK 2

pkg-config --modversion gtk+-3.0 for GTK 3

pkg-config --modversion gtk4 for GTK 4

(This changed because the + from GTK+ was dropped a while ago.)


问:
Ansible - dynamically prompt vault password when needed
Context

In my company, we have a shared repository containing our ansible script for our servers. I would like to introduce vault variables to handle services password in the near future. For now, we use encrypted password prompts at the beginning of our playbooks. This solution is annoying (it asked for 3 passwords on some playbooks).

Need

As most of our ansible users are no experts, I would like them to be able to run playbooks smoothly. It means ansible-playbook commands should be short and work without any mandatory parameters (e.g. no --ask-sudo-pass and whatnot). It also means I prefer prompting for vault password at the beginning of a playbook only when it’s needed.
Moreover, I do not want to use ansible password file, because it is not easily shareable and I don’t like the idea of having a cleartext password file on all our ansible users computers.

Problem

Adding --ask-vault-pass for every concerned playbooks is not an option. Our ansible users will not understand why sometimes this parameter is needed and why sometimes it’s not. On the contrary, asking the vault password for every playbook is a burden, because we have a lot of playbooks and sudo password is already asked each time too.

I tried to achieve the following solution, using prompts and various options. Nothing seems to work. Documentation does not explain how to do this:

The best solution (according to me)

Let’s look at this main.yml file:

```<code>- import_tasks: foo.yml
  tags: always

- import_tasks: bar.yml
  tags: bar

# Only this tasks uses a vault encrypted variable
- import_tasks: baz.yml
  tags: [baz, vault]
</code>```

Now, there’s a playbook.yml, importing this main.yml file.

In a perfect world, I would like this to happen:

example1:

```<code>ansible-playbook -i prod playbook.yml

Vault password:
</code>```

example2:

```<code>ansible-playbook -i prod playbook.yml --tags baz

Vault password:
</code>```

example3:

```<code>ansible-playbook -i prod playbook.yml --tags foo

# it runs without asking for vault password, because no tasks needing vault
# password will be run
</code>```

Question

How can I configure ansible to ask for vault password only when it is needed (meaning: every time a vault encrypted variable is encountered)? Is it even possible? If not, what workaround would be viable given my situation?

Thanks.

答:
I found a workaround.

The idea is to always load all passwords (including sudo) from an ansible vault file, needing only the vault password for each playbook. It means all machines should have the same deployer user password. This is even simpler than before, because there’s a single master password (the vault password) to control them all.

This is how it’s done:

ansible.cfg:

```<code>[privilege_escalation]
become_ask_pass = False
become = True

[defaults]
ask_vault_pass = True
</code>```

vars/vault/env:

```<code>_vault:
  sudo: !vault |
        $ANSIBLE_VAULT;1.1;AES256
        BLAHBLAHBLAH
  another_pass: !vault |
                $ANSIBLE_VAULT;1.1;AES256
                ANOTHERENCRYPTEDPASSWORD
</code>```

And for each playbook:

```<code># Playbook stuff
# [...]

vars:
  ansible_become_pass: "{{ _vault.sudo }}"
vars_files:
  # env var is set dynamically in inventory file, so I can have different password per env.
  # If the file is not found, it loads an empty null file
  - [ "vars/vault/{{ env }}", "vars/null"]

# [...] Loading other var files
</code>```

Now, a simple ansible-playbook -i env/prod myPlayBook.yml will only ask for the vault password, no prompt for sudo or anything else. It’s consistent and easy to share (only the encrypted password file and the vault password must be shared).

Body:
Context

In my company, we have a shared repository containing our ansible script for our servers. I would like to introduce vault variables to handle services password in the near future. For now, we use encrypted password prompts at the beginning of our playbooks. This solution is annoying (it asked for 3 passwords on some playbooks).

Need

As most of our ansible users are no experts, I would like them to be able to run playbooks smoothly. It means ansible-playbook commands should be short and work without any mandatory parameters (e.g. no --ask-sudo-pass and whatnot). It also means I prefer prompting for vault password at the beginning of a playbook only when it’s needed.
Moreover, I do not want to use ansible password file, because it is not easily shareable and I don’t like the idea of having a cleartext password file on all our ansible users computers.

Problem

Adding --ask-vault-pass for every concerned playbooks is not an option. Our ansible users will not understand why sometimes this parameter is needed and why sometimes it’s not. On the contrary, asking the vault password for every playbook is a burden, because we have a lot of playbooks and sudo password is already asked each time too.

I tried to achieve the following solution, using prompts and various options. Nothing seems to work. Documentation does not explain how to do this:

The best solution (according to me)

Let’s look at this main.yml file:

- import_tasks: foo.yml
  tags: always

- import_tasks: bar.yml
  tags: bar

# Only this tasks uses a vault encrypted variable
- import_tasks: baz.yml
  tags: [baz, vault]

Now, there’s a playbook.yml, importing this main.yml file.

In a perfect world, I would like this to happen:

example1:

ansible-playbook -i prod playbook.yml

Vault password:

example2:

ansible-playbook -i prod playbook.yml --tags baz

Vault password:

example3:

ansible-playbook -i prod playbook.yml --tags foo

# it runs without asking for vault password, because no tasks needing vault
# password will be run

Question

How can I configure ansible to ask for vault password only when it is needed (meaning: every time a vault encrypted variable is encountered)? Is it even possible? If not, what workaround would be viable given my situation?

Thanks.

Body:
I found a workaround.

The idea is to always load all passwords (including sudo) from an ansible vault file, needing only the vault password for each playbook. It means all machines should have the same deployer user password. This is even simpler than before, because there’s a single master password (the vault password) to control them all.

This is how it’s done:

ansible.cfg:

[privilege_escalation]
become_ask_pass = False
become = True

[defaults]
ask_vault_pass = True

vars/vault/env:

_vault:
  sudo: !vault |
        $ANSIBLE_VAULT;1.1;AES256
        BLAHBLAHBLAH
  another_pass: !vault |
                $ANSIBLE_VAULT;1.1;AES256
                ANOTHERENCRYPTEDPASSWORD

And for each playbook:

# Playbook stuff
# [...]

vars:
  ansible_become_pass: "{{ _vault.sudo }}"
vars_files:
  # env var is set dynamically in inventory file, so I can have different password per env.
  # If the file is not found, it loads an empty null file
  - [ "vars/vault/{{ env }}", "vars/null"]

# [...] Loading other var files

Now, a simple ansible-playbook -i env/prod myPlayBook.yml will only ask for the vault password, no prompt for sudo or anything else. It’s consistent and easy to share (only the encrypted password file and the vault password must be shared).


问:
How can 3-SAT be reduced to Independent set?
I was reading about NP hardness from here (pages 8, 9) and in the notes the author reduces a problem in 3-SAT form to a graph that can be used to solve the maximum independent set problem.

In the example, the author converts the following 3-SAT problem into a graph. The 3-SAT problem is:

```<code>(a ∨ b ∨ c) ∧ (b ∨ ~c ∨ ~d) ∧ (~a ∨ c ∨ d) ∧ (a ∨ ~b ∨ ~d)
</code>```

The equivalent graph generated is:

The author states that two nodes are connected by an edge if:

They correspond to literals in the same clause

They correspond to a variable and its inverse.

I am having trouble understanding how the author came up with these rules.

Why do we need to draw edges between a variable and its inverse?

Suppose there are two clauses and clause 1 has (a,b,~c) and clause 2 has (~a,b,c) to connect clause 1 to clause 2, why do we have to connect a and ~a? Why can't we connect a (clause 1) with c (clause 2) instead?

答:
I think what can clear the problem is reduction concept. Suppose you are familiar with a problem say X(i.e 3-SAT)[what it means familiar? You know how much is hard to solve X]. Also you are currently working to analysis another new problem say Y(i.e independent set)...

How can the knowledge of you about X help you to come up with Y? If you can find a relation(i.e reduction) between them, then you can use the knowledge about X to Y. Something like "Y is harder than X" or "Y is as hard as X". So what that solution wants to do is finding a relation between two problems.

In computability theory and computational complexity theory, a reduction is an algorithm for transforming one problem into another problem. A reduction from one problem to another may be used to show that the second problem is at least as difficult as the first.

Two rules you noted here is all of that(i.e the relation).

You cannot select two vertices of an edge simultaneously. Also you cannot set a variable and its negation TRUE simultaneously.

You must have a TRUE variable at a clause. Also to maximize the number of selected vertices you must select one node form each clauses.

This shows where these rules comes from.

PS: What here noted is not precise as a proof to solve the 3-SAT to Independent Set problem. This explanation was just for you to get more insight about what procedure the proofs want to do. The proof left to academic notes.

One another important thing in the reduction is its own time. On the other hand the reduction time(i.e time takes to convert a X instance to Y instance) must be less than the X problem time(o.w it dominates the X solution time).

Also There is some notation to show that X < Y with an other time order as index of <. Moreover, if you show that X < Y and Y < X. This means that these problems have equal hardness.

At the last point note that what quoted note said about reduction ...a reduction is an algorithm....

Body:
I was reading about NP hardness from here (pages 8, 9) and in the notes the author reduces a problem in 3-SAT form to a graph that can be used to solve the maximum independent set problem.

In the example, the author converts the following 3-SAT problem into a graph. The 3-SAT problem is:

(a ∨ b ∨ c) ∧ (b ∨ ~c ∨ ~d) ∧ (~a ∨ c ∨ d) ∧ (a ∨ ~b ∨ ~d)

The equivalent graph generated is:

The author states that two nodes are connected by an edge if:

They correspond to literals in the same clause

They correspond to a variable and its inverse.

I am having trouble understanding how the author came up with these rules.

Why do we need to draw edges between a variable and its inverse?

Suppose there are two clauses and clause 1 has (a,b,~c) and clause 2 has (~a,b,c) to connect clause 1 to clause 2, why do we have to connect a and ~a? Why can't we connect a (clause 1) with c (clause 2) instead?