问:
How do I create a child object before a parent object gets created? Can I bypass foreign key constraints?
I have three tables: Term, Course, and Assessment. Term is the parent to Course, and Course is the parent to Assessment. When I am creating a course there is a listview of all existing terms. The user clicks on the term they want this course to be apart of, and a foreign key gets inserted that is equivalent to the id of the selected term. This works great without foreign key constraints. When I turn foreign key constraints on, I can't create a course if a term doesn't exist, or an assessment if a course doesn't exist. Obviously if the user creates a term first, then a course, then an assessment everything works but that is not practical. Can I not have foreign keys enabled while being able to create a child before a parent?

Here is where I create my tables

```<code>
@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TermDbSchema.TermTable.NAME + "(" +
                "_id integer primary key autoincrement, " +
                TermDbSchema.TermTable.Cols.UUID + ", " +
                TermDbSchema.TermTable.Cols.TITLE + ", " +
                TermDbSchema.TermTable.Cols.START_DATE + ", " +
                TermDbSchema.TermTable.Cols.END_DATE +
                ")"
        );
        db.execSQL("create table " + TermDbSchema.CourseTable.NAME + "(" +
                "_id integer primary key autoincrement, " +
                TermDbSchema.CourseTable.Cols.UUID + ", " +
                TermDbSchema.CourseTable.Cols.TITLE + ", " +
                TermDbSchema.CourseTable.Cols.START_DATE + ", " +
                TermDbSchema.CourseTable.Cols.END_DATE + ", " +
                TermDbSchema.CourseTable.Cols.CHOSEN_START_DATE + ", " +
                TermDbSchema.CourseTable.Cols.CHOSEN_END_DATE + ", " +

                TermDbSchema.CourseTable.Cols.COURSE_STATUS + ", " +
                TermDbSchema.CourseTable.Cols.OPTIONAL_NOTE + ", " +
                TermDbSchema.CourseTable.Cols.MENTOR_NAME + ", " +
                TermDbSchema.CourseTable.Cols.MENTOR_PHONE + ", " +
                TermDbSchema.CourseTable.Cols.MENTOR_EMAIL + ", " +
//this foreign key references TermTable
                TermDbSchema.CourseTable.Cols.COL_COURSE_TERM_REFERENCE + " INTEGER REFERENCES " + TermDbSchema.TermTable.NAME + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" + //<<<<<<<<<< ADDED
                ")"
        );
        db.execSQL("create table " + TermDbSchema.AssessmentTable.NAME + "(" +
                "_id integer primary key autoincrement, " +
                TermDbSchema.AssessmentTable.Cols.UUID + ", " +
                TermDbSchema.AssessmentTable.Cols.TITLE + ", " +
                TermDbSchema.AssessmentTable.Cols.ASSESS_TYPE + ", " +
                TermDbSchema.AssessmentTable.Cols.DUE_DATE + ", " +
                TermDbSchema.AssessmentTable.Cols.GOAL_DATE + ", " +
//this foreign key references CourseTable
                TermDbSchema.AssessmentTable.Cols.COL_ASSESS_COURSE_REFERENCE + " INTEGER REFERENCES " + TermDbSchema.CourseTable.NAME + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" + //<<<<<<<<<< ADDED
                //"course_reference" + " INTEGER REFERENCES " + "courses" + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" +
                ")"
        );
    }
</code>```

Here is my Tables schema:

```<code>
public class TermDbSchema {
    public static final class TermTable {
        public static final String NAME = "terms";
        public static final class Cols {
            public static final String UUID = "uuid";
            public static final String TITLE = "title";
            public static final String START_DATE = "startdate";
            public static final String END_DATE = "enddate";

        }
    }
    public static final class CourseTable {
        public static final String NAME = "courses";
        public static final class Cols {
            public static final String UUID = "uuid";
            public static final String TITLE = "title";
            public static final String START_DATE = "startdate";
            public static final String END_DATE = "enddate";
            public static final String CHOSEN_START_DATE = "chosenstartdate";
            public static final String CHOSEN_END_DATE = "chosenenddate";

            public static final String COURSE_STATUS = "coursestatus";
            public static final String OPTIONAL_NOTE = "optionalnote";
            public static final String MENTOR_NAME = "mentorname";
            public static final String MENTOR_PHONE = "mentorphone";
            public static final String MENTOR_EMAIL = "mentoremail";
            public static final String COL_COURSE_TERM_REFERENCE = "term_reference";

        }
    }
    public static final class AssessmentTable {
        public static final String NAME = "assessments";
        public static final class Cols {
            public static final String UUID = "uuid";
            public static final String TITLE = "title";
            public static final String ASSESS_TYPE = "assesstype";

            public static final String DUE_DATE = "duedate";
            public static final String GOAL_DATE = "goaldate";
           public static final String COL_ASSESS_COURSE_REFERENCE = "course_reference";
        }
    }
}
</code>```

Here is my code where I insert the values to the created Course object.

```<code>
private static ContentValues getContentValues(Course course) {
        ContentValues values = new ContentValues();
        values.put(CourseTable.Cols.UUID, course.getID().toString());
        values.put(CourseTable.Cols.TITLE, course.getTitle());
        values.put(CourseTable.Cols.START_DATE, course.getStartDate().getTime());
        values.put(CourseTable.Cols.END_DATE, course.getEndDate().getTime());
        values.put(CourseTable.Cols.CHOSEN_START_DATE, course.getChosenStartDate());
        values.put(CourseTable.Cols.CHOSEN_END_DATE, course.getChosenEndDate());

        values.put(CourseTable.Cols.COURSE_STATUS, course.getCourseStatus());
        values.put(CourseTable.Cols.OPTIONAL_NOTE, course.getCourseNote());
        values.put(CourseTable.Cols.MENTOR_NAME, course.getCourseMentorName());
        values.put(CourseTable.Cols.MENTOR_PHONE, course.getCourseMentorPhone());
        values.put(CourseTable.Cols.MENTOR_EMAIL, course.getCourseMentorEmail());
</code>```

This inserts a foreign key that matches
the primary key of the term the user wants
this course to be apart of

```<code>
        values.put(CourseTable.Cols.COL_COURSE_TERM_REFERENCE, course.getTermReference());
        return values;
    }
</code>```

答:
Can I bypass foreign key constraints?

Yes,

1. Simply don't add the ForeignKey constraint.

2. Use NULL

As long as NOT NULL is not specified then set the value to NULL.

e.g. consider :-

```<code>DROP TABLE IF EXISTS course;
DROP TABLE IF EXISTS term;
CREATE TABLE IF NOT EXISTS term (id INTEGER PRIMARY KEY, termname TEXT);
INSERT INTO TERM (termname) VALUES ('Term001'),('Term002');
CREATE TABLE IF NOT EXISTS course (id INTEGER PRIMARY KEY, coursename TEXT, term_ref INTEGER REFERENCES term(id));
INSERT INTO course (coursename, term_ref) VALUES ('Course001',1),('Course002',2),('Course003',null);
SELECT * FROM course;
</code>```

which results in :-

i.e. Course003 has no related/mapped entry in the term table (in SQLite NULL is considered unique)

3. DEFERRED

Probably impractical is to utilise DEFERRABLE INITIALLY DEFERRED BUT the constraint will be applied when committed and can only be used for an explicit transaction i.e. you'd have to add the term before committing the course (hence why it would likely be impractical)

4 Intermediate table

You could introduce a schema that allows items (such as courses) to be unrelated, and then related via a mapping table that maps a course to a term etc.

Where a course has to be associated with a term (such as for a potential attendee to book the course) enforce accessing the course via the mapping table (which could have Foreign Key definitions).

Body:
I have three tables: Term, Course, and Assessment. Term is the parent to Course, and Course is the parent to Assessment. When I am creating a course there is a listview of all existing terms. The user clicks on the term they want this course to be apart of, and a foreign key gets inserted that is equivalent to the id of the selected term. This works great without foreign key constraints. When I turn foreign key constraints on, I can't create a course if a term doesn't exist, or an assessment if a course doesn't exist. Obviously if the user creates a term first, then a course, then an assessment everything works but that is not practical. Can I not have foreign keys enabled while being able to create a child before a parent?

Here is where I create my tables

@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TermDbSchema.TermTable.NAME + "(" +
                "_id integer primary key autoincrement, " +
                TermDbSchema.TermTable.Cols.UUID + ", " +
                TermDbSchema.TermTable.Cols.TITLE + ", " +
                TermDbSchema.TermTable.Cols.START_DATE + ", " +
                TermDbSchema.TermTable.Cols.END_DATE +
                ")"
        );
        db.execSQL("create table " + TermDbSchema.CourseTable.NAME + "(" +
                "_id integer primary key autoincrement, " +
                TermDbSchema.CourseTable.Cols.UUID + ", " +
                TermDbSchema.CourseTable.Cols.TITLE + ", " +
                TermDbSchema.CourseTable.Cols.START_DATE + ", " +
                TermDbSchema.CourseTable.Cols.END_DATE + ", " +
                TermDbSchema.CourseTable.Cols.CHOSEN_START_DATE + ", " +
                TermDbSchema.CourseTable.Cols.CHOSEN_END_DATE + ", " +

                TermDbSchema.CourseTable.Cols.COURSE_STATUS + ", " +
                TermDbSchema.CourseTable.Cols.OPTIONAL_NOTE + ", " +
                TermDbSchema.CourseTable.Cols.MENTOR_NAME + ", " +
                TermDbSchema.CourseTable.Cols.MENTOR_PHONE + ", " +
                TermDbSchema.CourseTable.Cols.MENTOR_EMAIL + ", " +
//this foreign key references TermTable
                TermDbSchema.CourseTable.Cols.COL_COURSE_TERM_REFERENCE + " INTEGER REFERENCES " + TermDbSchema.TermTable.NAME + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" + //<<<<<<<<<< ADDED
                ")"
        );
        db.execSQL("create table " + TermDbSchema.AssessmentTable.NAME + "(" +
                "_id integer primary key autoincrement, " +
                TermDbSchema.AssessmentTable.Cols.UUID + ", " +
                TermDbSchema.AssessmentTable.Cols.TITLE + ", " +
                TermDbSchema.AssessmentTable.Cols.ASSESS_TYPE + ", " +
                TermDbSchema.AssessmentTable.Cols.DUE_DATE + ", " +
                TermDbSchema.AssessmentTable.Cols.GOAL_DATE + ", " +
//this foreign key references CourseTable
                TermDbSchema.AssessmentTable.Cols.COL_ASSESS_COURSE_REFERENCE + " INTEGER REFERENCES " + TermDbSchema.CourseTable.NAME + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" + //<<<<<<<<<< ADDED
                //"course_reference" + " INTEGER REFERENCES " + "courses" + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" +
                ")"
        );
    }

Here is my Tables schema:

public class TermDbSchema {
    public static final class TermTable {
        public static final String NAME = "terms";
        public static final class Cols {
            public static final String UUID = "uuid";
            public static final String TITLE = "title";
            public static final String START_DATE = "startdate";
            public static final String END_DATE = "enddate";

        }
    }
    public static final class CourseTable {
        public static final String NAME = "courses";
        public static final class Cols {
            public static final String UUID = "uuid";
            public static final String TITLE = "title";
            public static final String START_DATE = "startdate";
            public static final String END_DATE = "enddate";
            public static final String CHOSEN_START_DATE = "chosenstartdate";
            public static final String CHOSEN_END_DATE = "chosenenddate";

            public static final String COURSE_STATUS = "coursestatus";
            public static final String OPTIONAL_NOTE = "optionalnote";
            public static final String MENTOR_NAME = "mentorname";
            public static final String MENTOR_PHONE = "mentorphone";
            public static final String MENTOR_EMAIL = "mentoremail";
            public static final String COL_COURSE_TERM_REFERENCE = "term_reference";

        }
    }
    public static final class AssessmentTable {
        public static final String NAME = "assessments";
        public static final class Cols {
            public static final String UUID = "uuid";
            public static final String TITLE = "title";
            public static final String ASSESS_TYPE = "assesstype";

            public static final String DUE_DATE = "duedate";
            public static final String GOAL_DATE = "goaldate";
           public static final String COL_ASSESS_COURSE_REFERENCE = "course_reference";
        }
    }
}

Here is my code where I insert the values to the created Course object.

private static ContentValues getContentValues(Course course) {
        ContentValues values = new ContentValues();
        values.put(CourseTable.Cols.UUID, course.getID().toString());
        values.put(CourseTable.Cols.TITLE, course.getTitle());
        values.put(CourseTable.Cols.START_DATE, course.getStartDate().getTime());
        values.put(CourseTable.Cols.END_DATE, course.getEndDate().getTime());
        values.put(CourseTable.Cols.CHOSEN_START_DATE, course.getChosenStartDate());
        values.put(CourseTable.Cols.CHOSEN_END_DATE, course.getChosenEndDate());

        values.put(CourseTable.Cols.COURSE_STATUS, course.getCourseStatus());
        values.put(CourseTable.Cols.OPTIONAL_NOTE, course.getCourseNote());
        values.put(CourseTable.Cols.MENTOR_NAME, course.getCourseMentorName());
        values.put(CourseTable.Cols.MENTOR_PHONE, course.getCourseMentorPhone());
        values.put(CourseTable.Cols.MENTOR_EMAIL, course.getCourseMentorEmail());

This inserts a foreign key that matches
the primary key of the term the user wants
this course to be apart of

        values.put(CourseTable.Cols.COL_COURSE_TERM_REFERENCE, course.getTermReference());
        return values;
    }

Body:
Can I bypass foreign key constraints?

Yes,

1. Simply don't add the ForeignKey constraint.

2. Use NULL

As long as NOT NULL is not specified then set the value to NULL.

e.g. consider :-

DROP TABLE IF EXISTS course;
DROP TABLE IF EXISTS term;
CREATE TABLE IF NOT EXISTS term (id INTEGER PRIMARY KEY, termname TEXT);
INSERT INTO TERM (termname) VALUES ('Term001'),('Term002');
CREATE TABLE IF NOT EXISTS course (id INTEGER PRIMARY KEY, coursename TEXT, term_ref INTEGER REFERENCES term(id));
INSERT INTO course (coursename, term_ref) VALUES ('Course001',1),('Course002',2),('Course003',null);
SELECT * FROM course;

which results in :-

i.e. Course003 has no related/mapped entry in the term table (in SQLite NULL is considered unique)

3. DEFERRED

Probably impractical is to utilise DEFERRABLE INITIALLY DEFERRED BUT the constraint will be applied when committed and can only be used for an explicit transaction i.e. you'd have to add the term before committing the course (hence why it would likely be impractical)

4 Intermediate table

You could introduce a schema that allows items (such as courses) to be unrelated, and then related via a mapping table that maps a course to a term etc.

Where a course has to be associated with a term (such as for a potential attendee to book the course) enforce accessing the course via the mapping table (which could have Foreign Key definitions).


来源: stackexchange

问:
Selecting an option element from a dropdown by its text value
Given an HTML form element like:

```<code><select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>
</code>```

I know I can select the first option with

```<code>document.getElementById("mydropdown").value='foo'
</code>```

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

答:
```<code>var desiredValue = "eggs"
var el = document.getElementById("mydropdown");
for(var i=0; i<el.options.length; i++) {
  if ( el.options[i].text == desiredValue ) {
    el.selectedIndex = i;
    break;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given an HTML form element like:

<select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>

I know I can select the first option with

document.getElementById("mydropdown").value='foo'

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?


问:
Not sending data with AJAX to database
I have a problem with catching AJAX data with PHP and send it to the database. Site is on the WordPress platform.

I have checked for the errors with mysqli_error but there nothing happened. Console not showing any error, just show there is `console.log data from the ajax, so the ajax work.

Here is what I have tried so far.

AJAX:

```<code>$.ajax({
    type: 'post',
    url: ajaxurl,
    dataType: 'json',
    data: {
         'creditCardValue':creditCardValue,
         'creditCardValueCvc':creditCardValueCvc,
         'phoneNumberForm':phoneNumberForm
    }
});
</code>```

Here is a PHP code:

```<code><?php
if (isset($_POST['button'])) { // button name from html
    $creditCardValue = $_POST['creditCardValue'];
    $creditCardValueCvc = $_POST['creditCardValueCvc'];
    $phoneNumberForm = $_POST['phoneNumberForm'];

    $query = "INSERT INTO validations(credit_card_number, credit_card_cvc, phone_number) ";
    $query .= "VALUES ({$creditCardValue}, '{$creditCardValueCvc}', '{$phoneNumberForm}' ) ";
    $create_post_query = mysqli_query($connection, $query);
}
?>
</code>```

I need to send all these data to the database so I can later call them and displayed them.

Thanks in advance.

答:
Remove the check for $_POST['button'] as this is not sent with the AJAX data. If you want to check if it's an AJAX call then just check that one of the values has been POSTed:

```<code>if (isset($_POST['creditCardValue'])) { ...
</code>```

ContentLicense: CC BY-SA 4.0

Title: Not sending data with AJAX to database

Body:
I have a problem with catching AJAX data with PHP and send it to the database. Site is on the WordPress platform.

I have checked for the errors with mysqli_error but there nothing happened. Console not showing any error, just show there is `console.log data from the ajax, so the ajax work.

Here is what I have tried so far.

AJAX:

$.ajax({
    type: 'post',
    url: ajaxurl,
    dataType: 'json',
    data: {
         'creditCardValue':creditCardValue,
         'creditCardValueCvc':creditCardValueCvc,
         'phoneNumberForm':phoneNumberForm
    }
});

Here is a PHP code:

<?php
if (isset($_POST['button'])) { // button name from html
    $creditCardValue = $_POST['creditCardValue'];
    $creditCardValueCvc = $_POST['creditCardValueCvc'];
    $phoneNumberForm = $_POST['phoneNumberForm'];

    $query = "INSERT INTO validations(credit_card_number, credit_card_cvc, phone_number) ";
    $query .= "VALUES ({$creditCardValue}, '{$creditCardValueCvc}', '{$phoneNumberForm}' ) ";
    $create_post_query = mysqli_query($connection, $query);
}
?>

I need to send all these data to the database so I can later call them and displayed them.

Thanks in advance.

Body:
Remove the check for $_POST['button'] as this is not sent with the AJAX data. If you want to check if it's an AJAX call then just check that one of the values has been POSTed:

if (isset($_POST['creditCardValue'])) { ...


问:
Remove loaded drake cache objects from RAM
I've run a plan to create a large set of objects in drake's cache. Now, outside of a plan, I ran lapply over a subset of those objects so I can summarize some of their properties and plan my next steps.

I'm using readd to load each one of these cached objects inside of the function I'm applying over, but they seem to still use up RAM after I'm done with them. That's a problem in my scenario because it's 100 GiB of RAM by the time it's finished. I'm not sure where in the environment I should be looking for them if I need to explicitly remove them.

I understand that drake is doing something similar to memoization with the cache, since if I readd the same object twice, the first one takes time to read from disk, and the second time is instantaneous. But in this scenario, I'd like to treat the cache as a simple data source like any other file, so that an object doesn't take up RAM if it's rm()'d or goes outside of the scope.

答:
Figured it out! It looks like the storr object returned by get_cache or new_cache has a flush_cache method. Calling that, then gc(), returns the memory.

Should flush_cache be documented somewhere in drake, even though it comes from storr?

I also found that if I call readd from multiple processes with mclapply, the objects don't stay in RAM, since they don't get transferred back to the main process.


问:
Remove the last part of a string after underscore and random digit
My string looks like

```<code>$img_name = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg"
</code>```

What's the easiest way to remove from the first underscore followed by a digit to the end?

I would like to output

```<code>my_beautiful_picture
</code>```

I tried

```<code>$img_name = substr($img_name, 0, strpos($img_name, "_"));
</code>```

and

```<code>$img_name = preg_replace('/_[0-9].*/', '', $img_name);
</code>```

But result is my for both, I'm not very familiar with regex.

答:
Based on the code I saw in the ideone link you posted earlier, I have an idea what might have happened. If you tried it like this before:

```<code>echo $img_name2 = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg";
echo " | ";
echo $img_name2 = substr($img_name2, 0, strpos($img_name2, "_"));
echo " | ";
echo $img_name2 = preg_replace('/_[0-9].*/', '', $img_name2);
</code>```

The reason the preg_replace looked like it didn't work is that the previous substr had already reduced $img_name2 to "my" before you used preg_replace on it. Since "my" doesn't have any underscores or numbers, that regex didn't match anything, so nothing was replaced and you just ended up with the same "my".

Body:
My string looks like

$img_name = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg"

What's the easiest way to remove from the first underscore followed by a digit to the end?

I would like to output

my_beautiful_picture

I tried

$img_name = substr($img_name, 0, strpos($img_name, "_"));

and

$img_name = preg_replace('/_[0-9].*/', '', $img_name);

But result is my for both, I'm not very familiar with regex.

Body:
Based on the code I saw in the ideone link you posted earlier, I have an idea what might have happened. If you tried it like this before:

echo $img_name2 = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg";
echo " | ";
echo $img_name2 = substr($img_name2, 0, strpos($img_name2, "_"));
echo " | ";
echo $img_name2 = preg_replace('/_[0-9].*/', '', $img_name2);

The reason the preg_replace looked like it didn't work is that the previous substr had already reduced $img_name2 to "my" before you used preg_replace on it. Since "my" doesn't have any underscores or numbers, that regex didn't match anything, so nothing was replaced and you just ended up with the same "my".


问:
Parent child relationship in ElasticSearch - search for a sentence in all the child docs combined
I am super new to Elastic Search. I have a use case which seems can be solved by the parent-child relationship. Parent doc contains the description of an NGO. Child doc contains various feedbacks sent to the NGO.

```<code>Parent Doc structure
{
    name
    address
    description
}

Child doc
{
    feedbackContent
}
</code>```

Let's say, NGO-A 4 feedbacks (meaning 4 child documents)

best teachers

best facilities

good students

location is too far

Another NGO-B  has 2 feedbacks (meaning 2 child documents)

good food quality

awesome location

The client should be able to look up the NGOs which has all the terms in the query string passed. Example - client searched for
"best" AND "location".

Since best is present in child1 and child2 and location is present in child 4, NGO-A is a valid output. However, for NGO-B child2 contains one search term and the other search term is not present in any other child doc so NGO-B is not a valid result.

I read the doc - https://blog.mimacom.com/parent-child-elasticsearch/ which is quite good but unable to conclude if this can be done.

Examples I tried

```<code>PUT message_index
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "mapping.single_type": true
  },
  "mappings": {
    "doc": {
      "properties": {
        "ngo": {"type": "text"},
        "feedback": {"type": "text"},
        "ngo_relations": {
          "type": "join",
          "relations": {
            "ngo": "feedback"
          }
        }
      }
    }
  }
}

POST message_index/doc/_bulk
{"index": {"_id":1}}
{"name":"teach for india", "ngo_relations": {"name":"ngo"}}
{"index":{"_id":2}}
{"name":"hope for autism", "ngo_relations": {"name":"ngo"}}

PUT message_index/doc/3?routing=1
{"feedback":"best food","ngo_relations":{"name":"feedback", "parent":1}}

PUT message_index/doc/4?routing=1
{"feedback":"average location","ngo_relations":{"name":"feedback", "parent":1}}

PUT message_index/doc/5?routing=1
{"feedback":"awesome staff","ngo_relations":{"name":"feedback", "parent":1}}

PUT message_index/doc/6?routing=2
{"feedback":"best teachers","ngo_relations":{"name":"feedback", "parent":2}}

PUT message_index/doc/7?routing=2
{"feedback":"awesome overload","ngo_relations":{"name":"feedback", "parent":2}}
</code>```

For best and location search, just teach for india NGO should be returned.

No hits:

```<code>GET message_index/_search
{
  "query": {
    "has_child": {
      "type": "feedback",
      "query": {
        "bool": {
          "must": {
            "term": {"feedback": "best"}
          },
          "must": {
            "term": {"feedback": "location"}
          }
        }
      }
    }
  }
}
</code>```

Both the documents are returned

```<code>GET message_index/_search
{
  "query": {
    "has_child": {
      "type": "feedback",
      "query": {
        "bool": {
          "should": {
            "term": {"feedback": "best"}
          },
          "should": {
            "term": {"feedback": "location"}
          }
        }
      }
    }
  }
}
</code>```

答:
This can be done. You were close just a small mistake in the query.

In your child query, you are performing a bool with two must/should. Therefore, your query is: Give me all documents such that they have a child such that the child has both (or 'one of the' in case of should) the terms "best" and "location".

Whereas, what you want is: Give me all documents such that they have a child such that the child has the term "best" and also have a child such that the child has the term "location".

Tweak your query as follows:

```<code>GET message_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "has_child": {
            "type": "feedback",
            "query": {
              "term": {
                "feedback": "best"
              }
            }
          }
        },
        {
          "has_child": {
            "type": "feedback",
            "query": {
              "term": {
                "feedback": "location"
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

Body:
I am super new to Elastic Search. I have a use case which seems can be solved by the parent-child relationship. Parent doc contains the description of an NGO. Child doc contains various feedbacks sent to the NGO.

Parent Doc structure
{
    name
    address
    description
}

Child doc
{
    feedbackContent
}

Let's say, NGO-A 4 feedbacks (meaning 4 child documents)

best teachers

best facilities

good students

location is too far

Another NGO-B  has 2 feedbacks (meaning 2 child documents)

good food quality

awesome location

The client should be able to look up the NGOs which has all the terms in the query string passed. Example - client searched for
"best" AND "location".

Since best is present in child1 and child2 and location is present in child 4, NGO-A is a valid output. However, for NGO-B child2 contains one search term and the other search term is not present in any other child doc so NGO-B is not a valid result.

I read the doc - https://blog.mimacom.com/parent-child-elasticsearch/ which is quite good but unable to conclude if this can be done.

Examples I tried

PUT message_index
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "mapping.single_type": true
  },
  "mappings": {
    "doc": {
      "properties": {
        "ngo": {"type": "text"},
        "feedback": {"type": "text"},
        "ngo_relations": {
          "type": "join",
          "relations": {
            "ngo": "feedback"
          }
        }
      }
    }
  }
}

POST message_index/doc/_bulk
{"index": {"_id":1}}
{"name":"teach for india", "ngo_relations": {"name":"ngo"}}
{"index":{"_id":2}}
{"name":"hope for autism", "ngo_relations": {"name":"ngo"}}

PUT message_index/doc/3?routing=1
{"feedback":"best food","ngo_relations":{"name":"feedback", "parent":1}}

PUT message_index/doc/4?routing=1
{"feedback":"average location","ngo_relations":{"name":"feedback", "parent":1}}

PUT message_index/doc/5?routing=1
{"feedback":"awesome staff","ngo_relations":{"name":"feedback", "parent":1}}

PUT message_index/doc/6?routing=2
{"feedback":"best teachers","ngo_relations":{"name":"feedback", "parent":2}}

PUT message_index/doc/7?routing=2
{"feedback":"awesome overload","ngo_relations":{"name":"feedback", "parent":2}}

For best and location search, just teach for india NGO should be returned.

No hits:

GET message_index/_search
{
  "query": {
    "has_child": {
      "type": "feedback",
      "query": {
        "bool": {
          "must": {
            "term": {"feedback": "best"}
          },
          "must": {
            "term": {"feedback": "location"}
          }
        }
      }
    }
  }
}

Both the documents are returned

GET message_index/_search
{
  "query": {
    "has_child": {
      "type": "feedback",
      "query": {
        "bool": {
          "should": {
            "term": {"feedback": "best"}
          },
          "should": {
            "term": {"feedback": "location"}
          }
        }
      }
    }
  }
}

Body:
This can be done. You were close just a small mistake in the query.

In your child query, you are performing a bool with two must/should. Therefore, your query is: Give me all documents such that they have a child such that the child has both (or 'one of the' in case of should) the terms "best" and "location".

Whereas, what you want is: Give me all documents such that they have a child such that the child has the term "best" and also have a child such that the child has the term "location".

Tweak your query as follows:

GET message_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "has_child": {
            "type": "feedback",
            "query": {
              "term": {
                "feedback": "best"
              }
            }
          }
        },
        {
          "has_child": {
            "type": "feedback",
            "query": {
              "term": {
                "feedback": "location"
              }
            }
          }
        }
      ]
    }
  }
}


问:
Swift string replace and get new range
Any better way to retrieve the Range after string replace?

Here is the current version:

```<code>let username = "apple"
msgString = "{{user}} has an apple"
guard let range = msgString.range(of: "{{user}}") else { return }
msgString.replaceSubrange(range, with username)
userRange = msgString.range(of: username)
</code>```

Does any better way to get the user name range

答:
Let's start with a corrected version of the code you gave:

```<code>let username = "apple"
var msgString = "{{user}} has an apple"
guard let range = msgString.range(of: "{{user}}") else { return }
msgString.replaceSubrange(range, with: username)
</code>```

Here, within msgString we have replaced "{{user}}" with "apple". The question is: what is the range of this "apple" within msgString?

The solution is simple when you realize that we already know the answer. It comes in two parts:

The new range starts in the same place the old range did. That is the same as saying that the lower bound of the new range is the same as the lower bound of the old range. We already know what that is: it's range.lowerBound.

The new range's length is the length of the replacement string. This is expressed its count.

Hence the desired range is:

```<code>let newRange =
    range.lowerBound..<msgString.index(range.lowerBound, offsetBy: username.count)
</code>```

If we're going to be doing a lot of this sort of thing, it might be nice to extend String. For example:

```<code>extension String {
    mutating func replaceSubrangeAndReportNewRange (
        _ bounds: Range<String.Index>, with s: String
        ) -> Range<String.Index> {
            self.replaceSubrange(bounds, with:s)
            return bounds.lowerBound..<self.index(bounds.lowerBound, offsetBy:s.count)
    }
}
</code>```

Title: Swift string replace and get new range

Body:
Any better way to retrieve the Range after string replace?

Here is the current version:

let username = "apple"
msgString = "{{user}} has an apple"
guard let range = msgString.range(of: "{{user}}") else { return }
msgString.replaceSubrange(range, with username)
userRange = msgString.range(of: username)

Does any better way to get the user name range

Body:
Let's start with a corrected version of the code you gave:

let username = "apple"
var msgString = "{{user}} has an apple"
guard let range = msgString.range(of: "{{user}}") else { return }
msgString.replaceSubrange(range, with: username)

Here, within msgString we have replaced "{{user}}" with "apple". The question is: what is the range of this "apple" within msgString?

The solution is simple when you realize that we already know the answer. It comes in two parts:

The new range starts in the same place the old range did. That is the same as saying that the lower bound of the new range is the same as the lower bound of the old range. We already know what that is: it's range.lowerBound.

The new range's length is the length of the replacement string. This is expressed its count.

Hence the desired range is:

let newRange =
    range.lowerBound..<msgString.index(range.lowerBound, offsetBy: username.count)

If we're going to be doing a lot of this sort of thing, it might be nice to extend String. For example:

extension String {
    mutating func replaceSubrangeAndReportNewRange (
        _ bounds: Range<String.Index>, with s: String
        ) -> Range<String.Index> {
            self.replaceSubrange(bounds, with:s)
            return bounds.lowerBound..<self.index(bounds.lowerBound, offsetBy:s.count)
    }
}


问:
Counting particular words
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

```<code>def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))
</code>```

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

答:
You could do it like this:</p>

```<code>w5 = list(map(len,wordlist)).count(5)
</code>```

Title: Counting particular words

Body:
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

Body:
You could do it like this:

w5 = list(map(len,wordlist)).count(5)


问:
access to nested data
I need to access structured data in a nested way but I didn't understand how to do it.

The data is structured in this way:

```<code>{'function':'data_chip',
 'group_id': 172,
 'Types': [
    {'TMS0202':'SR-20',
     'TMS0207':'SR-22',
     'TMS0201': 'TI-4000',
     'TMS0203': 'TI-450'
    }
 ]
}
</code>```

答:
to access nested data you could using
data['keyword'] or data.get('keyword', default value)

In your case that you want information on types (I assumed you want all data) you could looping on types, using something like:

```<code>datas = {'function':'data_chip',
 'group_id': 172,
 'Types': [
    {'TMS0202':'SR-20',
     'TMS0207':'SR-22',
     'TMS0201': 'TI-4000',
     'TMS0203': 'TI-450'
    }
 ]
}

for data in datas['types']:
    put your code here
</code>```

Title: access to nested data

Body:
I need to access structured data in a nested way but I didn't understand how to do it.

The data is structured in this way:

{'function':'data_chip',
 'group_id': 172,
 'Types': [
    {'TMS0202':'SR-20',
     'TMS0207':'SR-22',
     'TMS0201': 'TI-4000',
     'TMS0203': 'TI-450'
    }
 ]
}

Body:
to access nested data you could using
data['keyword'] or data.get('keyword', default value)

In your case that you want information on types (I assumed you want all data) you could looping on types, using something like:

datas = {'function':'data_chip',
 'group_id': 172,
 'Types': [
    {'TMS0202':'SR-20',
     'TMS0207':'SR-22',
     'TMS0201': 'TI-4000',
     'TMS0203': 'TI-450'
    }
 ]
}

for data in datas['types']:
    put your code here


问:
How to return object to client when https request is fired in another file?
I'm trying to have the user be able to click a button, which sends a request to my node server and then with the data sent, it fires a function thats in another file. My problem isn't with the code, I'm just new to javascript so I'm not quite sure how i should be returning this object back to the client, i'm quite lost i'll explain more in the code below. I'm not sure if I should be doing something as simple as

```<code>return obj;
</code>```

or If i should be using async/await, i've tried doing this but couldn't quite understand it.

```<code>http.createServer(function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With")
    //res.writeHead(200, { 'Content-Type': 'text/plain' });
    var data = []
    if (req.method == "POST") {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        req.on('data', function (dat) {
            data.push(dat)
        })
        req.on('end', function () {
            var gamedata = Buffer.concat(data).toString();
            var game = JSON.parse(gamedata)

            games.getPing(game.placeId, 0)<--This is the function that gets fired in the other file

            res.end(/*some how get games.gameservers here to send back to client*/)

        })
    }

}).listen(9999)
</code>```

This is my node server that is in a file called server.js.

Now here is the function that gets fired. This function is in a file called api.js

```<code>games = {
gameservers: [],

getPing: function (id,index,callback) {
    var keepAliveAgent = new https.Agent({ keepAlive: true })

    var r = https.request(options, function (res) {
        var data = []
        res.on('data', function (d) {
            data.push(d)
        }).on('end', function () {
            var buf = Buffer.concat(data)
            var encodingheader = res.headers['content-encoding']
            if (encodingheader == 'gzip') {
                zlib.gunzip(buf, function (err, buffer) {
                    var o = JSON.parse(buffer.toString())
                    // o is what is returned
                    if (index < o.TotalCollectionSize) {
                        index = index + 10;
                        //console.log(index, o.TotalCollectionSize)
                        try {
                            let lowest = o.c.reduce((lowest, item) => item.x < lowest.x ? item : lowest)
                            if (lowest.q != lowest.p) {
                               // console.log(lowest)
                                games.gameservers.push(lowest)

                            }
                            games.getPing(id, index)
                        } catch (e) {
                            if (e) {
                                console.log(games.gameservers)
                               /*
                                This is where my function ends, I need to be able to send the games.gameservers array, back to the client in cloud.js

                               */
                            }
                        }
                    }
                })
            }
        })
    })
    r.end()
}
}
</code>```

Inside the error of the try/catch, is where the function ends. Basically, the res.end() in server.js needs to have the games.gameservers object in it to go back to the client.

I'm pretty new to javascript as a whole, so i'm not sure if I should be using return, async/await, callbacks. I've been at this for awhile and cant seem to get it.

答:
In Javascript, if you use function without "return" the function will return undefined. You can't do anything with that value.
Inside your method getPing. Use return to return your games.gameservers.
Inside your http.createServer . This part , you can write like this.

const result =  [...games.getPing(game.placeId, 0)] (as you have return so this function will return your games.gameservers and assign it to result)

res.end(/some how get games.gameservers here to send back to client/)
Hope this help.

Body:
I'm trying to have the user be able to click a button, which sends a request to my node server and then with the data sent, it fires a function thats in another file. My problem isn't with the code, I'm just new to javascript so I'm not quite sure how i should be returning this object back to the client, i'm quite lost i'll explain more in the code below. I'm not sure if I should be doing something as simple as

return obj;

or If i should be using async/await, i've tried doing this but couldn't quite understand it.

http.createServer(function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With")
    //res.writeHead(200, { 'Content-Type': 'text/plain' });
    var data = []
    if (req.method == "POST") {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        req.on('data', function (dat) {
            data.push(dat)
        })
        req.on('end', function () {
            var gamedata = Buffer.concat(data).toString();
            var game = JSON.parse(gamedata)

            games.getPing(game.placeId, 0)<--This is the function that gets fired in the other file

            res.end(/*some how get games.gameservers here to send back to client*/)

        })
    }

}).listen(9999)

This is my node server that is in a file called server.js.

Now here is the function that gets fired. This function is in a file called api.js

games = {
gameservers: [],

getPing: function (id,index,callback) {
    var keepAliveAgent = new https.Agent({ keepAlive: true })

    var r = https.request(options, function (res) {
        var data = []
        res.on('data', function (d) {
            data.push(d)
        }).on('end', function () {
            var buf = Buffer.concat(data)
            var encodingheader = res.headers['content-encoding']
            if (encodingheader == 'gzip') {
                zlib.gunzip(buf, function (err, buffer) {
                    var o = JSON.parse(buffer.toString())
                    // o is what is returned
                    if (index < o.TotalCollectionSize) {
                        index = index + 10;
                        //console.log(index, o.TotalCollectionSize)
                        try {
                            let lowest = o.c.reduce((lowest, item) => item.x < lowest.x ? item : lowest)
                            if (lowest.q != lowest.p) {
                               // console.log(lowest)
                                games.gameservers.push(lowest)

                            }
                            games.getPing(id, index)
                        } catch (e) {
                            if (e) {
                                console.log(games.gameservers)
                               /*
                                This is where my function ends, I need to be able to send the games.gameservers array, back to the client in cloud.js

                               */
                            }
                        }
                    }
                })
            }
        })
    })
    r.end()
}
}

Inside the error of the try/catch, is where the function ends. Basically, the res.end() in server.js needs to have the games.gameservers object in it to go back to the client.

I'm pretty new to javascript as a whole, so i'm not sure if I should be using return, async/await, callbacks. I've been at this for awhile and cant seem to get it.


问:
Can one use If/Else statements in HTML side of Google Script WebApp?
This question is a follow-on question to: Can one create an Interactive web app with GAS?

I am writing a script that should do the following:

Ask the user for their user number

Ask the user for a row number from a spreadsheet (if they know it) and some additional info.

If they don't know the row, get the row for them and display it.

Ask them for the additional info.

This obviously requires an if/else statement. I just don't know how to form it.

I have attempted to put the code on the client and server side and neither works. I have also realized that some JS seems to run on the client side and some does not Accordingly, I have researched client side JS, in general, but not found specific rules for what works and doesn't.

html

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <center>
Enter your User ID below. If you are re-using a row in your Catalog Spreadsheet (meaning you know the row number),<br>
enter it below in the "Song ID" field, enter the Song Title, and then click the "Continue" button. Else, enter your<br>
User ID only and click the "Continue" button. We will find the next avalable empty row at the end of your Catalog<br>
Spreadsheet and display its value to you. Then you may enter it and your Song Title. After you do, click the<br>
"Continue" button to create the lyric sheet and add the new song to your Catalog Spreadsheet.<br><br>

Note: We will automatically add your name to the lyric sheet as the songwriter. Add additional writers manually<br>
on the lyric sheet.<br><br>

<div>
<input id="user" type="text" placeholder="User ID"><br><br>
<div  id="results"></div>
</div>
<input id="song" type="text" placeholder="Song ID"><br><br>
<input id="title" type="text" placeholder="Song Title"><br><br>
<input type="button" value="Continue" onclick="saveUserInput()"><br><br>
</center>
<script>

   function saveUserInput() {
     var userId = document.getElementById('userId').value;
     var songId = document.getElementById('userId').value;
      if(songId != ""){
        window.saveUserInput = function() {
         var userId = document.getElementById('userId').value;
         var songId = document.getElementById('songId').value;
         var songTitle = document.getElementById('idNewSongTitle').value;
             console.log('songTitle: ' + songTitle)
         google.script.run
             .withSuccessHandler(openPrompt)
             .getSongId({userId:userId, songId:songId, songTitle:songTitle})
      }
      }
      else {
       google.script.run
          .withSuccessHandler(function(hl){
            document.getElementById('results').innerHTML=hl;
          })
          .getSongId({userId:userId})
      }

       function openPrompt(results){
           window.open(results.url, '_blank').focus();
      }
      }
    </script>
  </body>
</html>
</code>```

gs

```<code>function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function getSongId(uObj) {
  var userId = uObj.userId;
  var songId = uObj.songId;
  var songTitle = uObj.songTitle;

   if(songId !=""){

Code not included to keep this brief, but it has been tested in other applications of this project and works and what it does is: if the user has entered a Song ID, this code creates the new lyric sheet and adds the new song name to the Catalog SS.

      }
     else{

This code does this:
     return ('The next available row for the new song is '+songId);
        }
}
</code>```

When I run what I have the Execution Transcript output is:

[19-05-29 07:54:16:951 EDT] Starting execution

[19-05-29 07:54:16:959 EDT] HtmlService.createHtmlOutputFromFile([Index]) [0 seconds]

[19-05-29 07:54:16:961 EDT] HtmlOutput.getContent() [0 seconds]

[19-05-29 07:54:16:961 EDT] HtmlOutput.getTitle() [0 seconds]

[19-05-29 07:54:16:962 EDT] Execution succeeded [0.003 seconds total runtime]

答:
Revised/Corrected html

Got this completely working. revised html is below. The final piece of the puzzle was to make the songId equal to 0 when it is not entered and then test for zero in the gs side. Because, if the songId field is left blank, it renders as "undefined" which was breaking the if/else statement on the gs side.

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <center>
Enter your User ID below.

<div>
<input id="user" type="text" placeholder="User ID"><br><br>
<div  id="results"></div>
</div>
<input id="song" type="text" placeholder="Song ID"><br><br>
<input id="title" type="text" placeholder="Song Title"><br><br>
<input type="button" value="Continue" onclick="saveUserInput()"><br><br>

</center>
<script>

   function saveUserInput() {
     var userId = document.getElementById('user').value;
     var songId = document.getElementById('song').value;
     var songTitle = document.getElementById('title').value;

         console.log('songTitle: ' + songTitle)

   // If songId is supplied by user...
   if(songId != ""){
      google.script.run
          .withSuccessHandler(openNewDoc)
          .getSongId({userId:userId, songId:songId, songTitle:songTitle})

     function openNewDoc(results){
           window.open(results.url, '_blank').focus();
   }
   }
    // If songId is blank
    else {
       var songId = 0;
       google.script.run
          .withSuccessHandler(function(hl){
            document.getElementById('results').innerHTML=hl;
          })
          .getSongId({userId:userId, songId:songId})
        }
 }
    </script>
  </body>
</html>
</code>```

Body:
This question is a follow-on question to: Can one create an Interactive web app with GAS?

I am writing a script that should do the following:

Ask the user for their user number

Ask the user for a row number from a spreadsheet (if they know it) and some additional info.

If they don't know the row, get the row for them and display it.

Ask them for the additional info.

This obviously requires an if/else statement. I just don't know how to form it.

I have attempted to put the code on the client and server side and neither works. I have also realized that some JS seems to run on the client side and some does not Accordingly, I have researched client side JS, in general, but not found specific rules for what works and doesn't.

html

<!DOCTYPE html>

    <base target="_top">

Enter your User ID below. If you are re-using a row in your Catalog Spreadsheet (meaning you know the row number),

enter it below in the "Song ID" field, enter the Song Title, and then click the "Continue" button. Else, enter your

User ID only and click the "Continue" button. We will find the next avalable empty row at the end of your Catalog

Spreadsheet and display its value to you. Then you may enter it and your Song Title. After you do, click the

"Continue" button to create the lyric sheet and add the new song to your Catalog Spreadsheet.

Note: We will automatically add your name to the lyric sheet as the songwriter. Add additional writers manually

on the lyric sheet.

<input id="user" type="text" placeholder="User ID">

<input id="song" type="text" placeholder="Song ID">

<input id="title" type="text" placeholder="Song Title">

<input type="button" value="Continue" onclick="saveUserInput()">

gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function getSongId(uObj) {
  var userId = uObj.userId;
  var songId = uObj.songId;
  var songTitle = uObj.songTitle;

   if(songId !=""){

Code not included to keep this brief, but it has been tested in other applications of this project and works and what it does is: if the user has entered a Song ID, this code creates the new lyric sheet and adds the new song name to the Catalog SS.

      }
     else{

This code does this:
     return ('The next available row for the new song is '+songId);
        }
}

When I run what I have the Execution Transcript output is:

[19-05-29 07:54:16:951 EDT] Starting execution

[19-05-29 07:54:16:959 EDT] HtmlService.createHtmlOutputFromFile([Index]) [0 seconds]

[19-05-29 07:54:16:961 EDT] HtmlOutput.getContent() [0 seconds]

[19-05-29 07:54:16:961 EDT] HtmlOutput.getTitle() [0 seconds]

[19-05-29 07:54:16:962 EDT] Execution succeeded [0.003 seconds total runtime]

Body:
Revised/Corrected html

Got this completely working. revised html is below. The final piece of the puzzle was to make the songId equal to 0 when it is not entered and then test for zero in the gs side. Because, if the songId field is left blank, it renders as "undefined" which was breaking the if/else statement on the gs side.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <center>
Enter your User ID below.

<div>
<input id="user" type="text" placeholder="User ID"><br><br>
<div  id="results"></div>
</div>
<input id="song" type="text" placeholder="Song ID"><br><br>
<input id="title" type="text" placeholder="Song Title"><br><br>
<input type="button" value="Continue" onclick="saveUserInput()"><br><br>

</center>
<script>

   function saveUserInput() {
     var userId = document.getElementById('user').value;
     var songId = document.getElementById('song').value;
     var songTitle = document.getElementById('title').value;

         console.log('songTitle: ' + songTitle)

   // If songId is supplied by user...
   if(songId != ""){
      google.script.run
          .withSuccessHandler(openNewDoc)
          .getSongId({userId:userId, songId:songId, songTitle:songTitle})

     function openNewDoc(results){
           window.open(results.url, '_blank').focus();
   }
   }
    // If songId is blank
    else {
       var songId = 0;
       google.script.run
          .withSuccessHandler(function(hl){
            document.getElementById('results').innerHTML=hl;
          })
          .getSongId({userId:userId, songId:songId})
        }
 }
    </script>
  </body>
</html>


问:
Failed to import RSA private key: "Bad Version of provider"
I have a random private key ("C:\tmp\private.key"):

```<code>-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDHikastc8+I81zCg/qWW8dMr8mqvXQ3qbPAmu0RjxoZVI47tvs
kYlFAXOf0sPrhO2nUuooJngnHV0639iTTEYG1vckNaW2R6U5QTdQ5Rq5u+uV3pMk
7w7Vs4n3urQ6jnqt2rTXbC1DNa/PFeAZatbf7ffBBy0IGO0zc128IshYcwIDAQAB
AoGBALTNl2JxTvq4SDW/3VH0fZkQXWH1MM10oeMbB2qO5beWb11FGaOO77nGKfWc
bYgfp5Ogrql4yhBvLAXnxH8bcqqwORtFhlyV68U1y4R+8WxDNh0aevxH8hRS/1X5
031DJm1JlU0E+vStiktN0tC3ebH5hE+1OxbIHSZ+WOWLYX7JAkEA5uigRgKp8ScG
auUijvdOLZIhHWq7y5Wz+nOHUuDw8P7wOTKU34QJAoWEe771p9Pf/GTA/kr0BQnP
QvWUDxGzJwJBAN05C6krwPeryFKrKtjOGJIniIoY72wRnoNcdEEs3HDRhf48YWFo
riRbZylzzzNFy/gmzT6XJQTfktGqq+FZD9UCQGIJaGrxHJgfmpDuAhMzGsUsYtTr
iRox0D1Iqa7dhE693t5aBG010OF6MLqdZA1CXrn5SRtuVVaCSLZEL/2J5UcCQQDA
d3MXucNnN4NPuS/L9HMYJWD7lPoosaORcgyK77bSSNgk+u9WSjbH1uYIAIPSffUZ
bti+jc1dUg5wb+aeZlgJAkEAurrpmpqj5vg087ZngKfFGR5rozDiTsK5DceTV97K
a3Y+Nzl+XWTxDBWk4YPh2ZlKv402hZEfWBYxUDn5ZkH/bw==
-----END RSA PRIVATE KEY-----
</code>```

I tried to use the RSACryptoServiceProvider.ImportCspBlob to import it but it failed with the error:

System.Security.Cryptography.CryptographicException: Bad Version of
  provider.

Full stack trace:

```<code>Failed: System.Security.Cryptography.CryptographicException: Bad Version of provider.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils._ImportCspBlob(Byte[] keyBlob, SafeProvHandle hProv, CspProviderFlags flags, SafeKeyHandle& hKey)
   at System.Security.Cryptography.Utils.ImportCspBlobHelper(CspAlgorithmType keyType, Byte[] keyBlob, Boolean publicOnly, CspParameters& parameters, Boolean randomKeyContainer, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
   at System.Security.Cryptography.RSACryptoServiceProvider.ImportCspBlob(Byte[] keyBlob)
   at ConsoleApplication3.Program.DecodeRSA(Byte[] data, Int32 c_data) in C:\Users\myuser\Documents\Visual Studio 2015\Projects\myproj\ConsoleApplication3\Program.cs:line 28
   at ConsoleApplication3.Program.Main(String[] args) in C:\Users\myuser\Documents\Visual Studio 2015\Projects\myproj\ConsoleApplication3\Program.cs:line 14
Press any key to continue . . .
</code>```

Any idea what I am doing wrong?

This is my code:

```<code>using System;
using System.Security.Cryptography;

namespace ConsoleApplication3
{
    class Program
    {
        static public byte[] privateKey;
        static void Main(string[] args)
        {
            try
            {
                privateKey = System.IO.File.ReadAllBytes(@"C:\tmp\private.key");
                DecodeRSA(privateKey);
            }
            catch(Exception e)
            {
                Console.WriteLine("Failed: {0}", e);
            }
        }

        static public void DecodeRSA(byte[] data)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(Program.privateKey);
            }
        }

    }
}
</code>```

答:
Your private key has a PKCS1-PEM-Format. Private key BLOBs have another format. As already mentioned in the comments, the formats are very different and cannot be easily converted (see e.g. here). Of course you can use a PKCS1-PEM-key, but it is not that easy. Here are some options:

Possibility 1:

If you use .NET Core 3.0 there is a direct support for reading a PKCS1-key (see also here):

```<code>byte[] privateKeyPkcs1PEM = File.ReadAllBytes(@"C:\tmp\private.key"); // PKCS1 - PEM
byte[] privateKeyPkcs1DER = ConvertPKCS1PemToDer(Encoding.UTF8.GetString(privateKeyPkcs1PEM));
RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(privateKeyPkcs1DER, out _);

// use e.g. rsa.Decrypt(...)
</code>```

However, the ImportRSAPrivateKey-method can only process the DER-format which is essentially the binary format of the PEM-format (for more details see here or here). Thus, you have to convert the PEM-format into the DER-format with something like

```<code>private static byte[] ConvertPKCS1PemToDer(string pemContents)
{
    return Convert.FromBase64String(pemContents
        .TrimStart("-----BEGIN RSA PRIVATE KEY-----".ToCharArray())
        .TrimEnd("-----END RSA PRIVATE KEY-----".ToCharArray())
        .Replace("\r\n",""));
}
</code>```

Alternatively, OpenSSL can also be used for the conversion:

```<code>openssl rsa -inform PEM -outform DER -in C:\tmp\private.key -out C:\tmp\private.der
</code>```

Possibility 2:

You can convert your PKCS1-PEM-key into an PKCS8-DER-key using OpenSSL. The appropriate command is:

```<code>openssl pkcs8 -topk8 -inform pem -in C:\tmp\private.key -outform der -nocrypt -out C:\tmp\privatepkcs8.der
</code>```

The difference between PKCS1- and PKCS8-format is explained here. Then you can import the key with built-in .NET-methods (see also here, section PKCS#8 PrivateKeyInfo):

```<code>byte[] privateKeyPkcs8DER = File.ReadAllBytes(@"C:\tmp\privatepkcs8.der"); // PKCS8 - DER
CngKey cngKey = CngKey.Import(privateKeyPkcs8DER, CngKeyBlobFormat.Pkcs8PrivateBlob);
RSA rsa = new RSACng(cngKey);

// use e.g. rsa.Decrypt(...)
</code>```

Possibility 3:

If third-party-libraries may be used, BouncyCastle is also a possibility:

```<code>StreamReader reader = File.OpenText(@"C:\tmp\private.key"); // PKCS1 - PEM
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding(new RsaEngine());

// E.g. decryption
pkcs1Encoding.Init(false, keyPair.Private);
byte[] decrypted = pkcs1Encoding.ProcessBlock(encrypted, 0, encrypted.Length);
</code>```

Possibility 4:

Another possibility is the use of the DecodeRSAPrivateKey-method from JavaScience which can process a PKCS1-key. However, the DecodeRSAPrivateKey-method can only process the DER-format. Thus, you must first manually convert the PEM-format into the DER-format using e.g. ConvertPKCS1PemToDer or OpenSSL.

Body:
I have a random private key ("C:\tmp\private.key"):

-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDHikastc8+I81zCg/qWW8dMr8mqvXQ3qbPAmu0RjxoZVI47tvs
kYlFAXOf0sPrhO2nUuooJngnHV0639iTTEYG1vckNaW2R6U5QTdQ5Rq5u+uV3pMk
7w7Vs4n3urQ6jnqt2rTXbC1DNa/PFeAZatbf7ffBBy0IGO0zc128IshYcwIDAQAB
AoGBALTNl2JxTvq4SDW/3VH0fZkQXWH1MM10oeMbB2qO5beWb11FGaOO77nGKfWc
bYgfp5Ogrql4yhBvLAXnxH8bcqqwORtFhlyV68U1y4R+8WxDNh0aevxH8hRS/1X5
031DJm1JlU0E+vStiktN0tC3ebH5hE+1OxbIHSZ+WOWLYX7JAkEA5uigRgKp8ScG
auUijvdOLZIhHWq7y5Wz+nOHUuDw8P7wOTKU34QJAoWEe771p9Pf/GTA/kr0BQnP
QvWUDxGzJwJBAN05C6krwPeryFKrKtjOGJIniIoY72wRnoNcdEEs3HDRhf48YWFo
riRbZylzzzNFy/gmzT6XJQTfktGqq+FZD9UCQGIJaGrxHJgfmpDuAhMzGsUsYtTr
iRox0D1Iqa7dhE693t5aBG010OF6MLqdZA1CXrn5SRtuVVaCSLZEL/2J5UcCQQDA
d3MXucNnN4NPuS/L9HMYJWD7lPoosaORcgyK77bSSNgk+u9WSjbH1uYIAIPSffUZ
bti+jc1dUg5wb+aeZlgJAkEAurrpmpqj5vg087ZngKfFGR5rozDiTsK5DceTV97K
a3Y+Nzl+XWTxDBWk4YPh2ZlKv402hZEfWBYxUDn5ZkH/bw==
-----END RSA PRIVATE KEY-----

I tried to use the RSACryptoServiceProvider.ImportCspBlob to import it but it failed with the error:

System.Security.Cryptography.CryptographicException: Bad Version of
  provider.

Full stack trace:

Failed: System.Security.Cryptography.CryptographicException: Bad Version of provider.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils._ImportCspBlob(Byte[] keyBlob, SafeProvHandle hProv, CspProviderFlags flags, SafeKeyHandle& hKey)
   at System.Security.Cryptography.Utils.ImportCspBlobHelper(CspAlgorithmType keyType, Byte[] keyBlob, Boolean publicOnly, CspParameters& parameters, Boolean randomKeyContainer, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
   at System.Security.Cryptography.RSACryptoServiceProvider.ImportCspBlob(Byte[] keyBlob)
   at ConsoleApplication3.Program.DecodeRSA(Byte[] data, Int32 c_data) in C:\Users\myuser\Documents\Visual Studio 2015\Projects\myproj\ConsoleApplication3\Program.cs:line 28
   at ConsoleApplication3.Program.Main(String[] args) in C:\Users\myuser\Documents\Visual Studio 2015\Projects\myproj\ConsoleApplication3\Program.cs:line 14
Press any key to continue . . .

Any idea what I am doing wrong?

This is my code:

using System;
using System.Security.Cryptography;

namespace ConsoleApplication3
{
    class Program
    {
        static public byte[] privateKey;
        static void Main(string[] args)
        {
            try
            {
                privateKey = System.IO.File.ReadAllBytes(@"C:\tmp\private.key");
                DecodeRSA(privateKey);
            }
            catch(Exception e)
            {
                Console.WriteLine("Failed: {0}", e);
            }
        }

        static public void DecodeRSA(byte[] data)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(Program.privateKey);
            }
        }

    }
}

Body:
Your private key has a PKCS1-PEM-Format. Private key BLOBs have another format. As already mentioned in the comments, the formats are very different and cannot be easily converted (see e.g. here). Of course you can use a PKCS1-PEM-key, but it is not that easy. Here are some options:

Possibility 1:

If you use .NET Core 3.0 there is a direct support for reading a PKCS1-key (see also here):

byte[] privateKeyPkcs1PEM = File.ReadAllBytes(@"C:\tmp\private.key"); // PKCS1 - PEM
byte[] privateKeyPkcs1DER = ConvertPKCS1PemToDer(Encoding.UTF8.GetString(privateKeyPkcs1PEM));
RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(privateKeyPkcs1DER, out _);

// use e.g. rsa.Decrypt(...)

However, the ImportRSAPrivateKey-method can only process the DER-format which is essentially the binary format of the PEM-format (for more details see here or here). Thus, you have to convert the PEM-format into the DER-format with something like

private static byte[] ConvertPKCS1PemToDer(string pemContents)
{
    return Convert.FromBase64String(pemContents
        .TrimStart("-----BEGIN RSA PRIVATE KEY-----".ToCharArray())
        .TrimEnd("-----END RSA PRIVATE KEY-----".ToCharArray())
        .Replace("\r\n",""));
}

Alternatively, OpenSSL can also be used for the conversion:

openssl rsa -inform PEM -outform DER -in C:\tmp\private.key -out C:\tmp\private.der

Possibility 2:

You can convert your PKCS1-PEM-key into an PKCS8-DER-key using OpenSSL. The appropriate command is:

openssl pkcs8 -topk8 -inform pem -in C:\tmp\private.key -outform der -nocrypt -out C:\tmp\privatepkcs8.der

The difference between PKCS1- and PKCS8-format is explained here. Then you can import the key with built-in .NET-methods (see also here, section PKCS#8 PrivateKeyInfo):

byte[] privateKeyPkcs8DER = File.ReadAllBytes(@"C:\tmp\privatepkcs8.der"); // PKCS8 - DER
CngKey cngKey = CngKey.Import(privateKeyPkcs8DER, CngKeyBlobFormat.Pkcs8PrivateBlob);
RSA rsa = new RSACng(cngKey);

// use e.g. rsa.Decrypt(...)

Possibility 3:

If third-party-libraries may be used, BouncyCastle is also a possibility:

StreamReader reader = File.OpenText(@"C:\tmp\private.key"); // PKCS1 - PEM
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding(new RsaEngine());

// E.g. decryption
pkcs1Encoding.Init(false, keyPair.Private);
byte[] decrypted = pkcs1Encoding.ProcessBlock(encrypted, 0, encrypted.Length);

Possibility 4:

Another possibility is the use of the DecodeRSAPrivateKey-method from JavaScience which can process a PKCS1-key. However, the DecodeRSAPrivateKey-method can only process the DER-format. Thus, you must first manually convert the PEM-format into the DER-format using e.g. ConvertPKCS1PemToDer or OpenSSL.


问:
Problems calling a variadic Java function from Clojure
I'm having a play with the Java NIO.2 API from JDK 7.

In particular, I want to call the method: Paths#get(String first, String... more)

This is a static method which takes in at least one string, and returns a Path object corresponding to it. There's an overloaded form: Paths#get(URI uri)

However, I can't seem to call the top method from Clojure. The nearest I can seem to get is this:

```<code>(Paths/get ^String dir-fq (object-array 0))
</code>```

which fails with:

```<code>java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
</code>```

as you might expect. After all, we're passing in an Object[] to something that's expecting String[].

I've tried removing the (object-array) form - but that just causes Clojure to try to call the get(URI) method - both with and without the type hint.

Passing nil as the second argument to Paths#get(String, String...) causes the right method to be called, but Java 7 then fails with an NPE.

I can't seem to find a way in Clojure to express the type String[] - I'm guessing I either need to do that or provide a hint to the dispatch system.

Any ideas?

答:
As you noticed, it doesn't want an Object[], it wants a String[]. object-array does exactly what it says: it makes an array of objects. If you want to create an array with some different type, make-array and into-array are your friends. For example here:

```<code>(Paths/get "foo" (into-array String ["bar" "baz"]))
</code>```

The String specifier there is optional in this case: if you leave out the array's desired type, Clojure uses the type of the first object as the array's component type.

Body:
I'm having a play with the Java NIO.2 API from JDK 7.

In particular, I want to call the method: Paths#get(String first, String... more)

This is a static method which takes in at least one string, and returns a Path object corresponding to it. There's an overloaded form: Paths#get(URI uri)

However, I can't seem to call the top method from Clojure. The nearest I can seem to get is this:

(Paths/get ^String dir-fq (object-array 0))

which fails with:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

as you might expect. After all, we're passing in an Object[] to something that's expecting String[].

I've tried removing the (object-array) form - but that just causes Clojure to try to call the get(URI) method - both with and without the type hint.

Passing nil as the second argument to Paths#get(String, String...) causes the right method to be called, but Java 7 then fails with an NPE.

I can't seem to find a way in Clojure to express the type String[] - I'm guessing I either need to do that or provide a hint to the dispatch system.

Any ideas?

Body:
As you noticed, it doesn't want an Object[], it wants a String[]. object-array does exactly what it says: it makes an array of objects. If you want to create an array with some different type, make-array and into-array are your friends. For example here:

(Paths/get "foo" (into-array String ["bar" "baz"]))

The String specifier there is optional in this case: if you leave out the array's desired type, Clojure uses the type of the first object as the array's component type.


问:
Custom templates callInWindow
I am using the new custom template feature but I am still fairly new to the general concept and I was looking for opinions on the following code, I want to call a global function that sits on my application from GTM, will this code work for my custom tag?

```<code>const log = require('logToConsole'); // Console api
const query = require('queryPermission'); // Query api
const callInWindow = require('callInWindow'); // Call function in window api

if (query('access_globals', 'execute', 'OBJ.tracking.add')) { // Trying to access the method
    log('data =', data); // USE ONLY IN DEBUG
    callInWindow( 'OBJ.tracking.add' , [data.tagLabel, data.tagDetail]); // Send event
    data.gtmOnSuccess();
}
else {
  data.gtmOnFailure();
}
</code>```

Where OBJ.tracking.add has execute only permissions.
Thanks!

答: Elke's answer is correct in that the copyFromWindow api does a deep copy of objects. The callInWindow api will call the actual object on window, passing it the rest of the arguments. In your case you probably want to call callInWindow passing the label as the second argument, and the detail as the third, unless Obj.tracking.add expects an array as an argument. </p>

Title: Custom templates callInWindow

Body:
I am using the new custom template feature but I am still fairly new to the general concept and I was looking for opinions on the following code, I want to call a global function that sits on my application from GTM, will this code work for my custom tag?

const log = require('logToConsole'); // Console api
const query = require('queryPermission'); // Query api
const callInWindow = require('callInWindow'); // Call function in window api

if (query('access_globals', 'execute', 'OBJ.tracking.add')) { // Trying to access the method
    log('data =', data); // USE ONLY IN DEBUG
    callInWindow( 'OBJ.tracking.add' , [data.tagLabel, data.tagDetail]); // Send event
    data.gtmOnSuccess();
}
else {
  data.gtmOnFailure();
}

Where OBJ.tracking.add has execute only permissions.
Thanks!


问:
How can I generate every combination of pattern of 4 numbers and 2 A-Z characters
I wrote a small script to talk with a database that I got from a friend so I can link a dutch zip code with a street name. But I want to do it by myself

The ZIP codes are build up like NNNNCC where N is a number 0-9 (Ignoring the first 0's 0000-0999 isn't possible) and C = character A-Z.

How can I generate every possible combination in PHP?

答:
You could do it with a simple pager like function to avoid the memory issue:</p>

```<code><?php

function codeRange(int $start, int $end) {
    $codes = [];
    $number = $start - 1;
    while ($number++ !== $end + 1) {
        $letter = 'AA';
        while ($letter !== 'AAA') {
            $codes[] = sprintf('%s%s', $number, $letter++);
        }
    }

    return $codes;
}

echo codeRange(1000, 1010)[0] . PHP_EOL;       // output: 1000AA
echo codeRange(1000, 1010)[1] . PHP_EOL;       // output: 1000AB
echo codeRange(1000, 1010)[2] . PHP_EOL;       // output: 1000AC
echo codeRange(1000, 1010)[7434] . PHP_EOL;    // output: 1010ZY
echo codeRange(1000, 1010)[7435] . PHP_EOL;    // output: 1010ZZ
echo codeRange(9979, 9998)[0] . PHP_EOL;       // output: 9979AA
echo codeRange(9979, 9998)[14195] . PHP_EOL;   // output: 9999ZZ
</code>```

Body:
You could do it with a simple pager like function to avoid the memory issue:

<?php

function codeRange(int $start, int $end) {
    $codes = [];
    $number = $start - 1;
    while ($number++ !== $end + 1) {
        $letter = 'AA';
        while ($letter !== 'AAA') {
            $codes[] = sprintf('%s%s', $number, $letter++);
        }
    }

    return $codes;
}

echo codeRange(1000, 1010)[0] . PHP_EOL;       // output: 1000AA
echo codeRange(1000, 1010)[1] . PHP_EOL;       // output: 1000AB
echo codeRange(1000, 1010)[2] . PHP_EOL;       // output: 1000AC
echo codeRange(1000, 1010)[7434] . PHP_EOL;    // output: 1010ZY
echo codeRange(1000, 1010)[7435] . PHP_EOL;    // output: 1010ZZ
echo codeRange(9979, 9998)[0] . PHP_EOL;       // output: 9979AA
echo codeRange(9979, 9998)[14195] . PHP_EOL;   // output: 9999ZZ


问:
Access groovy variable in powershell
In Jenkins, I have created a foldable section controlled by a checkbox using groovy as below

groovy script:

```<code>        html =
        '''
        <form>
          Threads:<br>
          <input type="text" name="Threads"><br>
          Duration:<br>
          <input type="text" name="Duration"><br>
          RampUP:<br>
          <input type="text" name="RampUP"><br>
        </form>
        '''
        if (Override_Execution_Details .equals("Yes"))
        {return html}
</code>```

above code will open the fields as we select the checkbox

How to access the values of textbox field like threads, duration on my PowerShell code in build section.

I have made some below changes

and tried to access 'Threads' value '1234'
as $env:Threads; But it's not working. Please anyone can assist me.

答:
You are showing what you built but not what you've tried and either got errors with or had issues with. So, engenders assumptions on our part. So, since you did not provide code to examine, It's a bit of a challenge to give you a code response. Well, that and I have never used or even seen Jenkins, just folks talking about it on the forums/Q&A sites and the like.

PowerShell is not the tool to use for GUI automation. If you try, out of the box, you are limited to SendKeys, but mostly that is for sending stuff to on taking actions on a GUI, which do work, but can be unreliable in several instances.

You seem to be saying you want to copy stuff from the GUI, which you can do with SendKey7s, but again, my previous comment stands. So, you need a GUI automation tool that is more robust. See:

AutoIT and it's PowerShell cmdlets or similar tools, like Selenium.

Lastly, if it is just HTML, on the back end, you can get to that as long as you know the element you want. Yet, me not knowing anything about Jenkins, this screen shot looks like a fat x86/x64 GUI form. So, you have to access the form elements to get to content, just as you would with WinForms or WPF.

WF example:

```<code># build form, take user input, output to screen

 function Get-URL
 {
   [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

   $Form = New-Object System.Windows.Forms.Form
   $Form.width = 300
   $Form.height = 110
   $Form.Text = ”Please enter a URL”

   $txtURL = new-object System.Windows.Forms.TextBox;
   $txtURL.Location = new-object System.Drawing.Size(130,7)
   $txtURL.Size = new-object System.Drawing.Size(130,30)
   $Form.Controls.Add($txtURL)

   $lblURL = new-object System.Windows.Forms.Label
   $lblURL.Location = new-object System.Drawing.Size(10,10)
   $lblURL.size = new-object System.Drawing.Size(130,20)
   $lblURL.Text = "Please enter a URL:"
   $Form.Controls.Add($lblURL)

   $btnSubmit = new-object System.Windows.Forms.Button
   $btnSubmit.Location = new-object System.Drawing.Size(100,40)
   $btnSubmit.Size = new-object System.Drawing.Size(100,20)
   $btnSubmit.Text = "Submit"
   $btnSubmit.Add_Click({Return-Get-URL})
   $form.Controls.Add($btnSubmit)

   $Form.Add_Shown({$Form.Activate()})
   $x = $Form.ShowDialog()
   return $txtURL.Text
 }

function Return-Get-URL
{ $Form.Close() }

( $url = Get-URL )
</code>```

Title: Access groovy variable in powershell

Body:
In Jenkins, I have created a foldable section controlled by a checkbox using groovy as below

groovy script:

        html =
        '''
        <form>
          Threads:

          <input type="text" name="Threads">

          Duration:

          <input type="text" name="Duration">

          RampUP:

          <input type="text" name="RampUP">

        </form>
        '''
        if (Override_Execution_Details .equals("Yes"))
        {return html}

above code will open the fields as we select the checkbox

How to access the values of textbox field like threads, duration on my PowerShell code in build section.

I have made some below changes

and tried to access 'Threads' value '1234'
as $env:Threads; But it's not working. Please anyone can assist me.

Body:
You are showing what you built but not what you've tried and either got errors with or had issues with. So, engenders assumptions on our part. So, since you did not provide code to examine, It's a bit of a challenge to give you a code response. Well, that and I have never used or even seen Jenkins, just folks talking about it on the forums/Q&A sites and the like.

PowerShell is not the tool to use for GUI automation. If you try, out of the box, you are limited to SendKeys, but mostly that is for sending stuff to on taking actions on a GUI, which do work, but can be unreliable in several instances.

You seem to be saying you want to copy stuff from the GUI, which you can do with SendKey7s, but again, my previous comment stands. So, you need a GUI automation tool that is more robust. See:

AutoIT and it's PowerShell cmdlets or similar tools, like Selenium.

Lastly, if it is just HTML, on the back end, you can get to that as long as you know the element you want. Yet, me not knowing anything about Jenkins, this screen shot looks like a fat x86/x64 GUI form. So, you have to access the form elements to get to content, just as you would with WinForms or WPF.

WF example:

# build form, take user input, output to screen

 function Get-URL
 {
   [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

   $Form = New-Object System.Windows.Forms.Form
   $Form.width = 300
   $Form.height = 110
   $Form.Text = ”Please enter a URL”

   $txtURL = new-object System.Windows.Forms.TextBox;
   $txtURL.Location = new-object System.Drawing.Size(130,7)
   $txtURL.Size = new-object System.Drawing.Size(130,30)
   $Form.Controls.Add($txtURL)

   $lblURL = new-object System.Windows.Forms.Label
   $lblURL.Location = new-object System.Drawing.Size(10,10)
   $lblURL.size = new-object System.Drawing.Size(130,20)
   $lblURL.Text = "Please enter a URL:"
   $Form.Controls.Add($lblURL)

   $btnSubmit = new-object System.Windows.Forms.Button
   $btnSubmit.Location = new-object System.Drawing.Size(100,40)
   $btnSubmit.Size = new-object System.Drawing.Size(100,20)
   $btnSubmit.Text = "Submit"
   $btnSubmit.Add_Click({Return-Get-URL})
   $form.Controls.Add($btnSubmit)

   $Form.Add_Shown({$Form.Activate()})
   $x = $Form.ShowDialog()
   return $txtURL.Text
 }

function Return-Get-URL
{ $Form.Close() }

( $url = Get-URL )


问:
Case classes - Copy multiple fields with transforms
I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.

I have found a few examples of how to do this using shapeless (e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?

Simplified code example;

```<code>import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]

val freddie = new A(1,"Freddie","somestring")

val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")

val freddieB = bGen.from(record +
  (Symbol("fieldARenamed") ->> atmp) +
  (Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.
</code>```

I have a feeling Align is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field, as in that third link above - would be interesting.

In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.

EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;

```<code>val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)
</code>```

See below comment for various reasons why this is inappropriate.

答:
Just FYI, here's one way to get your question code to work.</p>

```<code>import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.{Align,Intersection}
import shapeless.syntax.singleton._

case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val fromGen = LabelledGeneric[A]
val toGen   = LabelledGeneric[B]

val freddie = A(1, "Freddie", "somestring")
val putARename = Symbol("fieldARenamed")     ->> freddie.fieldA
val putCTrans  = Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase

trait Field { type K; type V; type F = FieldType[K, V] }
object Field {
  def apply[K0,V0](sample: FieldType[K0,V0]) =
    new Field { type K = K0; type V = V0 }
}

val pFieldA  = Field(putARename)
val pFieldCT = Field(putCTrans)

val inter = Intersection[pFieldA.F :: pFieldCT.F :: fromGen.Repr, toGen.Repr]
val align = Align[inter.Out, toGen.Repr]

toGen.from(align(inter(putARename :: putCTrans :: fromGen.to(freddie))))
//res0: B = B(1,Freddie,somestring,SOMESTRING)
</code>```

Body:
I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.

I have found a few examples of how to do this using shapeless (e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?

Simplified code example;

import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]

val freddie = new A(1,"Freddie","somestring")

val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")

val freddieB = bGen.from(record +
  (Symbol("fieldARenamed") ->> atmp) +
  (Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.

I have a feeling Align is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field, as in that third link above - would be interesting.

In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.

EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;

val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)

See below comment for various reasons why this is inappropriate.

Body:
Just FYI, here's one way to get your question code to work.

import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.{Align,Intersection}
import shapeless.syntax.singleton._

case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val fromGen = LabelledGeneric[A]
val toGen   = LabelledGeneric[B]

val freddie = A(1, "Freddie", "somestring")
val putARename = Symbol("fieldARenamed")     ->> freddie.fieldA
val putCTrans  = Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase

trait Field { type K; type V; type F = FieldType[K, V] }
object Field {
  def apply[K0,V0](sample: FieldType[K0,V0]) =
    new Field { type K = K0; type V = V0 }
}

val pFieldA  = Field(putARename)
val pFieldCT = Field(putCTrans)

val inter = Intersection[pFieldA.F :: pFieldCT.F :: fromGen.Repr, toGen.Repr]
val align = Align[inter.Out, toGen.Repr]

toGen.from(align(inter(putARename :: putCTrans :: fromGen.to(freddie))))
//res0: B = B(1,Freddie,somestring,SOMESTRING)


问:
Executing a TCL script from line N
I have a TCL script that say, has 30 lines of automation code which I am executing in the dc shell (Synopsys Design Compiler). I want to stop and exit the script at line 10, exit the dc shell and bring it back up again after performing a manual review. However, this time, I want to run the script starting from line number 11, without having to execute the first 10 lines.

Instead of having two scripts, one which contains code till line number 10 and the other having the rest, I would like to make use of only one script and try to execute it from, let's say, line number N.

Something like:
    source a.tcl -line 11

How can I do this?

答:
If you have Tcl 8.6+ and if you consider re-modelling your script on top of a Tcl coroutine, you can realise this continuation behaviour in a few lines. This assumes that you run the script from an interactive Tcl shell (dc shell?).

```<code># script.tcl
if {[info procs allSteps] eq ""} {
    # We are not re-entering (continuing), so start all over.
    proc allSteps {args} {
      yield; # do not run when defining the coroutine;
      puts 1
      puts 2
      puts 3
      yield; # step out, once first sequence of steps (1-10) has been executed
      puts 4
      puts 5
      puts 6
      rename allSteps ""; # self-clean, once the remainder of steps (11-N) have run
    }
    coroutine nextSteps allSteps
}

nextSteps; # run coroutine
</code>```

Pack your script into a proc body (allSteps).

Within the proc body: Place a yield to indicate the hold/ continuation point after your first steps (e.g., after the 10th step).

Create a coroutine nextSteps based on allSteps.

Protect the proc and coroutine definitions in a way that they do not cause a re-definition (when steps are pending)

Then, start your interactive shell and run source script.tcl:

```<code>% source script.tcl
1
2
3
</code>```

Now, perform your manual review. Then, continue from within the same shell:

```<code>% source script.tcl
4
5
6
</code>```

Note that you can run the overall 2-phased sequence any number of times (because of the self-cleanup of the coroutine proc: rename):

```<code>% source script.tcl
1
2
3
% source script.tcl
4
5
6
</code>```

Again: All this assumes that you do not exit from the shell, and maintain your shell while performing your review. If you need to exit from the shell, for whatever reason (or you cannot run Tcl 8.6+), then Donal's suggestion is the way to go.

Update

If applicable in your case, you may improve the implementation by using an anonymous (lambda) proc. This simplifies the lifecycle management (avoiding re-definition, managing coroutine and proc, no need for a rename):

```<code># script.tcl
if {[info commands nextSteps] eq ""} {
    # We are not re-entering (continuing), so start all over.
    coroutine nextSteps apply {args {
      yield; # do not run when defining the coroutine;
      puts 1
      puts 2
      puts 3
      yield; # step out, once first sequence of steps (1-10) has been executed
      puts 4
      puts 5
      puts 6
    }}
}

nextSteps
</code>```

Title: Executing a TCL script from line N

Body:
If you have Tcl 8.6+ and if you consider re-modelling your script on top of a Tcl coroutine, you can realise this continuation behaviour in a few lines. This assumes that you run the script from an interactive Tcl shell (dc shell?).

# script.tcl
if {[info procs allSteps] eq ""} {
    # We are not re-entering (continuing), so start all over.
    proc allSteps {args} {
      yield; # do not run when defining the coroutine;
      puts 1
      puts 2
      puts 3
      yield; # step out, once first sequence of steps (1-10) has been executed
      puts 4
      puts 5
      puts 6
      rename allSteps ""; # self-clean, once the remainder of steps (11-N) have run
    }
    coroutine nextSteps allSteps
}

nextSteps; # run coroutine

Pack your script into a proc body (allSteps).

Within the proc body: Place a yield to indicate the hold/ continuation point after your first steps (e.g., after the 10th step).

Create a coroutine nextSteps based on allSteps.

Protect the proc and coroutine definitions in a way that they do not cause a re-definition (when steps are pending)

Then, start your interactive shell and run source script.tcl:

% source script.tcl
1
2
3

Now, perform your manual review. Then, continue from within the same shell:

% source script.tcl
4
5
6

Note that you can run the overall 2-phased sequence any number of times (because of the self-cleanup of the coroutine proc: rename):

% source script.tcl
1
2
3
% source script.tcl
4
5
6

Again: All this assumes that you do not exit from the shell, and maintain your shell while performing your review. If you need to exit from the shell, for whatever reason (or you cannot run Tcl 8.6+), then Donal's suggestion is the way to go.

Update

If applicable in your case, you may improve the implementation by using an anonymous (lambda) proc. This simplifies the lifecycle management (avoiding re-definition, managing coroutine and proc, no need for a rename):

# script.tcl
if {[info commands nextSteps] eq ""} {
    # We are not re-entering (continuing), so start all over.
    coroutine nextSteps apply {args {
      yield; # do not run when defining the coroutine;
      puts 1
      puts 2
      puts 3
      yield; # step out, once first sequence of steps (1-10) has been executed
      puts 4
      puts 5
      puts 6
    }}
}

nextSteps


问:
How to add navigationController to existing tab application?
I have an iPhone application with 2 tabs. This is my application delegate:

```<code> (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
 }
</code>```

My first tab is a subclass of UITableViewController. I would like to push a new view controller when someone clicks on a row of my table. I know that this is done in didSelectRowAtIndexPath like this:

```<code>TableViewDetailViewController *fvController = [[TableViewDetailViewController alloc] initWithNibName:@"TableViewDetailViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:fvController animated:YES];
    [fvController release];
    fvController = nil;
</code>```

My self.navigationController is NIL so nothing gets pushed to the view stack. Where should I create my navigationController, so there would be as little code to change as possible?

答:
We have direct solution using Interface builder.

In interface builder go to xib in which you have added tabBarController and delete the tabBarItem with which you have connected your tableViewController .

Now, drag and drop an UINavigationController from library in your tabBar and set this navigationController's rootViewController as your tableViewController.

Thanks

Body:
I have an iPhone application with 2 tabs. This is my application delegate:

 (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
 }

My first tab is a subclass of UITableViewController. I would like to push a new view controller when someone clicks on a row of my table. I know that this is done in didSelectRowAtIndexPath like this:

TableViewDetailViewController *fvController = [[TableViewDetailViewController alloc] initWithNibName:@"TableViewDetailViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:fvController animated:YES];
    [fvController release];
    fvController = nil;

My self.navigationController is NIL so nothing gets pushed to the view stack. Where should I create my navigationController, so there would be as little code to change as possible?


问:
Triggers - How to change another column when one is updated - MySQL
I have been given a use case where an user needs to update a certain TIME field if other of the same type changes.

I have been given two columns

horario_arribo (TIME)

horario_salida (TIME)

Now, what I need to do is the followin

Make a trigger so when I change for example horario_arribo, horario_salida is the same TIME as horario_arribo minus 1 hour, and the same if I update horario_salida , make horario_arribo plus 1 hour.

I have been thinking how to do it, first check if the value trying to be updated is horario_salida, then I just add 1 hour to horario_arribo, or if  I'm updating horario_arribo, to the same to horario_salida but minus 1 hour.

```<code>DELIMITER //
CREATE TRIGGER modificar_horarioruta AFTER
UPDATE ON ruta
FOR EACH ROW
BEGIN
IF(new.horario_salida) THEN
  SET AddTime(old.horario_arribo, '00:60:00')
ELSE
  SET AddTime(old.horario_salida, Here I dont know how to minus 1 hour to that)
END IF;
END //
DELIMITER ;
</code>```

This is the data I have

So , in short, if I update horario_salida, horario_arribo need to be 1 hour ahead, if I update horario_arribo, horario_salida needs to be 1 hour less.

Thanks

答:
IIUC:

```<code>DELIMITER //
CREATE TRIGGER modificar_horarioruta AFTER
UPDATE ON ruta
FOR EACH ROW
BEGIN
IF (NEW.horario_salida) THEN
  SET NEW.horario_arribo = OLD.horario_arribo + 1;
ELSE
  SET NEW.horario_salida = OLD.horario_salida - 1;
END IF;
END //
DELIMITER ;
</code>```

Let me know if this is not what you need.

Body:
I have been given a use case where an user needs to update a certain TIME field if other of the same type changes.

I have been given two columns

horario_arribo (TIME)

horario_salida (TIME)

Now, what I need to do is the followin

Make a trigger so when I change for example horario_arribo, horario_salida is the same TIME as horario_arribo minus 1 hour, and the same if I update horario_salida , make horario_arribo plus 1 hour.

I have been thinking how to do it, first check if the value trying to be updated is horario_salida, then I just add 1 hour to horario_arribo, or if  I'm updating horario_arribo, to the same to horario_salida but minus 1 hour.

DELIMITER //
CREATE TRIGGER modificar_horarioruta AFTER
UPDATE ON ruta
FOR EACH ROW
BEGIN
IF(new.horario_salida) THEN
  SET AddTime(old.horario_arribo, '00:60:00')
ELSE
  SET AddTime(old.horario_salida, Here I dont know how to minus 1 hour to that)
END IF;
END //
DELIMITER ;

This is the data I have

So , in short, if I update horario_salida, horario_arribo need to be 1 hour ahead, if I update horario_arribo, horario_salida needs to be 1 hour less.

Thanks

Body:
IIUC:

DELIMITER //
CREATE TRIGGER modificar_horarioruta AFTER
UPDATE ON ruta
FOR EACH ROW
BEGIN
IF (NEW.horario_salida) THEN
  SET NEW.horario_arribo = OLD.horario_arribo + 1;
ELSE
  SET NEW.horario_salida = OLD.horario_salida - 1;
END IF;
END //
DELIMITER ;

Let me know if this is not what you need.