问:
Google Scripts writing to Sheets
I have the script below to pull out information about google classrooms.
I seem to be bashing my head against a brick wall - how can I write the course.data into the google sheet I am creating?
Many thanks</p>

```<code>/**
 * Lists 100000 course names and ids.
 */
function listCourses() {
  var rows = 100000
  var columns = 5
  var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
  var spreadsheet = "ScriptClassroomCodes "+date

  var oldfiles = DriveApp.getFilesByName(spreadsheet);
  while (oldfiles.hasNext()) {
    var oldfile = oldfiles.next();
    oldfile.setTrashed(true);
}
  var optionalArgs = {
    pageSize: rows
  };
  SpreadsheetApp.create(spreadsheet, rows, columns)
  var currentfile = DriveApp.getFilesByName(spreadsheet);
  while (currentfile.hasNext()) {
    var file = currentfile.next();
    var sheetid = file.getId();
}

var sheet = SpreadsheetApp.openById(sheetid)

  var response = Classroom.Courses.list(optionalArgs);
  var courses = response.courses;
  if (courses && courses.length > 0) {
    for (i = 0; i < courses.length; i++) {
      var course = courses[i];
      Logger.log(course.name, course.alternateLink, course.enrollmentCode, course.courseState);
    }
  } else {
    Logger.log('No courses found.');
  }
}
</code>```

答:
I believe your goal as follows.

You want to put the values of course.name, course.alternateLink, course.enrollmentCode, course.courseState of each courses[i] to the created Spreadsheet by modifying your Google Apps Script.

For this, how about this answer?

Modification points:

SpreadsheetApp.create returns the Spreadsheet object. So you can use this.

When the values are put to the Spreadsheet in the for loop, the process cost will be high. So in this answer, I would like to prepare an array and put the values to the array in the for loop. And after the for loop, the values are put to the Spreadsheet using the array.

When above points are reflected to your script, it becomes as follows.

Modified script:

Please modify your script as follows.

From:

```<code>  SpreadsheetApp.create(spreadsheet, rows, columns)
  var currentfile = DriveApp.getFilesByName(spreadsheet);
  while (currentfile.hasNext()) {
    var file = currentfile.next();
    var sheetid = file.getId();
}

var sheet = SpreadsheetApp.openById(sheetid)

  var response = Classroom.Courses.list(optionalArgs);
  var courses = response.courses;
  if (courses && courses.length > 0) {
    for (i = 0; i < courses.length; i++) {
      var course = courses[i];
      Logger.log(course.name, course.alternateLink, course.enrollmentCode, course.courseState);
    }
  } else {
    Logger.log('No courses found.');
  }
</code>```

To:

```<code>var spreadsheet = SpreadsheetApp.create(spreadsheet, rows, columns);  // Modified
var sheet = spreadsheet.getSheets()[0];  // Added
var response = Classroom.Courses.list(optionalArgs);
var courses = response.courses;
if (courses && courses.length > 0) {
  var values = [];  // Added
  for (i = 0; i < courses.length; i++) {
    var course = courses[i];
    values.push([course.name, course.alternateLink, course.enrollmentCode, course.courseState]);  // Added
  }
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);  // Added
} else {
  Logger.log('No courses found.');
}
</code>```

In this case, the values are put to the 1st tab of the created Spreadsheet.

References:

create(name, rows, columns)

setValues(values)

Useful links for using Google Apps Script

Title: Google Scripts writing to Sheets

Body:
I have the script below to pull out information about google classrooms.
I seem to be bashing my head against a brick wall - how can I write the course.data into the google sheet I am creating?
Many thanks

/**
 * Lists 100000 course names and ids.
 */
function listCourses() {
  var rows = 100000
  var columns = 5
  var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
  var spreadsheet = "ScriptClassroomCodes "+date

  var oldfiles = DriveApp.getFilesByName(spreadsheet);
  while (oldfiles.hasNext()) {
    var oldfile = oldfiles.next();
    oldfile.setTrashed(true);
}
  var optionalArgs = {
    pageSize: rows
  };
  SpreadsheetApp.create(spreadsheet, rows, columns)
  var currentfile = DriveApp.getFilesByName(spreadsheet);
  while (currentfile.hasNext()) {
    var file = currentfile.next();
    var sheetid = file.getId();
}

var sheet = SpreadsheetApp.openById(sheetid)

  var response = Classroom.Courses.list(optionalArgs);
  var courses = response.courses;
  if (courses && courses.length > 0) {
    for (i = 0; i < courses.length; i++) {
      var course = courses[i];
      Logger.log(course.name, course.alternateLink, course.enrollmentCode, course.courseState);
    }
  } else {
    Logger.log('No courses found.');
  }
}

Body:
I believe your goal as follows.

You want to put the values of course.name, course.alternateLink, course.enrollmentCode, course.courseState of each courses[i] to the created Spreadsheet by modifying your Google Apps Script.

For this, how about this answer?

Modification points:

SpreadsheetApp.create returns the Spreadsheet object. So you can use this.

When the values are put to the Spreadsheet in the for loop, the process cost will be high. So in this answer, I would like to prepare an array and put the values to the array in the for loop. And after the for loop, the values are put to the Spreadsheet using the array.

When above points are reflected to your script, it becomes as follows.

Modified script:

Please modify your script as follows.

From:

  SpreadsheetApp.create(spreadsheet, rows, columns)
  var currentfile = DriveApp.getFilesByName(spreadsheet);
  while (currentfile.hasNext()) {
    var file = currentfile.next();
    var sheetid = file.getId();
}

var sheet = SpreadsheetApp.openById(sheetid)

  var response = Classroom.Courses.list(optionalArgs);
  var courses = response.courses;
  if (courses && courses.length > 0) {
    for (i = 0; i < courses.length; i++) {
      var course = courses[i];
      Logger.log(course.name, course.alternateLink, course.enrollmentCode, course.courseState);
    }
  } else {
    Logger.log('No courses found.');
  }

To:

var spreadsheet = SpreadsheetApp.create(spreadsheet, rows, columns);  // Modified
var sheet = spreadsheet.getSheets()[0];  // Added
var response = Classroom.Courses.list(optionalArgs);
var courses = response.courses;
if (courses && courses.length > 0) {
  var values = [];  // Added
  for (i = 0; i < courses.length; i++) {
    var course = courses[i];
    values.push([course.name, course.alternateLink, course.enrollmentCode, course.courseState]);  // Added
  }
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);  // Added
} else {
  Logger.log('No courses found.');
}

In this case, the values are put to the 1st tab of the created Spreadsheet.

References:

create(name, rows, columns)

setValues(values)

Useful links for using Google Apps Script


来源: stackexchange

问:
What type should I use for default arguments that depend on a type parameter?
I'm working on testing the validation logic for a form that has mostly simple text fields, but has some fields that have other kinds of values or require extra logic to set their value. I have an overloaded helper function that looks something like this:

type FieldSetter<T> = (field: Field, value: T) => void; // reusable utility functions to set field values

// overload for the most common case: value is a string, value and setter are optional
function testFieldValidation(
  field: Field,
  valueToTry?: string,
  setFieldValue?: FieldSetter<string>
): void;

// overload for the less common case: value is not a string, value and setter are required
function testFieldValidation<T>(
  field: Field,
  valueToTry: T,
  setFieldValue: FieldSetter<T>
): void;

// function implementation
function testFieldValidation(
  field: Field,
  valueToTry = '', // what should this type be? (defaults to string, which is wrong)
  setFieldValue = defaultStringSetter // and what should this type be?
): void {/* ... */}
```

<p>I'm trying to figure out what the type should be for the 2nd and 3rd arguments of <code>testFieldValidation</code>'s implementation. Here are some things I've already tried:</p>

<pre class="lang-js prettyprint-override"><code>// error: '""' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'
// This is just not how type parameters work, see https://github.com/microsoft/TypeScript/issues/21521
// .. though it'd be nice if TS could determine from the overloads that this is safe
function testFieldValidation<T = string>(
  field: Field,
  valueToTry: T = '',
  setFieldValue: FieldSetter<T> = defaultStringSetter
): void {/* ... */}

// error: this signature is incompatible with the first overload
function testFieldValidation(
  field: Field,
  valueToTry: unknown = '',
  setFieldValue: FieldSetter<unknown> = defaultStringSetter
): void {/* ... */}
</code>```

I'd prefer not to use any if I can get away with it. Anyone have any ideas?

A relevant GitHub issue, but no solutions are proposed: link

答:
Overload implementations are fairly loosely typed compared to the call signatures, in that as long as the implementation parameters and return types are at least as wide as the unions of the types in the call signatures, it should work.  So the following should type check:

```<code>// function implementation
function testFieldValidation<T>(
  field: Field,
  valueToTry: T | string = '',
  setFieldValue: FieldSetter<T> | FieldSetter<string> = defaultStringSetter
): void {/* ... */ }
</code>```

Whether or not this meets your needs is another story; inside the implementation the compiler will not have any idea that valueToTry and setFieldValue will be correlated to each other (e.g., if the first is string then the latter is definitely FieldSetter<string>), so you will find yourself either performing redundant checks or type assertions:

```<code>setFieldValue(field, valueToTry); // error!
// ----------------> ~~~~~~~~~~
// 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'

setFieldValue(field, valueToTry as T & string); // okay, asserted
</code>```

Speaking of type assertions, that's always a possibility when you know more about the types of things than the compiler does.  So, if you want to just tell the compiler that if the default "" is used then that "" will definitely be a valid T, that could work also:

```<code>// function implementation
function testFieldValidation<T extends unknown>(
  field: Field,
  valueToTry = '' as T,
  setFieldValue = defaultStringSetter as FieldSetter<T>
): void {/* ... */ }
</code>```

That might be easier to use inside the implementation, since the necessary assertions have already been done:

```<code>setFieldValue(field, valueToTry); // okay
</code>```

It's up to you which way if any you'd like to go.  Hope that helps; good luck!

Playground link to code

ContentLicense: CC BY-SA 4.0

Body:
I'm working on testing the validation logic for a form that has mostly simple text fields, but has some fields that have other kinds of values or require extra logic to set their value. I have an overloaded helper function that looks something like this:

type FieldSetter<T> = (field: Field, value: T) => void; // reusable utility functions to set field values

// overload for the most common case: value is a string, value and setter are optional
function testFieldValidation(
  field: Field,
  valueToTry?: string,
  setFieldValue?: FieldSetter<string>
): void;

// overload for the less common case: value is not a string, value and setter are required
function testFieldValidation<T>(
  field: Field,
  valueToTry: T,
  setFieldValue: FieldSetter<T>
): void;

// function implementation
function testFieldValidation(
  field: Field,
  valueToTry = '', // what should this type be? (defaults to string, which is wrong)
  setFieldValue = defaultStringSetter // and what should this type be?
): void {/* ... */}

I'm trying to figure out what the type should be for the 2nd and 3rd arguments of testFieldValidation's implementation. Here are some things I've already tried:

// error: '""' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'
// This is just not how type parameters work, see https://github.com/microsoft/TypeScript/issues/21521
// .. though it'd be nice if TS could determine from the overloads that this is safe
function testFieldValidation<T = string>(
  field: Field,
  valueToTry: T = '',
  setFieldValue: FieldSetter<T> = defaultStringSetter
): void {/* ... */}

// error: this signature is incompatible with the first overload
function testFieldValidation(
  field: Field,
  valueToTry: unknown = '',
  setFieldValue: FieldSetter<unknown> = defaultStringSetter
): void {/* ... */}

I'd prefer not to use any if I can get away with it. Anyone have any ideas?

A relevant GitHub issue, but no solutions are proposed: link

Body:
Overload implementations are fairly loosely typed compared to the call signatures, in that as long as the implementation parameters and return types are at least as wide as the unions of the types in the call signatures, it should work.  So the following should type check:

// function implementation
function testFieldValidation<T>(
  field: Field,
  valueToTry: T | string = '',
  setFieldValue: FieldSetter<T> | FieldSetter<string> = defaultStringSetter
): void {/* ... */ }

Whether or not this meets your needs is another story; inside the implementation the compiler will not have any idea that valueToTry and setFieldValue will be correlated to each other (e.g., if the first is string then the latter is definitely FieldSetter<string>), so you will find yourself either performing redundant checks or type assertions:

setFieldValue(field, valueToTry); // error!
// ----------------> ~~~~~~~~~~
// 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'

setFieldValue(field, valueToTry as T & string); // okay, asserted

Speaking of type assertions, that's always a possibility when you know more about the types of things than the compiler does.  So, if you want to just tell the compiler that if the default "" is used then that "" will definitely be a valid T, that could work also:

// function implementation
function testFieldValidation<T extends unknown>(
  field: Field,
  valueToTry = '' as T,
  setFieldValue = defaultStringSetter as FieldSetter<T>
): void {/* ... */ }

That might be easier to use inside the implementation, since the necessary assertions have already been done:

setFieldValue(field, valueToTry); // okay

It's up to you which way if any you'd like to go.  Hope that helps; good luck!

<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAYglhANgEygXigbygMwSgLigGdgAnOAOwHMoBfAbgChkIBjRAQzOjYHtKpKKxycAromABlclWpSIwYBDJF4SZAqUqAPKQo0AfMyahIsfJsXKyOgCqH0UABR4NaywBooAN06IxCCI7AEp0Rx8+OGQGKAB6OKgeMWJOACNEaDFgOEQ4UFwxSjYcgWIoYD4SRVxLX39A4iYmSk4AWwhiME42aABVSjgBLGaoeMS+HxVEPk5UHD4yCoALaDa+IX429cooNk5iIPqA6DhyzhJZGm8-E6hOSlRD7SXuaD4wUtbEJjGcIpKQ12ylI6hQADV-NFOF9nL8xrV3BYNJ54WNboE7Hw7GQQAB+Ij6OSohHVYBg5CQk4E5EoLQ2PRXaiGeEhIiRaImMYJKCTaazeaLFbQTLEcpbHZ7A5HDGncqUPjAe6XAzUG4NaAPJ7WFT3HhJCAARzEcB4yHh-2KXwqnXJlip0K+9kMcNJbkItOQJIRsqxOJAwW9Y2eFKpgQ8GnpugcrPZURio3GhStQKgcDaYEyHUowBhQItAOtILtGgdyDzAmdroR7uQEZQQeOmOxuOCUAAPiq5E4AOQ9xsh+0a+tWF7OjueqO2IlGJwicSSGSqqex3zxkZosmhjWuLxNiB+3EhWI8lRkRYAQk3PIAtHf7w-HzfHAA-N-vj-XxI9uw9vZ8CRUDSU5BFzHM4BhCBUAAd3yZZ7l2bg0nyMhuBACpwGgaDljgNh4P4QCoGAqAih4LhlFQSooB7GdqB7RNg0UbcTl3FF90PdCDigOwoAAMi7GhjyTPgAGtOBAbwDkOMgKMTOhmnkqAWnaTpul6KAAEExRUJVMETHk+TIGY5lwIVgFWKB1k2PhtmGfZDnZDU03OAS1X3BDtRePV3k+IF-ALFNhmLZjHSBas-ksEdG19Ft8UJJkByYodqRHKdGVVFkxjZNdOX0iYpiMgVTKWcyRU6cUbMleyZScs4oAVJULlo9U7i1MkbG8g1jVNKCAsBILbRC8snQccLEQ9Cloo1DjA03QdS2HScdVsGMsrjXL4R5S1+t2dNMwgbNcy+Pqi0G5LQsrHiIAAD2UR5yiKESFWgygXU3Wsos3GL-V7P8uLsRKSwhJyMHnCRpCZKd7nKCk0tWqBso5VA9NJebgZY2sWubf0hIMsSQHheS6CAA" rel="nofollow noreferrer">Playground link to code


问:
XPath for email scraping using selenium
I need to scrape multiple contact pages for e-mail adresses in python using selenium. They are all different in their layout and site structure, so I have to come up with a very dynamic XPATH pattern for finding the adresses.

An additional obstacle is that the adresses are sometimes plain text and sometimes an href mailto:

The pattern I have so far kinda works:

```<code>email = driver.find_elements_by_xpath("//*[text()[contains(.,'@')]]").text
</code>```

But it does not work if multiple data is stored in the same div
It also returns a list of elements but I only need the email. If I use find_element_by_xpath there is no text at all.

An example of this would be if you tried to scrape this site: http://schandorf.at/service/kontakt/

So if you have any tips, please let me know!

答:
For each of your pages you can try something like this (example with the website you've posted) :

```<code>emailA = driver.find_elements_by_xpath("//div[@id='col3']//p[contains(.,'@')]").text
emailA_fix = re.search('E-Mail: (.+?)[A-Z]',value).group(1)
emailB = driver.find_elements_by_xpath("//a[contains(@href,'mailto:')]").get_attribute("href")

email = emailA_fix + emailB
</code>```

emailA = search for email address in text format ; email B = search for email address in mailto format

With emailA, we use a regex(re.search) to extract the mail address.

Output : post@schandorf.bgld.gv.at

With LXML or Scrapy you could use a single XPath expression to support the multiple structures of your pages :

```<code> //div[@id='col3']//text()[contains(.,'Mail')]|//a[contains(@href,"mailto:")]/@href
</code>```

Title: XPath for email scraping using selenium

Body:
I need to scrape multiple contact pages for e-mail adresses in python using selenium. They are all different in their layout and site structure, so I have to come up with a very dynamic XPATH pattern for finding the adresses.

An additional obstacle is that the adresses are sometimes plain text and sometimes an href mailto:

The pattern I have so far kinda works:

email = driver.find_elements_by_xpath("//*[text()[contains(.,'@')]]").text

But it does not work if multiple data is stored in the same div
It also returns a list of elements but I only need the email. If I use find_element_by_xpath there is no text at all.

An example of this would be if you tried to scrape this site: http://schandorf.at/service/kontakt/

So if you have any tips, please let me know!

Body:
For each of your pages you can try something like this (example with the website you've posted) :

emailA = driver.find_elements_by_xpath("//div[@id='col3']//p[contains(.,'@')]").text
emailA_fix = re.search('E-Mail: (.+?)[A-Z]',value).group(1)
emailB = driver.find_elements_by_xpath("//a[contains(@href,'mailto:')]").get_attribute("href")

email = emailA_fix + emailB

emailA = search for email address in text format ; email B = search for email address in mailto format

With emailA, we use a regex(re.search) to extract the mail address.

Output : post@schandorf.bgld.gv.at

With LXML or Scrapy you could use a single XPath expression to support the multiple structures of your pages :

 //div[@id='col3']//text()[contains(.,'Mail')]|//a[contains(@href,"mailto:")]/@href


问:
How to count correct answer only one time if I attempt many time correctly?
I am counting the correct answer for total 5 questions. If I am going to re-attempt the same question and get correct again, I shouldn't count it as correct again. I am writing code using javascript.

my code is like this, but if I re attempt same question correctly, my total score will add again.

```<code>var score = 0;

question1.addEventListener("click", () => {

    var firstQuestion = confirm("Is 10 < 20?");

    if (firstQuestion == true){
        score += 1;
        document.getElementById("answerQuestion1").innerHTML = `Correct`;
        document.getElementById("summary").innerHTML = `Your score is: ${score}`;
    }
    else{
        score = 0;
        document.getElementById("answerQuestion1").innerHTML = `Incorrect`;
        document.getElementById("summary").innerHTML = `Your score is: ${score}`;
    }
});
</code>```

答:
Unbind event listener when correct, or hide, or disable.

var score = 0; var q1fn;
question1.addEventListener("click", q1fn = () => {

  var firstQuestion = confirm("Is 10 < 20?");

  if (firstQuestion == true) {
     //hide button
//         question1.style.display="none";
     //disable button
    question1.setAttribute('disabled','disabled');
     // or unbind event listener so it no longer responds
    question1.removeEventListener("click",q1fn);
    score += 1;
    document.getElementById("answerQuestion1").innerHTML = `Correct`;
    document.getElementById("summary").innerHTML = `Your score is: ${score}`;
  } else {
    score = 0;
    document.getElementById("answerQuestion1").innerHTML = `Incorrect`;
    document.getElementById("summary").innerHTML = `Your score is: ${score}`;
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="question1">q</button>

<div id="answerQuestion1"></div>
<div id="summary"></div></code>```

Body:
I am counting the correct answer for total 5 questions. If I am going to re-attempt the same question and get correct again, I shouldn't count it as correct again. I am writing code using javascript.

my code is like this, but if I re attempt same question correctly, my total score will add again.

var score = 0;

question1.addEventListener("click", () => {

    var firstQuestion = confirm("Is 10 < 20?");

    if (firstQuestion == true){
        score += 1;
        document.getElementById("answerQuestion1").innerHTML = `Correct`;
        document.getElementById("summary").innerHTML = `Your score is: ${score}`;
    }
    else{
        score = 0;
        document.getElementById("answerQuestion1").innerHTML = `Incorrect`;
        document.getElementById("summary").innerHTML = `Your score is: ${score}`;
    }
});

Body:
Unbind event listener when correct, or hide, or disable.

var score = 0; var q1fn;
question1.addEventListener("click", q1fn = () => {

  var firstQuestion = confirm("Is 10 < 20?");

  if (firstQuestion == true) {
     //hide button
//         question1.style.display="none";
     //disable button
    question1.setAttribute('disabled','disabled');
     // or unbind event listener so it no longer responds
    question1.removeEventListener("click",q1fn);
    score += 1;
    document.getElementById("answerQuestion1").innerHTML = `Correct`;
    document.getElementById("summary").innerHTML = `Your score is: ${score}`;
  } else {
    score = 0;
    document.getElementById("answerQuestion1").innerHTML = `Incorrect`;
    document.getElementById("summary").innerHTML = `Your score is: ${score}`;
  }

});

<button id="question1">q</button>

<div id="answerQuestion1"></div>
<div id="summary"></div>


问:
xcode preview could not be built into project
canvas preview has an error just like that:

UnknownPreviewProviderError: Unknown preview provider
  "AboutView_Previews" 买就返.app does not contain a preview provider named
  "AboutView_Previews".  Check your build settings to ensure the preview
  provider is compiled into your product. Mangled name:
  3买就返18AboutView_PreviewsV

Error Domain=com.apple.dt.UITestingAgent Code=-1 "Preview provider
  "3买就返18AboutView_PreviewsV" does not exist"
  UserInfo={NSLocalizedDescription=Preview provider
  "3买就返18AboutView_PreviewsV" does not exist}

ihave check the "build setting" -> "build options" -> "Enable Previews" is Yes

```<code>import SwiftUI
struct ContentView: View {

    var body: some View {
        TabView {
            HomeView()
                .tabItem {
                    Image("tabbarHome")
                    Text("首页")
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

答:
I have the same issue when I modify the Product Name(at Target -> Packing -> Product Name) to Chinese word.

The right way to use Chinese word as App name:

open info.plist

add Bundle display name with the name you want.

Use this way to change app name will not effect SwiftUI Previews.

Body:
canvas preview has an error just like that:

UnknownPreviewProviderError: Unknown preview provider
  "AboutView_Previews" 买就返.app does not contain a preview provider named
  "AboutView_Previews".  Check your build settings to ensure the preview
  provider is compiled into your product. Mangled name:
  3买就返18AboutView_PreviewsV

Error Domain=com.apple.dt.UITestingAgent Code=-1 "Preview provider
  "3买就返18AboutView_PreviewsV" does not exist"
  UserInfo={NSLocalizedDescription=Preview provider
  "3买就返18AboutView_PreviewsV" does not exist}

ihave check the "build setting" -> "build options" -> "Enable Previews" is Yes

import SwiftUI
struct ContentView: View {

    var body: some View {
        TabView {
            HomeView()
                .tabItem {
                    Image("tabbarHome")
                    Text("首页")
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
MyBatis when converting #{} element, redundant ' show up?
I am using MyBatis to do sql query, here is the mapper file:

```<code>  <select id="getDepByIdVersion"  resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from dependencies where id = #{repo_id} AND version = #{version_id} </select>
</code>```

while converting "#{version_id}", strange things happened ———— redundant single quote ' shows up：

```<code>2020-05-29 20:24:00.483  INFO 10684 --- [io-18080-exec-2] c.z.n.controller.RepoInfoController      : repo_id:1123
2020-05-29 20:24:00.483  INFO 10684 --- [io-18080-exec-2] c.z.n.controller.RepoInfoController      : version_id:1.0.0
2020-05-29 20:24:00.508  INFO 10684 --- [io-18080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-29 20:24:00.663  INFO 10684 --- [io-18080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-05-29 20:24:00.663 DEBUG 10684 --- [io-18080-exec-2] c.z.n.d.D.getDepByIdVersion              : ==>  Preparing: select id, version, dep_name, constraint from dependencies where id = ? AND version = ?
2020-05-29 20:24:00.695 DEBUG 10684 --- [io-18080-exec-2] c.z.n.d.D.getDepByIdVersion              : ==> Parameters: 1123(String), 1.0.0(String)
2020-05-29 20:24:00.806 ERROR 10684 --- [io-18080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint

    from dependencies where id = '1123' AND version = '1.0.0'' at line 3
### The error may exist in file [J:\Programming\NpmGraph\target\classes\mapper\DependenciesMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select           id, version, dep_name, constraint         from dependencies where id = ? AND version = ?
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint

    from dependencies where id = '1123' AND version = '1.0.0'' at line 3
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint

    from dependencies where id = '1123' AND version = '1.0.0'' at line 3] with root cause
</code>```

You can see from above, the original is 1.0.0, while after conversion it becomes '1.0.0''.
Anybody know why?

答: I think maybe it's because the column constraint, i'll check it out.</p>

Body:
I am using MyBatis to do sql query, here is the mapper file:

  <select id="getDepByIdVersion"  resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from dependencies where id = #{repo_id} AND version = #{version_id} </select>

while converting "#{version_id}", strange things happened ———— redundant single quote ' shows up：

2020-05-29 20:24:00.483  INFO 10684 --- [io-18080-exec-2] c.z.n.controller.RepoInfoController      : repo_id:1123
2020-05-29 20:24:00.483  INFO 10684 --- [io-18080-exec-2] c.z.n.controller.RepoInfoController      : version_id:1.0.0
2020-05-29 20:24:00.508  INFO 10684 --- [io-18080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-29 20:24:00.663  INFO 10684 --- [io-18080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-05-29 20:24:00.663 DEBUG 10684 --- [io-18080-exec-2] c.z.n.d.D.getDepByIdVersion              : ==>  Preparing: select id, version, dep_name, constraint from dependencies where id = ? AND version = ?
2020-05-29 20:24:00.695 DEBUG 10684 --- [io-18080-exec-2] c.z.n.d.D.getDepByIdVersion              : ==> Parameters: 1123(String), 1.0.0(String)
2020-05-29 20:24:00.806 ERROR 10684 --- [io-18080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint

    from dependencies where id = '1123' AND version = '1.0.0'' at line 3
### The error may exist in file [J:\Programming\NpmGraph\target\classes\mapper\DependenciesMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select           id, version, dep_name, constraint         from dependencies where id = ? AND version = ?
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint

    from dependencies where id = '1123' AND version = '1.0.0'' at line 3
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint

    from dependencies where id = '1123' AND version = '1.0.0'' at line 3] with root cause

You can see from above, the original is 1.0.0, while after conversion it becomes '1.0.0''.
Anybody know why?


问:
jQuery: Editing user inserted DOM elements
I want to add html items (text and buttons inside a div) to the DOM and each item be editable or deletable.  I used jquery to do this as follows.

```<code><div id="ak"></div>
<input type="text" name="lname" id="itext" size="60"/><br/>
<button id="but">Add Item</button>
<div id="test"></div>

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("<div class=\"item\"><p>"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button></p></div>");
        $("#itext").val("");
});

$(".deletable").click(function(){
    alert("Alert !!");
});
</code>```

However, when I pressed the delete button in each item nothing happens (should give an alert).  I feel something is very wrong.  Any help is appreciated.

答:
use jQuery.live bcoz

The .live() method is able to affect
  elements that have not yet been added
  to the DOM through the use of event
  delegation:

```<code>$(".deletable").live('click',function(){
    alert("Alert !!");
});
</code>```

DEMO

ContentLicense: CC BY-SA 3.0

Body:
I want to add html items (text and buttons inside a div) to the DOM and each item be editable or deletable.  I used jquery to do this as follows.

<input type="text" name="lname" id="itext" size="60"/>

<button id="but">Add Item</button>

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("

"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button>

");
        $("#itext").val("");
});

$(".deletable").click(function(){
    alert("Alert !!");
});

However, when I pressed the delete button in each item nothing happens (should give an alert).  I feel something is very wrong.  Any help is appreciated.

Body:
use jQuery.live bcoz

The .live() method is able to affect
  elements that have not yet been added
  to the DOM through the use of event
  delegation:

$(".deletable").live('click',function(){
    alert("Alert !!");
});

DEMO


问:
Make an array of strings of the names
I'd like to make an array of strings of the names

```<code>function namesOnly(arr) {

}
namesOnly([
  {
    name: "Angelina Jolie",
    age: 80
  },
  {
    name: "Eric Jones",
    age: 2
  },
  {
    name: "Paris Hilton",
    age: 5
  },
  {
    name: "Kayne West",
    age: 16
  },
  {
    name: "Bob Ziroll",
    age: 100
  }
])
// expect: ["Angelina Jolie", "Eric Jones", "Paris Hilton", "Kayne West", "Bob Ziroll"]
</code>```

So hope!

答:
```<code>    function makeStrings(arr){
      let str = arr.map(function(s) {
        if(s.age >= 17) {
         return s.name + 'can go to The Matrix';
        } else if(s.age) {
          return s.name + 'is under age!';
      }
   })
   return str;
 }
</code>```

Title: Make an array of strings of the names

Body:
I'd like to make an array of strings of the names

function namesOnly(arr) {

}
namesOnly([
  {
    name: "Angelina Jolie",
    age: 80
  },
  {
    name: "Eric Jones",
    age: 2
  },
  {
    name: "Paris Hilton",
    age: 5
  },
  {
    name: "Kayne West",
    age: 16
  },
  {
    name: "Bob Ziroll",
    age: 100
  }
])
// expect: ["Angelina Jolie", "Eric Jones", "Paris Hilton", "Kayne West", "Bob Ziroll"]

So hope!


问:
WPF SharedSizeGroup does not adjust properly
In my application I have two classes DataObj and SubDataObj. For those two classes I want to create a ListView in which I can edit objects of both classes. DataObj holds a List<SubDataObj> and some data modification have an impact on the SubDataObj properties.

My approach was to build my UI like this:

Structured like this:

But I can not align the border of the 3 parts of the view and I can not figure out what I'm doing wrong.

The parent grid has Grid.IsSharedSizeScope="True" and all ColumnDefinitions, the ones in the Grid representing the headers, the ones in the ListView.DataTemplate use SharedSizeGroup="xxx".

My XAML-Code looks like this:

```<code><UserControl
    x:Class="SharedSizeGroupSandBox.Views.SharedSizeGroupView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:SharedSizeGroupSandBox.Views"
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    xmlns:models="clr-namespace:SharedSizeGroupSandBox.Models.SharedSizeGroup"
    xmlns:vms="clr-namespace:SharedSizeGroupSandBox.ViewModels"
    xmlns:converter="clr-namespace:SharedSizeGroupSandBox.ValueConverter"
    mc:Ignorable="d"
    d:DesignHeight="450"
    d:DesignWidth="800"
    d:DataContext="{x:Type vms:SharedSizeGroupVM}">
    <UserControl.Resources>
        <ResourceDictionary>
            <converter:BoolNotConverter
                x:Key="BoolNotConverter" />

        </ResourceDictionary>
    </UserControl.Resources>

    <!--#endregion  Buttons-->
    <ScrollViewer
        Grid.Row="1"
        HorizontalAlignment="Stretch"
        Grid.IsSharedSizeScope="True"
        HorizontalScrollBarVisibility="Auto">
        <Grid
            Grid.Row="1"
            HorizontalAlignment="Left"
            Margin="0">
            <Grid.RowDefinitions>
                <RowDefinition
                    Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>
            <!--#region  Headers-->
            <Grid
                Margin="0,0,0,0"
                Grid.Row="0"
                HorizontalAlignment="Left"
                x:Name="grdlistHeader">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition
                        SharedSizeGroup="a" />
                    <ColumnDefinition
                        SharedSizeGroup="b" />
                    <ColumnDefinition
                        SharedSizeGroup="c" />
                    <ColumnDefinition
                        SharedSizeGroup="d" />
                    <ColumnDefinition
                        SharedSizeGroup="e" />
                    <ColumnDefinition
                        Width="Auto"
                        SharedSizeGroup="f" />
                </Grid.ColumnDefinitions>
                <Border
                    Style="{StaticResource headerBorderStyle}">
                    <TextBlock
                        Text="{Binding NameText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="1">
                    <TextBlock
                        Text="{Binding DescriptionText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="2">
                    <TextBlock
                        Text="{Binding MandatoryText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="3">
                    <TextBlock
                        Text="{Binding ObsoleteText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="4">
                    <TextBlock
                        Text="{Binding CountryText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <TextBlock
                    Grid.Column="5"
                    Text="{Binding CityText}"
                    Style="{StaticResource textBlockHeaderStyle}" />
            </Grid>

            <!--#endregion  Headers-->
            <ListView
                Margin="0,0,0,0"
                Padding="0"
                Grid.Row="1"
                BorderThickness="0,0,0,0"
                BorderBrush="Black"
                SelectionMode="Single"
                SelectedItem="{Binding SelectedItem}"
                ItemsSource="{Binding Data}"
                HorizontalAlignment="Stretch"
                ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                ScrollViewer.VerticalScrollBarVisibility="Hidden">
                <ListView.ItemContainerStyle>

                </ListView.ItemContainerStyle>
                <ListView.ItemTemplate>
                    <DataTemplate
                        DataType="{x:Type vms:DataObjVM}">
                        <Grid
                            Margin="0">
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <!--#region  DataObjVMs-->
                            <Grid
                                Margin="0">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition
                                        SharedSizeGroup="a"
                                        Width="Auto" />
                                    <ColumnDefinition
                                        SharedSizeGroup="b" />
                                    <ColumnDefinition
                                        SharedSizeGroup="c" />
                                    <ColumnDefinition
                                        SharedSizeGroup="d" />
                                    <ColumnDefinition
                                        SharedSizeGroup="e" />
                                    <ColumnDefinition
                                        SharedSizeGroup="f" />
                                    <ColumnDefinition
                                        SharedSizeGroup="g" />
                                    <ColumnDefinition
                                        SharedSizeGroup="h" />
                                    <ColumnDefinition
                                        SharedSizeGroup="i" />
                                </Grid.ColumnDefinitions>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="0">
                                    <TextBox
                                        Text="{Binding Path=Data.Name, UpdateSourceTrigger=PropertyChanged}"
                                        IsReadOnly="{Binding Path=Obsolete}"
                                        Style="{StaticResource baseMargingStyle}"
                                        Padding="0" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="1">
                                    <TextBox
                                        Text="{Binding Path=Data.Description}"
                                        IsReadOnly="{Binding Path=Obsolete}"
                                        Style="{StaticResource baseMargingStyle}" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="2">
                                    <CheckBox
                                        IsEnabled="{Binding Path=Obsolete, Converter={StaticResource BoolNotConverter}}"
                                        IsChecked="{Binding Path=Data.Mandatory}"
                                        Style="{StaticResource checkBoxStyle}" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="3">
                                    <CheckBox
                                        x:Name="cbObsolete"
                                        IsChecked="{Binding Path=Obsolete}"
                                        Style="{StaticResource checkBoxStyle}" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="4">
                                    <ComboBox
                                        Style="{StaticResource baseMargingStyle}"
                                        ItemsSource="{Binding Countries}"
                                        SelectedItem="{Binding Data.Country}"
                                        DisplayMemberPath="ExternalName"
                                        IsEnabled="{Binding Obsolete, Converter={StaticResource BoolNotConverter}}" />
                                </Border>
                                <ComboBox
                                    Grid.Column="5"
                                    Style="{StaticResource baseMargingStyle}"
                                    ItemsSource="{Binding Data.Country.Cities}"
                                    SelectedItem="{Binding Data.City}"
                                    DisplayMemberPath="ExternalName"
                                    IsEnabled="{Binding Obsolete, Converter={StaticResource BoolNotConverter}}" />
                            </Grid>
                            <!--#endregion  Temmplates-->
                            <!--#region  SubTemmplates-->
                            <ListView
                                Margin="0,0,0,0"
                                BorderThickness="0"
                                ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                                ScrollViewer.VerticalScrollBarVisibility="Hidden"
                                IsEnabled="{Binding IsEditEnabled}"
                                Padding="0"
                                Grid.Row="1">
                                <ListView.Resources>
                                    <CollectionViewSource
                                        x:Key="SubDataObjs">
                                        <CollectionViewSource.Source>
                                            <Binding
                                                Path="Data.SubDataObjs"
                                                Mode="OneWay"
                                                UpdateSourceTrigger="PropertyChanged" />
                                        </CollectionViewSource.Source>
                                        <CollectionViewSource.SortDescriptions>
                                            <scm:SortDescription
                                                PropertyName="Name"
                                                Direction="Ascending" />
                                        </CollectionViewSource.SortDescriptions>
                                    </CollectionViewSource>
                                </ListView.Resources>
                                <ListView.ItemContainerStyle>

                                </ListView.ItemContainerStyle>
                                <ListView.ItemsSource>
                                    <Binding
                                        Source="{StaticResource SubDataObjs}" />
                                </ListView.ItemsSource>
                                <ListView.ItemTemplate>
                                    <DataTemplate
                                        DataType="{x:Type models:SubDataObj}">
                                        <Grid
                                            Margin="0">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition
                                                    SharedSizeGroup="a" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="b" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="c" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="d" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="e" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="f" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="g" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="h" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="i" />
                                            </Grid.ColumnDefinitions>

                                            <Border
                                                Style="{StaticResource headerBorderStyle}">
                                                <TextBox
                                                    Style="{StaticResource baseMargingStyle}"
                                                    Text="{Binding Path=Name}"
                                                    IsReadOnly="{Binding Path=Obsolete}"
                                                    MaxLength="{Binding MaxNameLength}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="1">
                                                <TextBox
                                                    Style="{StaticResource baseMargingStyle}"
                                                    IsReadOnly="{Binding Path=Obsolete}"
                                                    BorderThickness="1"
                                                    Text="{Binding Path=Description}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="2"
                                                Padding="0, 0,0,0">
                                                <CheckBox
                                                    IsEnabled="{Binding Path=Obsolete, Converter={StaticResource BoolNotConverter}}"
                                                    IsChecked="{Binding Path=Mandatory}"
                                                    Style="{StaticResource checkBoxStyle}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="3">
                                                <CheckBox
                                                    IsChecked="{Binding Path=Obsolete}"
                                                    IsEnabled="{Binding ElementName=cbObsolete, Path=IsChecked, Converter={StaticResource BoolNotConverter}}"
                                                    Style="{StaticResource checkBoxStyle}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="4" />
                                        </Grid>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                            <!--#endregion  SubTemmplates-->
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>

            </ListView>
        </Grid>
    </ScrollViewer>
</UserControl>
</code>```

I have written a full working sandbox application in case the XAML itself is not enough.

Thank you in advance.

答:
Make a single collection that holds both DataObj and SubDataObj.

When you load the data, loop through each DataObj, and for each one add itself and all of its SubDataObjs to the overall list. Then you can use a normal ListView with a normal GridView and use the overall list as the ItemsSource.

As for the type of this "overall collection", I see three options:

DataObj and SubDataObj obviously share some properties (since they can both be displayed in the same grid), so it might make sense for them to both inherit from the same base class, or for one of them to inherit form the other. Then you could use a SomeCollection<BaseDataObj> (for example).

If inheritance is not appropriate, have them both implement the same interface which includes their shared properties. Then you would use a SomeBaseCollection<IDataInterface> (for example).

If for some reason you don't want to do either of the above, just use a List<Object>.

Body:
In my application I have two classes DataObj and SubDataObj. For those two classes I want to create a ListView in which I can edit objects of both classes. DataObj holds a List<SubDataObj> and some data modification have an impact on the SubDataObj properties.

My approach was to build my UI like this:

Structured like this:

But I can not align the border of the 3 parts of the view and I can not figure out what I'm doing wrong.

The parent grid has Grid.IsSharedSizeScope="True" and all ColumnDefinitions, the ones in the Grid representing the headers, the ones in the ListView.DataTemplate use SharedSizeGroup="xxx".

My XAML-Code looks like this:

<UserControl
    x:Class="SharedSizeGroupSandBox.Views.SharedSizeGroupView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:SharedSizeGroupSandBox.Views"
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    xmlns:models="clr-namespace:SharedSizeGroupSandBox.Models.SharedSizeGroup"
    xmlns:vms="clr-namespace:SharedSizeGroupSandBox.ViewModels"
    xmlns:converter="clr-namespace:SharedSizeGroupSandBox.ValueConverter"
    mc:Ignorable="d"
    d:DesignHeight="450"
    d:DesignWidth="800"
    d:DataContext="{x:Type vms:SharedSizeGroupVM}">
    <UserControl.Resources>
        <ResourceDictionary>
            <converter:BoolNotConverter
                x:Key="BoolNotConverter" />

        </ResourceDictionary>
    </UserControl.Resources>

    <ScrollViewer
        Grid.Row="1"
        HorizontalAlignment="Stretch"
        Grid.IsSharedSizeScope="True"
        HorizontalScrollBarVisibility="Auto">
        <Grid
            Grid.Row="1"
            HorizontalAlignment="Left"
            Margin="0">
            <Grid.RowDefinitions>
                <RowDefinition
                    Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Grid
                Margin="0,0,0,0"
                Grid.Row="0"
                HorizontalAlignment="Left"
                x:Name="grdlistHeader">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition
                        SharedSizeGroup="a" />
                    <ColumnDefinition
                        SharedSizeGroup="b" />
                    <ColumnDefinition
                        SharedSizeGroup="c" />
                    <ColumnDefinition
                        SharedSizeGroup="d" />
                    <ColumnDefinition
                        SharedSizeGroup="e" />
                    <ColumnDefinition
                        Width="Auto"
                        SharedSizeGroup="f" />
                </Grid.ColumnDefinitions>
                <Border
                    Style="{StaticResource headerBorderStyle}">
                    <TextBlock
                        Text="{Binding NameText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="1">
                    <TextBlock
                        Text="{Binding DescriptionText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="2">
                    <TextBlock
                        Text="{Binding MandatoryText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="3">
                    <TextBlock
                        Text="{Binding ObsoleteText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <Border
                    Style="{StaticResource headerBorderStyle}"
                    Grid.Column="4">
                    <TextBlock
                        Text="{Binding CountryText}"
                        Style="{StaticResource textBlockHeaderStyle}" />
                </Border>
                <TextBlock
                    Grid.Column="5"
                    Text="{Binding CityText}"
                    Style="{StaticResource textBlockHeaderStyle}" />
            </Grid>

            <ListView
                Margin="0,0,0,0"
                Padding="0"
                Grid.Row="1"
                BorderThickness="0,0,0,0"
                BorderBrush="Black"
                SelectionMode="Single"
                SelectedItem="{Binding SelectedItem}"
                ItemsSource="{Binding Data}"
                HorizontalAlignment="Stretch"
                ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                ScrollViewer.VerticalScrollBarVisibility="Hidden">
                <ListView.ItemContainerStyle>

                </ListView.ItemContainerStyle>
                <ListView.ItemTemplate>
                    <DataTemplate
                        DataType="{x:Type vms:DataObjVM}">
                        <Grid
                            Margin="0">
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>

                            <Grid
                                Margin="0">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition
                                        SharedSizeGroup="a"
                                        Width="Auto" />
                                    <ColumnDefinition
                                        SharedSizeGroup="b" />
                                    <ColumnDefinition
                                        SharedSizeGroup="c" />
                                    <ColumnDefinition
                                        SharedSizeGroup="d" />
                                    <ColumnDefinition
                                        SharedSizeGroup="e" />
                                    <ColumnDefinition
                                        SharedSizeGroup="f" />
                                    <ColumnDefinition
                                        SharedSizeGroup="g" />
                                    <ColumnDefinition
                                        SharedSizeGroup="h" />
                                    <ColumnDefinition
                                        SharedSizeGroup="i" />
                                </Grid.ColumnDefinitions>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="0">
                                    <TextBox
                                        Text="{Binding Path=Data.Name, UpdateSourceTrigger=PropertyChanged}"
                                        IsReadOnly="{Binding Path=Obsolete}"
                                        Style="{StaticResource baseMargingStyle}"
                                        Padding="0" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="1">
                                    <TextBox
                                        Text="{Binding Path=Data.Description}"
                                        IsReadOnly="{Binding Path=Obsolete}"
                                        Style="{StaticResource baseMargingStyle}" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="2">
                                    <CheckBox
                                        IsEnabled="{Binding Path=Obsolete, Converter={StaticResource BoolNotConverter}}"
                                        IsChecked="{Binding Path=Data.Mandatory}"
                                        Style="{StaticResource checkBoxStyle}" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="3">
                                    <CheckBox
                                        x:Name="cbObsolete"
                                        IsChecked="{Binding Path=Obsolete}"
                                        Style="{StaticResource checkBoxStyle}" />
                                </Border>
                                <Border
                                    Style="{StaticResource headerBorderStyle}"
                                    Grid.Column="4">
                                    <ComboBox
                                        Style="{StaticResource baseMargingStyle}"
                                        ItemsSource="{Binding Countries}"
                                        SelectedItem="{Binding Data.Country}"
                                        DisplayMemberPath="ExternalName"
                                        IsEnabled="{Binding Obsolete, Converter={StaticResource BoolNotConverter}}" />
                                </Border>
                                <ComboBox
                                    Grid.Column="5"
                                    Style="{StaticResource baseMargingStyle}"
                                    ItemsSource="{Binding Data.Country.Cities}"
                                    SelectedItem="{Binding Data.City}"
                                    DisplayMemberPath="ExternalName"
                                    IsEnabled="{Binding Obsolete, Converter={StaticResource BoolNotConverter}}" />
                            </Grid>

                            <ListView
                                Margin="0,0,0,0"
                                BorderThickness="0"
                                ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                                ScrollViewer.VerticalScrollBarVisibility="Hidden"
                                IsEnabled="{Binding IsEditEnabled}"
                                Padding="0"
                                Grid.Row="1">
                                <ListView.Resources>
                                    <CollectionViewSource
                                        x:Key="SubDataObjs">
                                        <CollectionViewSource.Source>
                                            <Binding
                                                Path="Data.SubDataObjs"
                                                Mode="OneWay"
                                                UpdateSourceTrigger="PropertyChanged" />
                                        </CollectionViewSource.Source>
                                        <CollectionViewSource.SortDescriptions>
                                            <scm:SortDescription
                                                PropertyName="Name"
                                                Direction="Ascending" />
                                        </CollectionViewSource.SortDescriptions>
                                    </CollectionViewSource>
                                </ListView.Resources>
                                <ListView.ItemContainerStyle>

                                </ListView.ItemContainerStyle>
                                <ListView.ItemsSource>
                                    <Binding
                                        Source="{StaticResource SubDataObjs}" />
                                </ListView.ItemsSource>
                                <ListView.ItemTemplate>
                                    <DataTemplate
                                        DataType="{x:Type models:SubDataObj}">
                                        <Grid
                                            Margin="0">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition
                                                    SharedSizeGroup="a" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="b" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="c" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="d" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="e" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="f" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="g" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="h" />
                                                <ColumnDefinition
                                                    SharedSizeGroup="i" />
                                            </Grid.ColumnDefinitions>

                                            <Border
                                                Style="{StaticResource headerBorderStyle}">
                                                <TextBox
                                                    Style="{StaticResource baseMargingStyle}"
                                                    Text="{Binding Path=Name}"
                                                    IsReadOnly="{Binding Path=Obsolete}"
                                                    MaxLength="{Binding MaxNameLength}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="1">
                                                <TextBox
                                                    Style="{StaticResource baseMargingStyle}"
                                                    IsReadOnly="{Binding Path=Obsolete}"
                                                    BorderThickness="1"
                                                    Text="{Binding Path=Description}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="2"
                                                Padding="0, 0,0,0">
                                                <CheckBox
                                                    IsEnabled="{Binding Path=Obsolete, Converter={StaticResource BoolNotConverter}}"
                                                    IsChecked="{Binding Path=Mandatory}"
                                                    Style="{StaticResource checkBoxStyle}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="3">
                                                <CheckBox
                                                    IsChecked="{Binding Path=Obsolete}"
                                                    IsEnabled="{Binding ElementName=cbObsolete, Path=IsChecked, Converter={StaticResource BoolNotConverter}}"
                                                    Style="{StaticResource checkBoxStyle}" />
                                            </Border>
                                            <Border
                                                Style="{StaticResource headerBorderStyle}"
                                                Grid.Column="4" />
                                        </Grid>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>

                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>

            </ListView>
        </Grid>
    </ScrollViewer>
</UserControl>

I have written a full working sandbox application in case the XAML itself is not enough.

Thank you in advance.


问:
Class diagram - Confused about UML association multiplicity

I am little confused about how multiplicity works.

Let's i have a system where the user signs up, fills details about themselves and after signing up they have to fill details separately about their relative.

My question :

I want to indicate that for every User class there is only one Relative class and same backwards.

But what if there are many Users objects and each one is connected to their Relative class

so shouldn't the association be 1..* ?

答:
But what if there are many Users objects and each one is connected to their Relative class

That's exactly what your diagram says: each User instance (or object) must have one, and only one, Relative object associated with it.

so shouldn't the association be 1..* ?

If the multiplicity was 1..*, then you're allowing one instance of a User to have multiple instances of Relatives associated with it. But that's not what you want, right? So it's correct to specify the way you did.


问:
Is that style of FSM is correct and synthesible?
Talking about only the state function here, is there any problem here ? not using "next state" and only use 1 state "rd_state" that can take 2 values "IDLE_RD" and "RD_TRAN"?</p>

```<code> always @(posedge clk)
    begin : rd_state_func
        if (reset==1) begin
            rd_state<=IDLE_RD;
        end else begin
            case (rd_state)
                IDLE_RD: begin
                        if (pkt_req==1) begin
                            if (fifo_empty==0) begin
                                rd_state <= RD_TRAN;
                            end else begin
                                rd_state <= IDLE_RD;
                            end
                        end else begin
                            rd_state <= IDLE_RD;
                        end
                        end
                RD_TRAN: begin
                        if (some_if.eop==1) begin
                            rd_state <= IDLE_RD;
                        end else begin
                            rd_state <= RD_TRAN;
                        end
                end
            endcase
        end
    end
</code>```

答:
It is correct.

It is synthesizable (why wouldn't?).

But it might not to be the best style.

I tend to use that precisely style. I find it to be useful when maintaining and debugging large FSMs, such as the ones that come from the translation of a sequential algorithm.

OTOH, synthesizers seem to detect better a two or three "always" style FSMs and tend to produce a better result (less gates). This is because this style don't rely on a given datapath, but the datapath must be inferred by the synthesizer (for each register, the synthesizer must determine which signals are routed to its input and calculate the equations that determine which of the routed signals must enter the register). I thought this should be straightforward, but I've found that it's not the case. Some FSMs which XST synthesizes correctly, don't work in Quartus, and viceversa.

Body:
Talking about only the state function here, is there any problem here ? not using "next state" and only use 1 state "rd_state" that can take 2 values "IDLE_RD" and "RD_TRAN"?

 always @(posedge clk)
    begin : rd_state_func
        if (reset==1) begin
            rd_state<=IDLE_RD;
        end else begin
            case (rd_state)
                IDLE_RD: begin
                        if (pkt_req==1) begin
                            if (fifo_empty==0) begin
                                rd_state <= RD_TRAN;
                            end else begin
                                rd_state <= IDLE_RD;
                            end
                        end else begin
                            rd_state <= IDLE_RD;
                        end
                        end
                RD_TRAN: begin
                        if (some_if.eop==1) begin
                            rd_state <= IDLE_RD;
                        end else begin
                            rd_state <= RD_TRAN;
                        end
                end
            endcase
        end
    end


问:
Scala - Handle empty strings when instantiating a class
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

```<code>case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))
</code>```

Would result in:

```<code>SomeClass = SomeClass(,a)
</code>```

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

答:
You can define companion object with apply function.

case class SomeClass(a: String, b: String)

object SomeClass {
  def apply(a: String, b: String): SomeClass = {
     if (a.trim.isEmpty || b.trim.isEmpty) throw new IllegalArgumentException
     SomeClass(a, b)
  }
}
```

```@ SomeClass("", "b")
java.lang.IllegalArgumentException
  ammonite.$sess.cmd4$SomeClass$.apply(cmd4.sc:3)
  ammonite.$sess.cmd5$.<init>(cmd5.sc:1)
  ammonite.$sess.cmd5$.<clinit>(cmd5.sc)
```

Body:
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))

Would result in:

SomeClass = SomeClass(,a)

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

Body:
You can define companion object with apply function.

case class SomeClass(a: String, b: String)

object SomeClass {
  def apply(a: String, b: String): SomeClass = {
     if (a.trim.isEmpty || b.trim.isEmpty) throw new IllegalArgumentException
     SomeClass(a, b)
  }
}

@ SomeClass("", "b")
java.lang.IllegalArgumentException
  ammonite.$sess.cmd4$SomeClass$.apply(cmd4.sc:3)
  ammonite.$sess.cmd5$.<init>(cmd5.sc:1)
  ammonite.$sess.cmd5$.<clinit>(cmd5.sc)


问:
Facebook Open Graph not clearing cache
I'm having troubles with my meta tags with Open Graph. It seems as though Facebook is caching old values of my meta tags. Old values for Attributes og:title and og:url are still used, even though I have changed them already.

I ran Lint on a page in my site, and this appeared:

Notice that there are two values for og:title and og:url, and the last one prevailed. However, The last two entries are the OLD entries that I used for this site. I am now currently using these meta tags (you can verify if you view the source of the HTML):

<meta property="og:title" content="Smart og rummelig pusletaske fra Petit Amour med god plads til alt – værdi 1.099 kr – køb nu kun 599 kr   "/>
<meta property="og:description" content="Pinq.dk - Det gode liv for det halve"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="http://pinq.dk/tilbud/landsdaekkende/lissy/"/>
<meta property="og:image" content="http://pinq.dk/wp-content/themes/pinq/images/logo-top.png"/>
<meta property="og:site_name" content="Pinq" />
<meta property="fb:app_id" content="161840830532004" />
```

Why is Facebook caching og:title and og:url? Is anyone experiencing the same issue?

答: I had a different, but similar problem with Facebook recently, and found that the scraper/debug page mentioned, simply does not appear to read any page in its entirety.  My meta properties for Open Graph were further down in the head section, and the scraper would constantly inform me that the image specification was not correct, and would use a cached version regardless.  I moved the Open Graph tags further up in the code, near the very top of the page, and then everything worked perfectly, every time.</p>

Title: Facebook Open Graph not clearing cache

Body:
I'm having troubles with my meta tags with Open Graph. It seems as though Facebook is caching old values of my meta tags. Old values for Attributes og:title and og:url are still used, even though I have changed them already.

I ran Lint on a page in my site, and this appeared:

Notice that there are two values for og:title and og:url, and the last one prevailed. However, The last two entries are the OLD entries that I used for this site. I am now currently using these meta tags (you can verify if you view the source of the HTML):

<meta property="og:title" content="Smart og rummelig pusletaske fra Petit Amour med god plads til alt – værdi 1.099 kr – køb nu kun 599 kr   "/>
<meta property="og:description" content="Pinq.dk - Det gode liv for det halve"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="http://pinq.dk/tilbud/landsdaekkende/lissy/"/>
<meta property="og:image" content="http://pinq.dk/wp-content/themes/pinq/images/logo-top.png"/>
<meta property="og:site_name" content="Pinq" />
<meta property="fb:app_id" content="161840830532004" />

Why is Facebook caching og:title and og:url? Is anyone experiencing the same issue?


问:
How do you write or replace a url in a function using onClick?
I'm new to javascript and I'm having a particularly difficult time figuring out how write new urls into an existing function using onClick.

Here is some more info:

I want to have something like this

```<code>   <script type="text/javascript">

    function addurl(){
    "server": [
                 {
                    "position": "center",
                    "url": "New_Url"
                 }
              ]
                     }
    </script>

    <div id="urlbutton"></div>
    <input type="button" onclick="????" value="url123">
</code>```

Basically I want to replace the "url" when clicking different buttons/links. I've spent hours and hours today trying to figure this out and now I'm basically all turned around not knowing what to do.

Any type of help will be greatly appreciated!

答:
Been a month since I used Javascript, but here it goes...
I found a website that might be able to help you out. It appears older, but works.

The link is here: http://www.htmlgoodies.com/tutorials/buttons/article.php/3478871/So-You-Want-A-Link-Button-Huh.htm

This is what he suggests:

```<code>    <FORM>
    <INPUT TYPE="button" onClick="parent.location='page.html'">
    </FORM>
</code>```

Just change out the "page.html" with the URL of the page you want to click and go to. I won't get into the concept of JavaScript here, but if you're willing to learn more, see my JavaScript primers.

Hope this helps.

Body:
I'm new to javascript and I'm having a particularly difficult time figuring out how write new urls into an existing function using onClick.

Here is some more info:

I want to have something like this

    <input type="button" onclick="????" value="url123">

Basically I want to replace the "url" when clicking different buttons/links. I've spent hours and hours today trying to figure this out and now I'm basically all turned around not knowing what to do.

Any type of help will be greatly appreciated!

Body:
Been a month since I used Javascript, but here it goes...
I found a website that might be able to help you out. It appears older, but works.

The link is here: http://www.htmlgoodies.com/tutorials/buttons/article.php/3478871/So-You-Want-A-Link-Button-Huh.htm

This is what he suggests:

    <FORM>
    <INPUT TYPE="button" onClick="parent.location='page.html'">
    </FORM>

Just change out the "page.html" with the URL of the page you want to click and go to. I won't get into the concept of JavaScript here, but if you're willing to learn more, see my JavaScript primers.

Hope this helps.


问:
How do you make a choropleth map with Mapbox GL JS, and an object?
I'm struggling to find the right information in order to create a choropleth map using mapbox. Their examples are very vague.

I currently have a geojson showing the polygons for all the UK counties. I used map.addLayer to add this to the map, but at the moment, the whole map is the same color:

```<code>        map.addLayer({
        "id": 'counties',
        "type": "fill",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": counties
            }
        },
        "layout": {},
        "paint": {
            "fill-color": fill,
            "fill-opacity": 0.8
        }
    });
</code>```

counties is the geojson file, which also includes a property called 'County'. In addition, I have returned an object, which returns key, value pairs of counties, and the number of times it appeared in my data, respectively:

```<code>{
    "Bristol": 2,
    "Cheshire": 1,
    "City and County of the City of London": 14,
    "City of Aberdeen": 1,
    "City of Edinburgh": 3
}
</code>```

How can I create a choropleth map using the data from my object, to return as different shades/color for the layer (e.g, counties such as Cheshire would be a lighter color, because the value is one, but City and County of the City of London would have a darker color because the value is 14?

答:
How is your geojson structured?

The easiest way would be for your features to have a property called "frequency" for example. Then you can use Mapbox GL JS data-driven styling like this:

```<code>'fill-color': {
property: 'frequency',
stops: [[2, '#fff'], [5, '#f00']]
}
</code>```

Check this post by Mapbox: https://blog.mapbox.com/data-driven-styling-for-fill-layers-in-mapbox-gl-js-80bb5292af4e

Body:
I'm struggling to find the right information in order to create a choropleth map using mapbox. Their examples are very vague.

I currently have a geojson showing the polygons for all the UK counties. I used map.addLayer to add this to the map, but at the moment, the whole map is the same color:

        map.addLayer({
        "id": 'counties',
        "type": "fill",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": counties
            }
        },
        "layout": {},
        "paint": {
            "fill-color": fill,
            "fill-opacity": 0.8
        }
    });

counties is the geojson file, which also includes a property called 'County'. In addition, I have returned an object, which returns key, value pairs of counties, and the number of times it appeared in my data, respectively:

{
    "Bristol": 2,
    "Cheshire": 1,
    "City and County of the City of London": 14,
    "City of Aberdeen": 1,
    "City of Edinburgh": 3
}

How can I create a choropleth map using the data from my object, to return as different shades/color for the layer (e.g, counties such as Cheshire would be a lighter color, because the value is one, but City and County of the City of London would have a darker color because the value is 14?

Body:
How is your geojson structured?

The easiest way would be for your features to have a property called "frequency" for example. Then you can use Mapbox GL JS data-driven styling like this:

'fill-color': {
property: 'frequency',
stops: [[2, '#fff'], [5, '#f00']]
}

Check this post by Mapbox: https://blog.mapbox.com/data-driven-styling-for-fill-layers-in-mapbox-gl-js-80bb5292af4e


问:
nextcloud and mariadb (both) on docker: SQLSTATE[HY000] [2002] No such file or directory
I've been trying to set up Nextcloud and MariaDB with the Linux server images and hit my road block when I want to get through the first run wizard of Nextcloud:

Problem

I.e. the first time wizard gives me Error while trying to create admin user: Failed to connect to the database: An exception occured in driver: SQLSTATE[HY000] [2002] No such file or directory.

Question:

Where is that coming from and how to solve the problem?

System

I'm using Amahi 11 and have installed docker from the repositories. Docker verision:

```<code>  Client:
 Version:           18.09.0
 API version:       1.39
 Go version:        go1.10.4
 Git commit:        4d60db4
 Built:             Wed Nov  7 00:48:52 2018
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.0
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.4
  Git commit:       4d60db4
  Built:            Wed Nov  7 00:19:08 2018
  OS/Arch:          linux/amd64
  Experimental:     false
</code>```

I am starting nextcloud and mariadb with docker-compose. Following the content for mariadb:

```<code>version: '2'
  services:
    mariadb:
      image: linuxserver/mariadb
      container_name: mariadb
      environment:
        - PUID=XX
        - PGID=YYY
        - MYSQL_ROOT_USER=root
        - MYSQL_ROOT_PASSWORD=secret
        - MYSQL_DATABASE=nextcloud
      volumes:
        - <path/to/my/folder>:/config
      ports:
        - 3307:3306
      restart: unless-stopped
</code>```

Already tried:

A lot of research, which came up empty or lead me to do the next point:

So from the error info I started checking if the database actually exists:sudo docker exec -it mariadb bash. There I figured, that access to command-line with 'mysql' for root was denied because the password was not set. (mmmh... is ther something wrong with my docker-compose-file?)
Anyway I corrected that one with mysql -u root -pSECRETand mysql -u root --password=SECRET. With show databases; I found no nextcloud database. (There MUST be something wrong with my docker-compose-file.) So I created it as well (create database nextcloud;). Database is now shown properly and I found it in <path/to/my/folder>. Result: No change, problem still there.

I did some more editing with on my docker-compose-file:

```<code>version: '2'
  services:
    mariadb:
      image: linuxserver/mariadb
      container_name: mariadb
      environment:
        - MYSQL_ROOT_PASSWORD=secret
        - MYSQL_DATABASE=nextcloud
        - PUID=XX
        - PGID=YYY
      volumes:
        - <path/to/my/folder>:/config
      ports:
        - 3307:3306
      restart: unless-stopped
</code>```

So I changed the hierarchy and eliminated the MYSQL_ROOT_USER=rootline. When restarting I can mysql -u root --password=SECRET and show the nextcloud database. YET, I am not sure, if these changes remained in the volume from my last (manual) changes. Result: Problem still there.

答: I had to use nextcloud-mariadb:3306 as the connection string. I figured it out by running $ docker ps -a which lists the name and the port.

Body:
I've been trying to set up Nextcloud and MariaDB with the Linux server images and hit my road block when I want to get through the first run wizard of Nextcloud:

Problem

I.e. the first time wizard gives me Error while trying to create admin user: Failed to connect to the database: An exception occured in driver: SQLSTATE[HY000] [2002] No such file or directory.

Question:

Where is that coming from and how to solve the problem?

System

I'm using Amahi 11 and have installed docker from the repositories. Docker verision:

  Client:
 Version:           18.09.0
 API version:       1.39
 Go version:        go1.10.4
 Git commit:        4d60db4
 Built:             Wed Nov  7 00:48:52 2018
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.0
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.4
  Git commit:       4d60db4
  Built:            Wed Nov  7 00:19:08 2018
  OS/Arch:          linux/amd64
  Experimental:     false

I am starting nextcloud and mariadb with docker-compose. Following the content for mariadb:

version: '2'
  services:
    mariadb:
      image: linuxserver/mariadb
      container_name: mariadb
      environment:
        - PUID=XX
        - PGID=YYY
        - MYSQL_ROOT_USER=root
        - MYSQL_ROOT_PASSWORD=secret
        - MYSQL_DATABASE=nextcloud
      volumes:
        - <path/to/my/folder>:/config
      ports:
        - 3307:3306
      restart: unless-stopped

Already tried:

A lot of research, which came up empty or lead me to do the next point:

So from the error info I started checking if the database actually exists:sudo docker exec -it mariadb bash. There I figured, that access to command-line with 'mysql' for root was denied because the password was not set. (mmmh... is ther something wrong with my docker-compose-file?)
Anyway I corrected that one with mysql -u root -pSECRETand mysql -u root --password=SECRET. With show databases; I found no nextcloud database. (There MUST be something wrong with my docker-compose-file.) So I created it as well (create database nextcloud;). Database is now shown properly and I found it in <path/to/my/folder>. Result: No change, problem still there.

I did some more editing with on my docker-compose-file:

version: '2'
  services:
    mariadb:
      image: linuxserver/mariadb
      container_name: mariadb
      environment:
        - MYSQL_ROOT_PASSWORD=secret
        - MYSQL_DATABASE=nextcloud
        - PUID=XX
        - PGID=YYY
      volumes:
        - <path/to/my/folder>:/config
      ports:
        - 3307:3306
      restart: unless-stopped

So I changed the hierarchy and eliminated the MYSQL_ROOT_USER=rootline. When restarting I can mysql -u root --password=SECRET and show the nextcloud database. YET, I am not sure, if these changes remained in the volume from my last (manual) changes. Result: Problem still there.


问:
How to call my method at a particular throughput in C#?
I am doing some performance testing so want to call my method at a particular throughput which I can control. With this way I can generate some load and figure out how it behaves under various throughput.

For example: I need to call my doIOStuff method at an approximate rate of x requests per second from multiple threads where x will be less than 2000 mostly but it really doesn't matter in this case. It doesn't have to be accurate so there is some room for an error but the overall idea is I need to make sure that my method doIOStuff is executed no more than x times in a sliding window of y seconds.

Below is the code I got where I am creating 3 different threads and that is calling doIOStuff method in parallel but not able to figure out how to rate limit this method for x requests per second. Is there an easy way where I can control this?

```<code>class Program
{
    static void Main(string[] args)
    {
        var tasks = new List<Task>();

        for(int i = 0; i< 100; i ++)
            tasks.Add(Task.Factory.StartNew(() => doIOStuff(), i));

        Task.WaitAll(tasks.ToArray());
        Console.WriteLine("All threads complete");
    }

    // how to call this method at a particular rate?
    static void doIOStuff()
    {
        // do some IO work
    }
}
</code>```

I want to keep running this test for some duration of time but during that duration it should always make calls to that method at a particular throughput only.

Note:

This is just an idea from me of generating random throughput which I can control but if this doesn't do things correctly then we should try to do it in a better and efficient way if possible but overall idea is to control the random throughput on my own and generate that much load to my method.

答:
Assuming you start n threads and want a maximum of m calls per second. This can be achieved by having each thread generate a random number between 0 and 1, k times per second and call your IO method only if the generated number is less than m / n / k

```<code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp7
{
    class Program
    {
        const int m_threads = 100;
        const int n_throughput = 2000;
        const int k_toss_per_second = 2000; // Note that k_toss_per_second x  m_threads >= n_throughput

        static void Main(string[] args)
        {
            var tasks = new List<Task>();

            for (int i = 0; i < m_threads; i++)
                tasks.Add(Task.Factory.StartNew(() => callDoIOStuff()));

            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("All threads complete");
        }

        static void callDoIOStuff()
        {
           int sleep_time = (int) (1000 * 1.0d / k_toss_per_second);
           double threshold = (double) n_throughput / m_threads / k_toss_per_second;
           Random random = new Random();
           while (true) {
                Thread.Sleep(sleep_time);
                if (random.NextDouble() < threshold)
                    doIOStuff();
            }
        }

        // how to call this method at a particular rate?
        static void doIOStuff()
        {
            // do some IO work
        }
    }
}
</code>```

You need to take care of passing the cancellation tokens and whatever parameters. This code sample is quick and dirty using global variables and could be greatly improved.

Body:
I am doing some performance testing so want to call my method at a particular throughput which I can control. With this way I can generate some load and figure out how it behaves under various throughput.

For example: I need to call my doIOStuff method at an approximate rate of x requests per second from multiple threads where x will be less than 2000 mostly but it really doesn't matter in this case. It doesn't have to be accurate so there is some room for an error but the overall idea is I need to make sure that my method doIOStuff is executed no more than x times in a sliding window of y seconds.

Below is the code I got where I am creating 3 different threads and that is calling doIOStuff method in parallel but not able to figure out how to rate limit this method for x requests per second. Is there an easy way where I can control this?

class Program
{
    static void Main(string[] args)
    {
        var tasks = new List<Task>();

        for(int i = 0; i< 100; i ++)
            tasks.Add(Task.Factory.StartNew(() => doIOStuff(), i));

        Task.WaitAll(tasks.ToArray());
        Console.WriteLine("All threads complete");
    }

    // how to call this method at a particular rate?
    static void doIOStuff()
    {
        // do some IO work
    }
}

I want to keep running this test for some duration of time but during that duration it should always make calls to that method at a particular throughput only.

Note:

This is just an idea from me of generating random throughput which I can control but if this doesn't do things correctly then we should try to do it in a better and efficient way if possible but overall idea is to control the random throughput on my own and generate that much load to my method.

Body:
Assuming you start n threads and want a maximum of m calls per second. This can be achieved by having each thread generate a random number between 0 and 1, k times per second and call your IO method only if the generated number is less than m / n / k

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp7
{
    class Program
    {
        const int m_threads = 100;
        const int n_throughput = 2000;
        const int k_toss_per_second = 2000; // Note that k_toss_per_second x  m_threads >= n_throughput

        static void Main(string[] args)
        {
            var tasks = new List<Task>();

            for (int i = 0; i < m_threads; i++)
                tasks.Add(Task.Factory.StartNew(() => callDoIOStuff()));

            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("All threads complete");
        }

        static void callDoIOStuff()
        {
           int sleep_time = (int) (1000 * 1.0d / k_toss_per_second);
           double threshold = (double) n_throughput / m_threads / k_toss_per_second;
           Random random = new Random();
           while (true) {
                Thread.Sleep(sleep_time);
                if (random.NextDouble() < threshold)
                    doIOStuff();
            }
        }

        // how to call this method at a particular rate?
        static void doIOStuff()
        {
            // do some IO work
        }
    }
}

You need to take care of passing the cancellation tokens and whatever parameters. This code sample is quick and dirty using global variables and could be greatly improved.