问:
Spark, Scala, DataFrame: create feature vectors
I have a DataFrame that looks like follow:

userID, category, frequency
1,cat1,1
1,cat2,3
1,cat9,5
2,cat4,6
2,cat9,2
2,cat10,1
3,cat1,5
3,cat7,16
3,cat8,2
```

<p>The number of distinct categories is 10, and I would like to create a feature vector for each <code>userID</code> and fill the missing categories with zeros.</p>

<p>So the output would be something like:</p>

<pre class="lang-none prettyprint-override"><code>userID,feature
1,[1,3,0,0,0,0,0,0,5,0]
2,[0,0,0,6,0,0,0,0,2,1]
3,[5,0,0,0,0,0,16,2,0,0]
</code>```

It is just an illustrative example, in reality I have about 200,000 unique userID and and 300 unique category.

What is the most efficient way to create the features DataFrame?

答:
Given your input:

```<code>val df = Seq((1, "cat1", 1), (1, "cat2", 3), (1, "cat9", 5),
             (2, "cat4", 6), (2, "cat9", 2), (2, "cat10", 1),
             (3, "cat1", 5), (3, "cat7", 16), (3, "cat8", 2))
           .toDF("userID", "category", "frequency")
df.show
+------+--------+---------+
|userID|category|frequency|
+------+--------+---------+
|     1|    cat1|        1|
|     1|    cat2|        3|
|     1|    cat9|        5|
|     2|    cat4|        6|
|     2|    cat9|        2|
|     2|   cat10|        1|
|     3|    cat1|        5|
|     3|    cat7|       16|
|     3|    cat8|        2|
+------+--------+---------+
</code>```

Just run:

```<code>val pivoted = df.groupBy("userID").pivot("category").avg("frequency")
val dfZeros = pivoted.na.fill(0)
dzZeros.show
+------+----+-----+----+----+----+----+----+
|userID|cat1|cat10|cat2|cat4|cat7|cat8|cat9|
+------+----+-----+----+----+----+----+----+
|     1| 1.0|  0.0| 3.0| 0.0| 0.0| 0.0| 5.0|
|     3| 5.0|  0.0| 0.0| 0.0|16.0| 2.0| 0.0|
|     2| 0.0|  1.0| 0.0| 6.0| 0.0| 0.0| 2.0|
+------+----+-----+----+----+----+----+----+
</code>```

Finally, use VectorAssembler to create a org.apache.spark.ml.linalg.Vector

NOTE: I have not checked performances on this yet...

EDIT: Possibly more complex, but likely more efficient!

```<code>def toSparseVectorUdf(size: Int) = udf[Vector, Seq[Row]] {
  (data: Seq[Row]) => {
    val indices = data.map(_.getDouble(0).toInt).toArray
    val values = data.map(_.getInt(1).toDouble).toArray
    Vectors.sparse(size, indices, values)
  }
}

val indexer = new StringIndexer().setInputCol("category").setOutputCol("idx")
val indexerModel = indexer.fit(df)
val totalCategories = indexerModel.labels.size
val dataWithIndices = indexerModel.transform(df)
val data = dataWithIndices.groupBy("userId").agg(sort_array(collect_list(struct($"idx", $"frequency".as("val")))).as("data"))
val dataWithFeatures = data.withColumn("features", toSparseVectorUdf(totalCategories)($"data")).drop("data")
dataWithFeatures.show(false)
+------+--------------------------+
|userId|features                  |
+------+--------------------------+
|1     |(7,[0,1,3],[1.0,5.0,3.0]) |
|3     |(7,[0,2,4],[5.0,16.0,2.0])|
|2     |(7,[1,5,6],[2.0,6.0,1.0]) |
+------+--------------------------+
</code>```

NOTE: StringIndexer will sort categories by frequency => most frequent category will be at index=0 in indexerModel.labels. Feel free to use your own mapping if you'd like and pass that directly to toSparseVectorUdf.

ContentLicense: CC BY-SA 4.0

Body:
I have a DataFrame that looks like follow:

userID, category, frequency
1,cat1,1
1,cat2,3
1,cat9,5
2,cat4,6
2,cat9,2
2,cat10,1
3,cat1,5
3,cat7,16
3,cat8,2

The number of distinct categories is 10, and I would like to create a feature vector for each userID and fill the missing categories with zeros.

So the output would be something like:

userID,feature
1,[1,3,0,0,0,0,0,0,5,0]
2,[0,0,0,6,0,0,0,0,2,1]
3,[5,0,0,0,0,0,16,2,0,0]

It is just an illustrative example, in reality I have about 200,000 unique userID and and 300 unique category.

What is the most efficient way to create the features DataFrame?

Body:
Given your input:

val df = Seq((1, "cat1", 1), (1, "cat2", 3), (1, "cat9", 5),
             (2, "cat4", 6), (2, "cat9", 2), (2, "cat10", 1),
             (3, "cat1", 5), (3, "cat7", 16), (3, "cat8", 2))
           .toDF("userID", "category", "frequency")
df.show
+------+--------+---------+
|userID|category|frequency|
+------+--------+---------+
|     1|    cat1|        1|
|     1|    cat2|        3|
|     1|    cat9|        5|
|     2|    cat4|        6|
|     2|    cat9|        2|
|     2|   cat10|        1|
|     3|    cat1|        5|
|     3|    cat7|       16|
|     3|    cat8|        2|
+------+--------+---------+

Just run:

val pivoted = df.groupBy("userID").pivot("category").avg("frequency")
val dfZeros = pivoted.na.fill(0)
dzZeros.show
+------+----+-----+----+----+----+----+----+
|userID|cat1|cat10|cat2|cat4|cat7|cat8|cat9|
+------+----+-----+----+----+----+----+----+
|     1| 1.0|  0.0| 3.0| 0.0| 0.0| 0.0| 5.0|
|     3| 5.0|  0.0| 0.0| 0.0|16.0| 2.0| 0.0|
|     2| 0.0|  1.0| 0.0| 6.0| 0.0| 0.0| 2.0|
+------+----+-----+----+----+----+----+----+

Finally, use VectorAssembler to create a org.apache.spark.ml.linalg.Vector

NOTE: I have not checked performances on this yet...

EDIT: Possibly more complex, but likely more efficient!

def toSparseVectorUdf(size: Int) = udf[Vector, Seq[Row]] {
  (data: Seq[Row]) => {
    val indices = data.map(_.getDouble(0).toInt).toArray
    val values = data.map(_.getInt(1).toDouble).toArray
    Vectors.sparse(size, indices, values)
  }
}

val indexer = new StringIndexer().setInputCol("category").setOutputCol("idx")
val indexerModel = indexer.fit(df)
val totalCategories = indexerModel.labels.size
val dataWithIndices = indexerModel.transform(df)
val data = dataWithIndices.groupBy("userId").agg(sort_array(collect_list(struct($"idx", $"frequency".as("val")))).as("data"))
val dataWithFeatures = data.withColumn("features", toSparseVectorUdf(totalCategories)($"data")).drop("data")
dataWithFeatures.show(false)
+------+--------------------------+
|userId|features                  |
+------+--------------------------+
|1     |(7,[0,1,3],[1.0,5.0,3.0]) |
|3     |(7,[0,2,4],[5.0,16.0,2.0])|
|2     |(7,[1,5,6],[2.0,6.0,1.0]) |
+------+--------------------------+

NOTE: StringIndexer will sort categories by frequency => most frequent category will be at index=0 in indexerModel.labels. Feel free to use your own mapping if you'd like and pass that directly to toSparseVectorUdf.


来源: stackexchange

问:
MSI for multiple websites WITHOUT custom actions
I would like to create an installer that installs 6 websites, all of which rely on a data access library.  So the solution contains 6 web applications, and 1 class library.

Question is: how can I accomplish this without using custom actions?

So far, the only thing I've thought of is to make merge modules out of the web app projects, each of them throwing in the primary output of the class library project, and then making a main installer that has all the merge modules.

答:
I would put each website in a feature that way you could give the end user the control over which website they require, if that is an option.

Although, you'll have to repeat the same type of code for each website in their respective.wxs file.

OwnerDisplayName: andrew

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: CheGueVerra

ContentLicense: CC BY-SA 2.5


问:
Oracle APEX Dynamic Action PageLoad Processing
Situation: I currently have a page that is a type of Dashboard page. It contains several charts and reports. This page is the home page of the application. When the page first loads a Request Type of First is passed into the page. As the page renders several page processes calling Oracle Package, setting values, etc are executed. Once the page processes are complete, i believe the dynamic actions are then fired off. There are probably 10 DA's that are fired on PageLoad. The very first DA is fires on PageLoad but has a condition of REQUEST = 'First'. If condition is met, the page is then resubmitted with a Request Type of: search.

Question: How does APEX process Dynamic Actions, specifically PageLoad? If there are 10 Dynamic Actions all sequences are greater then another, does APEX or Page Processing handle one at a time or do they all execute at the same time regardless of sequence and conditions?

Reason for Question: I created a DA to execute an insert statement into a DB Table. This DA executes on page load with no conditions and is sequence#: 0. Then, i created another DA to do the same but is the very last sequence#. When logged into the application and then viewed the data inserted into the DB table, it showed both records 4 times. the first two were inserted when request type = First. Then the DA already mentioned fired and resubmitted the page which then inserted two more records. I was only expecting three records to be in the DB Table. One for the request type First and two for the request type search.

答:
Why are you using dynamic actions? Why not use processes that execute during page render?

Dynamic action execute order can't be guaranteed in that way, in the same way has a JavaScript loop behaves like nothing you'd think. JavaScript does it's own thing.

If you're executing PL/SQL in your dynamic actions, this will behave synchronously or asynchronously. Either way, they will be launched with x separate processes. The only way to control order would be to have them in the same dynamic action and 'wait for result' set to yes.

Which brings me back to: why use dynamic actions?


问:
Microsoft Translator Hub with dictionary file only
I have setup a Microsoft Translator Hub system to treat some specific words on my webpage (like company name etc) with a custom translation using a dictionary *.xlsx sheet.

But i am not able to train + deploy the system, because it forces me to upload at least 2.000 parallel sentences to start a training.

I only want it to use the few words i've added in the dictionary sheet. All other translation should be use the default translation system.

Documentation says: "You can start with as little as one dictionary entry. The custom category you create with your dictionary can be built on top of the general or the standard (speech or tech) categories..."

But there is no way to clone the general of a standard category and build upon it.

So what am i missing here? Who can i deploy a system with just one dictionary file?

答:
the ability to build a system with a dictionary only depends on the language pair you are customizing for. Not all language pairs that the API exposes have an underlying language pair.

The details are explained in this article:
https://cognitive.uservoice.com/knowledgebase/articles/1166938-hub-building-a-custom-system-using-a-dictionary-o


问:
Sorting an array of objects based on another array
So, there will probably be guys that will say this is a duplicate, but I read many relatively similar questions and still I'm unable to find an answer that resolves this particular problem, I've even tried some npm modules that claim to solve this, but to no avail...

Well, I have an array of objects:

```<code> var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];
</code>```

and another array which should help in sorting the first array:

```<code>var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];
</code>```

The result should be this:

```<code>[{id: 1, question: '12', author: 'Zoran  Stanić', '34': 3, '5': 1, '6': 1}]
</code>```

How can I achieve this?

P.S. These are the values from the database, and the order of objArr could be completely different than the one in example, depending on the db logic - it's MySQL thingy.

答:
Objects cannot be sorted in JS. You'd either have to do create your own implementation using an Array. If you can use ES6, Map will maintain the order with which pairs are added. The link below talks about this:

http://www.jstips.co/en/javascript/map-to-the-rescue-adding-order-to-object-properties/

Body:
So, there will probably be guys that will say this is a duplicate, but I read many relatively similar questions and still I'm unable to find an answer that resolves this particular problem, I've even tried some npm modules that claim to solve this, but to no avail...

Well, I have an array of objects:

 var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];

and another array which should help in sorting the first array:

var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

The result should be this:

[{id: 1, question: '12', author: 'Zoran  Stanić', '34': 3, '5': 1, '6': 1}]

How can I achieve this?

P.S. These are the values from the database, and the order of objArr could be completely different than the one in example, depending on the db logic - it's MySQL thingy.


答:
Alternatively, you can have an array or arrays, in which every array conforms to the structure of sortingArr, like this:

var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];

var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

var sortedArrsVals = objArr.map(el =>
  sortingArr.map(e => el[e])
)

console.log(sortedArrsVals)```

Title: Sorting an array of objects based on another array


问:
setting height to wrap_content in Java makes the view deny all predefined XML attributes?
I have created a TextView in XML and have set some rules for it (for example layout_bellow="something"), and made it's height set to 0, so that when a button is clicked, it's height would be set to wrap_content. I wrote the code bellow for the button responsible for resizing, and below it is the XML code i wrote for the TextView. The problem is, when i click the button, the height becomes match_parent, the layout_bellow attribute gets ignored and it is drawn from the start of the parent layout, and width (that was set to match_parent) becomes wrap_content. Whats the problem? thanks.

the Button:

```<code>    btnExpand.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, height));
        }
    });
</code>```

the XML:

```<code>        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/firstRow"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                .
                .
                .
            </LinearLayout>

            <TextView
                android:id="@+id/theTextView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_below="@id/firstRow"
                android:text="lorem ipsom lorem ipsom">

        </RelativeLayout>
</code>```

EDIT: here's an image to demonstrate the problem

答:
Basically the problem is you are creating new LayoutParams and setting it to the view. You have get the already set(xml) LayoutParams of the view and modify whichever you want to modify and set it back to the View.</p>

```<code>LayoutParams layoutParams = textView.getLayoutParams();
//height = LayoutParams.WRAP_CONTENT;or 100 or whatever
layoutParams.height = LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(layoutParams);
</code>```

Body:
I have created a TextView in XML and have set some rules for it (for example layout_bellow="something"), and made it's height set to 0, so that when a button is clicked, it's height would be set to wrap_content. I wrote the code bellow for the button responsible for resizing, and below it is the XML code i wrote for the TextView. The problem is, when i click the button, the height becomes match_parent, the layout_bellow attribute gets ignored and it is drawn from the start of the parent layout, and width (that was set to match_parent) becomes wrap_content. Whats the problem? thanks.

the Button:

    btnExpand.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, height));
        }
    });

the XML:

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/firstRow"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                .
                .
                .
            </LinearLayout>

            <TextView
                android:id="@+id/theTextView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_below="@id/firstRow"
                android:text="lorem ipsom lorem ipsom">

        </RelativeLayout>

EDIT: here's an image to demonstrate the problem

Body:
Basically the problem is you are creating new LayoutParams and setting it to the view. You have get the already set(xml) LayoutParams of the view and modify whichever you want to modify and set it back to the View.

LayoutParams layoutParams = textView.getLayoutParams();
//height = LayoutParams.WRAP_CONTENT;or 100 or whatever
layoutParams.height = LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(layoutParams);


问:
Batch file: row in txt file contains xxx then do one thing, else do nothing
I am trying to make the modify a text file.

Right now i have some modifications that are applying always.

I want to make before the changes the conditional that if a row contains xxxx then do nothing else do the changes. Here i paste you the code.

setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
   SET "s='%%a "
   SET "s=!s:;= ! "
   SET "s=!s:- =-;;! "
   SET "s=!s: -=-! "
   SET "s=!s:-;;-=-;-! "
   SET "s=!s:-=%!"
   SET "s=!s:_= %!"
   SET "s=!s:;=';'%!"
   SET "s=!s:;'';'=;;%!"

   echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")
```

答:
Insert an echo to find with conditional execution on fail ||

```<code>@Echo off
Setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
    Echo:%%a|find "xxx" >NUL 2>&1||(
        SET "s='%%a "
        SET "s=!s:;= ! "
        SET "s=!s:- =-;;! "
        SET "s=!s: -=-! "
        SET "s=!s:-;;-=-;-! "
        SET "s=!s:-=%!"
        SET "s=!s:_= %!"
        SET "s=!s:;=';'%!"
        SET "s=!s:;'';'=;;%!"
    )
    echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")
</code>```

Body:
Insert an echo to find with conditional execution on fail ||

@Echo off
Setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
    Echo:%%a|find "xxx" >NUL 2>&1||(
        SET "s='%%a "
        SET "s=!s:;= ! "
        SET "s=!s:- =-;;! "
        SET "s=!s: -=-! "
        SET "s=!s:-;;-=-;-! "
        SET "s=!s:-=%!"
        SET "s=!s:_= %!"
        SET "s=!s:;=';'%!"
        SET "s=!s:;'';'=;;%!"
    )
    echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")


问:
Ruby - Reading a file, replacing contents, then closing
How do you open a file, read it, then write to it replacing the entire contents, and close it?

I could do this:

```<code>File.open('foo.bin', 'r') do |f|
  contents = f.read
end
# do something with the contents
File.open('foo.bin', 'w') do |f|
  f.print contents
end
</code>```

But there are 2 IO open steps and 2 IO close steps in that and doubling the IO steps seems like a total waste, not to mention much harder on the disk with as many times as it is likely to happen in my script.

Is there a way to open, read, overwrite, then close?

答:
First, if you didn't profile your code, do it now. An extra file open/close is unlikely to be the cause of your slow down. Profiling will show where the real issue is.

I'm not convinced this will be any faster, but here are the general steps to do this with a single open and close.

Open for read & write.

Read the whole file (not line by line).

Truncate the file.

Go back to the beginning.

Write.

Close.

In Ruby, you do that like so:

```<code># Open the file for read/write.
File.open("test.data", "r+") { |f|
    # Read the whole file
    contents = f.read

    # Truncate the file
    f.truncate(0)

    # Jump back to the beginning
    f.rewind

    # Write the new content
    f.write("new stuff\n")
}
</code>```

Body:
How do you open a file, read it, then write to it replacing the entire contents, and close it?

I could do this:

File.open('foo.bin', 'r') do |f|
  contents = f.read
end
# do something with the contents
File.open('foo.bin', 'w') do |f|
  f.print contents
end

But there are 2 IO open steps and 2 IO close steps in that and doubling the IO steps seems like a total waste, not to mention much harder on the disk with as many times as it is likely to happen in my script.

Is there a way to open, read, overwrite, then close?

Body:
First, if you didn't profile your code, do it now. An extra file open/close is unlikely to be the cause of your slow down. Profiling will show where the real issue is.

I'm not convinced this will be any faster, but here are the general steps to do this with a single open and close.

Open for read & write.

Read the whole file (not line by line).

Truncate the file.

Go back to the beginning.

Write.

Close.

In Ruby, you do that like so:

# Open the file for read/write.
File.open("test.data", "r+") { |f|
    # Read the whole file
    contents = f.read

    # Truncate the file
    f.truncate(0)

    # Jump back to the beginning
    f.rewind

    # Write the new content
    f.write("new stuff\n")
}


问:
How to create routes or services while one pod with two containers on openshift-origin?
I have two applications with two ports 8080 and 8081 . They have no connection except using a same static resource . So I create a pod with two containers according https://kubernetes.io/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume/ .

But how to create the services and the routes ? Can I create one service with two ports ? Or two services ?

Help please !

答: You can use two services or one service with two ports.  Routes however must pick a single port - use the targetPort field on the route to control which pod port number to target (or you can use the service port name)


问:
Passing state info into a service worker before `install`
Background

I'm new to service workers but working on a library that is intended to become "offline-first" (really, almost "offline-only") (FWIW, the intent is to allow consumers of the library to provide JSON config representing tabular multilinear texts and get in return an app which allows their users to browse these texts in a highly customizable manner by paragraph/verse ranges.)

Other projects are to install the library as a dependency and then supply information via our JavaScript API such as the path of a JSON config file indicating the files that our app will consume to produce an (offline) app for them.

While I know we could do any of the following:

require users provide a hard-coded path from which our service worker's install script could use waitUntil with its own JSON request to retrieve the user's necessary files

skip the service worker's install step of the service worker for the JSON file, and rely on fetch events to update the cache, providing a fallback display if the user completed the install and went offline before the fetches could occur.

Post some state info from our main script to a server which the service worker, once registered, would query before completing its install event.

...but all choices seems less than ideal because, respectively:

Our library's consumers may prefer to be able to designate their own location for their JSON config.

Given that the JSON config designates files critical to showing their users anything useful, I'd rather not allow an install to complete only to say that the user has to go back online to get the rest of the files if they were not able to remain online after the install event to see all the required fetches occur.

Besides wanting to avoid more trips to the server and extra code, I'd prefer for our code to be so offline-oriented as to be able to work entirely on mere static file servers.

Question:

Is there some way to pass a message or state information into a service worker before the install event occurs, whether as part of the query string of the service worker URL, or through a messaging event? The messaging event could even technically arrive after the install event begins as long as it can occur before a waitUntil within the install is complete.

I know I could test this myself, but I'd like to know what best practices might be anyways when the critical app files must themselves be dynamically obtained as in such libraries as ours.

I'm guessing indexedDB might be the sole alternative here (i.e., saving the config info or path of the JSON config to indexedDB, registering a service worker, and retrieving the indexedDB data from within the install event)? Even this would not be ideal as I'm letting users define a namespace for their storage, but I need a way for it too to be passed into the worker, or otherwise, multiple such apps on the origin could clash.

答:
Update 3:

And since it is not supposed to be safe to rely on globals within the worker, my messaging solution seems even less sound. I think it either has to be Jeff Posnick's solution (in some cases, importScripts may work).

Update 2:

Although not directly related to the topic of this thread relating to "install" event, as per a discussion starting at https://github.com/w3c/ServiceWorker/issues/659#issuecomment-384919053 , there are some issues, particularly with using this message-passing approach for the activate event. Namely, the activate event may never fail, and thus never be tried again, leaving one's application in an unstable state. (A failure of install will at least not apply the new service worker to old pages, whereas activate will keep fetches on hold until the event completes, which it may never do if it is left waiting for a message that was not received, and which anything but a new worker will fail to correct since new pages won't be able to load to send that message again.)

Update:

Although I got the client from within the install script in Chrome, I wasn't able to receive the message back with navigator.serviceWorker.onmessage for some reason.

However, I was able to fully confirm the following approach in its place:

In the service worker:

```<code>self.addEventListener('install', e => {
    e.waitUntil(
        new Promise((resolve, reject) => {
            self.addEventListener('message', ({data: {
                myData
            }}) => {
                // Do something with `myData` here
                //    then when ready, `resolve`
            });
        })
    );
 });
</code>```

In the calling script:

```<code>navigator.serviceWorker.register('sw.js').then((r) => {
    r.installing.postMessage({myData: 100});
});
</code>```

@JeffPosnick 's is the best answer for the simple case I described in the OP, but I thought I'd present my discovering that one can get messages from and into a service worker script early (tested on Chrome) by such as the following:

In the service worker:

```<code>self.addEventListener('install', e => {
    e.waitUntil(self.clients.matchAll({
        includeUncontrolled: true,
        type: 'window'
    }).then((clients) => new Promise((resolve, reject) => {
        if (clients && clients.length) {
            const client = clients.pop();
            client.postMessage('send msg to main script');
            // One should presumably be able to poll to check for a
            //   variable set in the SW message listener below
            //   and then `resolve` when set
            // Despite the unreliability of setting globals in SW's
            //   I believe this could be safe here as the `install`
            //   event is to run while the main script is still open.
        }
    })));
});

self.addEventListener('message', e => {
    console.log('SW receiving main script msg', e.data);
    e.ports[0].postMessage('sw response');
});
</code>```

In the calling script:

```<code>navigator.serviceWorker.addEventListener('message', (e) => {
    console.log('msg recd in main script', e.data);
    e.source.postMessage('sending back to sw');
});
return navigator.serviceWorker.register(
    'sw.js'
).then((r) => {
    // navigator.serviceWorker.ready.then((r) => { // This had been necessary at some point in my testing (with r.active.postMessage), but not working for me atm...
        // Sending a subsequent message
        const messageChannel = new MessageChannel();
        messageChannel.port1.onmessage = (e) => {
            if (e.data.error) {
                console.log('err', e.data.error);
            } else {
                console.log('data', e.data);
            }
        };
        navigator.serviceWorker.controller.postMessage('sending to sw', [messageChannel.port2]);
    // });
});
</code>```

Body:
Update 3:

And since it is not supposed to be safe to rely on globals within the worker, my messaging solution seems even less sound. I think it either has to be Jeff Posnick's solution (in some cases, importScripts may work).

Update 2:

Although not directly related to the topic of this thread relating to "install" event, as per a discussion starting at https://github.com/w3c/ServiceWorker/issues/659#issuecomment-384919053 , there are some issues, particularly with using this message-passing approach for the activate event. Namely, the activate event may never fail, and thus never be tried again, leaving one's application in an unstable state. (A failure of install will at least not apply the new service worker to old pages, whereas activate will keep fetches on hold until the event completes, which it may never do if it is left waiting for a message that was not received, and which anything but a new worker will fail to correct since new pages won't be able to load to send that message again.)

Update:

Although I got the client from within the install script in Chrome, I wasn't able to receive the message back with navigator.serviceWorker.onmessage for some reason.

However, I was able to fully confirm the following approach in its place:

In the service worker:

self.addEventListener('install', e => {
    e.waitUntil(
        new Promise((resolve, reject) => {
            self.addEventListener('message', ({data: {
                myData
            }}) => {
                // Do something with `myData` here
                //    then when ready, `resolve`
            });
        })
    );
 });

In the calling script:

navigator.serviceWorker.register('sw.js').then((r) => {
    r.installing.postMessage({myData: 100});
});

@JeffPosnick 's is the best answer for the simple case I described in the OP, but I thought I'd present my discovering that one can get messages from and into a service worker script early (tested on Chrome) by such as the following:

In the service worker:

self.addEventListener('install', e => {
    e.waitUntil(self.clients.matchAll({
        includeUncontrolled: true,
        type: 'window'
    }).then((clients) => new Promise((resolve, reject) => {
        if (clients && clients.length) {
            const client = clients.pop();
            client.postMessage('send msg to main script');
            // One should presumably be able to poll to check for a
            //   variable set in the SW message listener below
            //   and then `resolve` when set
            // Despite the unreliability of setting globals in SW's
            //   I believe this could be safe here as the `install`
            //   event is to run while the main script is still open.
        }
    })));
});

self.addEventListener('message', e => {
    console.log('SW receiving main script msg', e.data);
    e.ports[0].postMessage('sw response');
});

In the calling script:

navigator.serviceWorker.addEventListener('message', (e) => {
    console.log('msg recd in main script', e.data);
    e.source.postMessage('sending back to sw');
});
return navigator.serviceWorker.register(
    'sw.js'
).then((r) => {
    // navigator.serviceWorker.ready.then((r) => { // This had been necessary at some point in my testing (with r.active.postMessage), but not working for me atm...
        // Sending a subsequent message
        const messageChannel = new MessageChannel();
        messageChannel.port1.onmessage = (e) => {
            if (e.data.error) {
                console.log('err', e.data.error);
            } else {
                console.log('data', e.data);
            }
        };
        navigator.serviceWorker.controller.postMessage('sending to sw', [messageChannel.port2]);
    // });
});


问:
Distinct command doesn't work
This is the command:

```<code>SELECT DISTINCT T.TRIP_ID, T.TRIP_NAME, T.STATE, T.TYPE, S.TRIP_ID, S.TRIP_NAME

FROM TRIP T, TRIP S

WHERE T.STATE = 'NH'

AND T.TYPE = 'Hiking'

AND T.TRIP_ID < S.TRIP_ID

ORDER BY T.TRIP_NAME;
</code>```

I should only getting about 6 results but somehow I get 298 repeated results. What's the problem with this code?

Correct result (6 entries)

My result (first few entries) which totals to 298 entries

答:
I'm not sure why you are doing a self join in this example. But if you want just the distinct trip names in New Hampshire that involved hiking, do this:</p>

```<code>SELECT DISTINCT T.TRIP_NAME
FROM TRIP T
WHERE T.STATE = 'NH' AND T.TYPE = 'Hiking'
ORDER BY T.TRIP_NAME;
</code>```

Title: Distinct command doesn't work

Body:
This is the command:

SELECT DISTINCT T.TRIP_ID, T.TRIP_NAME, T.STATE, T.TYPE, S.TRIP_ID, S.TRIP_NAME

FROM TRIP T, TRIP S

WHERE T.STATE = 'NH'

AND T.TYPE = 'Hiking'

AND T.TRIP_ID < S.TRIP_ID

ORDER BY T.TRIP_NAME;

I should only getting about 6 results but somehow I get 298 repeated results. What's the problem with this code?

Correct result (6 entries)

My result (first few entries) which totals to 298 entries

Body:
I'm not sure why you are doing a self join in this example. But if you want just the distinct trip names in New Hampshire that involved hiking, do this:

SELECT DISTINCT T.TRIP_NAME
FROM TRIP T
WHERE T.STATE = 'NH' AND T.TYPE = 'Hiking'
ORDER BY T.TRIP_NAME;


问:
How to define hash tables in Bash?
What is the equivalent of Python dictionaries but in Bash (should work across OS X and Linux).</p>

答:
There's parameter substitution, though it may be un-PC as well ...like indirection.

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

# Array pretending to be a Pythonic dictionary
ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

for animal in "${ARRAY[@]}" ; do
    KEY="${animal%%:*}"
    VALUE="${animal##*:}"
    printf "%s likes to %s.\n" "$KEY" "$VALUE"
done

printf "%s is an extinct animal which likes to %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"
</code>```

The BASH 4 way is better of course, but if you need a hack ...only a hack will do.
You could search the array/hash with similar techniques.

Title: How to define hash tables in Bash?

Body:
There's parameter substitution, though it may be un-PC as well ...like indirection.

#!/bin/bash

# Array pretending to be a Pythonic dictionary
ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

for animal in "${ARRAY[@]}" ; do
    KEY="${animal%%:*}"
    VALUE="${animal##*:}"
    printf "%s likes to %s.\n" "$KEY" "$VALUE"
done

printf "%s is an extinct animal which likes to %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"

The BASH 4 way is better of course, but if you need a hack ...only a hack will do.
You could search the array/hash with similar techniques.


问:
Align nav-items to right side in bootstrap-4
I just switched to bootstrap 4 and reworking all my html and scss to work with it and I cant seem to find how to put a group of nav-items on the right side of the navbar. This is my navbar code:

```<code><nav class="navbar navbar-full navbar-dark bg-primary">
        <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
        <%= link_to "Living Recipe", recipes_path(sort_attribut: "popularity", sort_order: :desc), class: "navbar-brand" %>
        <div class="collapse navbar-toggleable-sm" id="navbarResponsive">
            <ul class="nav navbar-nav float-md-left">
                <li class="nav-item">
                    <%= form_tag(recipes_path, :method => "get", id: "search-form", class: "form-inline") do %>
                            <%= text_field_tag :search, params[:search], placeholder: "Search Recipes", class: "form-control col-md-8" %>
                    <% end %>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="http://example.com" id="responsiveNavbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Browse</a>
                    <div class="dropdown-menu" aria-labelledby="responsiveNavbarDropdown">
                        <%= link_to "Popular", recipes_path(sort_attribute: "popularity", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Newest", recipes_path(sort_attribute: "created_at", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Updated", recipes_path(sort_attribute: "most_active", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Saved", recipes_path(sort_attribute: "save_count", sort_order: :desc), class: "dropdown-item" %>
                    </div>
                </li>
            </ul>
            <ul class="nav navbar-nav float-md-right">
                <% if user_signed_in? %>
                    <li class="dropdown">
                        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <%= current_user.displayname.present? ? "D-ring" : current_user.firstname %>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="responsiveNavbarDropdown">
                            <%= link_to "Profile", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Recipe Box", user_saved_recipes_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Add Recipe", new_recipe_path, class: "dropdown-item" %>
                            <%= link_to "Submitted Recipes", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Sign Out", destroy_user_session_path, :method => :delete, class: "dropdown-item" %>
                        </div>
                    </li>
                <% else %>
                    <li class="nav-item">
                        <%= link_to "Create Account", '', data: {:'toggle' => 'modal', :'target' => '#signupModal'}, class: "nav-link" %>
                    </li>
                    <li class="nav-item">
                        <%= link_to "Login", '', data: {:'toggle' => 'modal', :'target' => '#loginModal'}, class: "nav-link" %>
                    </li>
                <% end %>
            </ul>
        </div>
    </nav>
</code>```

And this is the screenshot of what it looks like

答:
I have a working codepen with left- and right-aligned nav links that all collapse into a responsive menu together using .justify-content-between on the parent tag: https://codepen.io/epan/pen/bREVVW?editors=1000

```<code><nav class="navbar navbar-toggleable-sm navbar-inverse bg-inverse">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar"     aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">Acme</a>
  <div class="collapse navbar-collapse justify-content-between" id="navbar">
    <div class="navbar-nav">
      <a class="nav-item nav-link" href="#">Ball Bearings</a>
      <a class="nav-item nav-link" href="#">TNT Boxes</a>
    </div>
    <div class="navbar-nav">
      <a class="nav-item nav-link" href="#">Logout</a>
    </div>
  </div>
</nav>
</code>```

Body:
I just switched to bootstrap 4 and reworking all my html and scss to work with it and I cant seem to find how to put a group of nav-items on the right side of the navbar. This is my navbar code:

        <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
        <%= link_to "Living Recipe", recipes_path(sort_attribut: "popularity", sort_order: :desc), class: "navbar-brand" %>

                    <%= form_tag(recipes_path, :method => "get", id: "search-form", class: "form-inline") do %>
                            <%= text_field_tag :search, params[:search], placeholder: "Search Recipes", class: "form-control col-md-8" %>
                    <% end %>

                    Browse

                        <%= link_to "Popular", recipes_path(sort_attribute: "popularity", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Newest", recipes_path(sort_attribute: "created_at", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Updated", recipes_path(sort_attribute: "most_active", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Saved", recipes_path(sort_attribute: "save_count", sort_order: :desc), class: "dropdown-item" %>

                <% if user_signed_in? %>

                            <%= current_user.displayname.present? ? "D-ring" : current_user.firstname %>

                            <%= link_to "Profile", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Recipe Box", user_saved_recipes_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Add Recipe", new_recipe_path, class: "dropdown-item" %>
                            <%= link_to "Submitted Recipes", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Sign Out", destroy_user_session_path, :method => :delete, class: "dropdown-item" %>

                <% else %>

                        <%= link_to "Create Account", '', data: {:'toggle' => 'modal', :'target' => '#signupModal'}, class: "nav-link" %>

                        <%= link_to "Login", '', data: {:'toggle' => 'modal', :'target' => '#loginModal'}, class: "nav-link" %>

                <% end %>

And this is the screenshot of what it looks like

Body:
I have a working codepen with left- and right-aligned nav links that all collapse into a responsive menu together using .justify-content-between on the parent tag: https://codepen.io/epan/pen/bREVVW?editors=1000

<nav class="navbar navbar-toggleable-sm navbar-inverse bg-inverse">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar"     aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">Acme</a>
  <div class="collapse navbar-collapse justify-content-between" id="navbar">
    <div class="navbar-nav">
      <a class="nav-item nav-link" href="#">Ball Bearings</a>
      <a class="nav-item nav-link" href="#">TNT Boxes</a>
    </div>
    <div class="navbar-nav">
      <a class="nav-item nav-link" href="#">Logout</a>
    </div>
  </div>
</nav>


问:
ASP.NET JS file does not update latest on SOME clients
I am not really sure how to fully explain this problem. There has been this ongoing issue where SOME clients web browsers are not able to get the latest JS file for my website no matter what they do. Mind you, everything works fine when I visit the webpage from my workstation, but for others the js files are old versions.

Things we have tried:
-Appending a random parameter to the end of the js file
-Force-refreshing the cache (Ctrl-F5)
-Setting Internet Options browsing history to "Everytime I visit a webpage"
-Clearing all browser data (IE, Chrome, Edge)

What is getting me is this doesn't happen to everyone, and it doesn't happen all the time. Only occasionally and only to some users and the issue always eventually resolves itself within a day or two. Whats going on here?

Website is an ASP.NET MVC application running on IIS8 on Windows Server 2012 R2

答:
I don't have a silver bullet for you on this but my application has the same issue. In my instance we have a third-party authentication system (specifically, Tivoli Access Manager) between our clients and our server. Our suspicion has always been that something in TAM is caching stuff invisibly to us, and despite of any settings we have in IIS or what have you. </p>

<p>In your environment do you have any proxies or middle tiers that could be performing caching on your app's behalf? </p>

Body:
I don't have a silver bullet for you on this but my application has the same issue. In my instance we have a third-party authentication system (specifically, Tivoli Access Manager) between our clients and our server. Our suspicion has always been that something in TAM is caching stuff invisibly to us, and despite of any settings we have in IIS or what have you.

In your environment do you have any proxies or middle tiers that could be performing caching on your app's behalf?


问:
Removing Empty DataFrame Objects in Zipped DataFrame Tuple
Given an input list of times and values that have been indexed based on Time, as shown in the Dataframe, df:

```<code>>>> df
                       Value
Times
2017-05-10 01:05:03        1
2017-05-10 01:05:00        2
2017-05-10 01:05:10        3
2017-05-10 01:08:12        8
2017-05-11 08:30:20        4
2017-05-11 08:30:14        5
2017-05-11 08:30:35        6
</code>```

I then grouped the times by Minute using the following command:

```<code>>>> g = df.groupby(pd.TimeGrouper('min'))
</code>```

I then zipped this new dataframe using the following command:

```<code>>>> (zip(*g)[1])
</code>```

But now, since I grouped by minute, I have multiple empty dataframes.  I want to group by minute so that I can iterate through each minute, but here's my question:  How do I remove Empty DataFrames that are created, when there's no minute to group?  An example output looks like this:

```<code>Index: [], Empty DataFrame
Columns: [  Value]
Index: [], Empty DataFrame
Columns: [  Value]
Index: [], Empty DataFrame
Columns: [  Value]
Index: [],                        Value
Times
2017-05-11 08:30:14        5
2017-05-11 08:30:20        4
2017-05-11 08:30:35        6
</code>```

Ideally, I would like to have a dataframe with sub-data frames that only include entries that are not empty.  Thanks for the help.

Body:
Given an input list of times and values that have been indexed based on Time, as shown in the Dataframe, df:

>>> df
                       Value
Times
2017-05-10 01:05:03        1
2017-05-10 01:05:00        2
2017-05-10 01:05:10        3
2017-05-10 01:08:12        8
2017-05-11 08:30:20        4
2017-05-11 08:30:14        5
2017-05-11 08:30:35        6

I then grouped the times by Minute using the following command:

>>> g = df.groupby(pd.TimeGrouper('min'))

I then zipped this new dataframe using the following command:

>>> (zip(*g)[1])

But now, since I grouped by minute, I have multiple empty dataframes.  I want to group by minute so that I can iterate through each minute, but here's my question:  How do I remove Empty DataFrames that are created, when there's no minute to group?  An example output looks like this:

Index: [], Empty DataFrame
Columns: [  Value]
Index: [], Empty DataFrame
Columns: [  Value]
Index: [], Empty DataFrame
Columns: [  Value]
Index: [],                        Value
Times
2017-05-11 08:30:14        5
2017-05-11 08:30:20        4
2017-05-11 08:30:35        6

Ideally, I would like to have a dataframe with sub-data frames that only include entries that are not empty.  Thanks for the help.

Body:
Would this do it for you?

Setup:

import pandas as pd
import io

c = io.StringIO(u'''
Times,Value
2017-05-10 01:05:03,1
2017-05-10 01:05:00,2
2017-05-10 01:05:10,3
2017-05-10 01:08:12,8
2017-05-11 08:30:20,4
2017-05-11 08:30:14,5
2017-05-11 08:30:35,6
''')

df = pd.read_csv(c, parse_dates = ['Times']).set_index('Times')

Solution:

g = df.groupby(pd.TimeGrouper('min')).max().dropna()

x = (zip(*g)[1])


问:
Circular iterator / generator for list of custom class items
Say I have a custom class:

```<code>public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}
</code>```

I also have a list of my custom class objects:

```<code>CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};
</code>```

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

答:
Here's a Java 8 friendly way:</p>

```<code>IntStream.range(0, K)
    .mapToObj(i -> list[i % list.length])
    .forEach(cc -> /* play with CustomClass cc instance */);
</code>```

Body:
Say I have a custom class:

public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}

I also have a list of my custom class objects:

CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Body:
Here's a Java 8 friendly way:

IntStream.range(0, K)
    .mapToObj(i -> list[i % list.length])
    .forEach(cc -> /* play with CustomClass cc instance */);


问:
How to properly position bootstrap html divs
I want to properly align the controls within bootstrap divs, so that they look like

Currently there is a lot of gap between the rows and margin-bottom or padding doesnot seem to work. Also, how do i expand the list box to completely cover the length of screen? It looks like this

HTML

```<code>  <div class="row" style="margin-left: 5px; margin-right: 5px">
    <div class="table">
        <div class="row" style="margin-top:0px; padding-top:0px; border:dotted">
            <div style="float: left; margin-left:10px;">
                @Html.ListBoxFor(m => m.cM.CategoryList, new SelectList(Model.cM.CategoryList, "CategoryID", "Description"), new { @id = "listCommentCategory" })
            </div>
            <div style="margin-left:100px; margin-top:0px;">
                <div class="row" style="margin:0px; padding:0px; margin-bottom:0px; padding-bottom:0px; border:dashed">
                    <div class="col-md-1">
                        @Html.DropDownListFor(m => m.cM.HeaderList, new SelectList(Model.cM.HeaderList, "CommentID", "Comment"), new { @id = "ddlCommentHeaders" })
                    </div>
                    <div class="col-md-2" style="margin-left:10px">
                        Search:
                        @Html.TextBox("txtSearchHeader")
                        <button id="clear">X</button>
                    </div>
                    <div class="col-md-1" style="margin-left:10px">
                        <button id="refresh">Refresh</button>
                    </div>
                </div>
                <div class="row" style="margin-left:10px;  border:dashed">
                    Select or double-click on a comment to insert:
                </div>
                <div class="row" style="margin-left:10px;  border:dashed">
                    @Html.ListBoxFor(m => m.cM.CommentsList, new SelectList(Model.cM.CommentsList, "CommentID", "Comment"), "listComments")
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
After lots of hard-coding of height, width, padding and margin, i was able to achieve the target. (Also, if i set the col-xs-4 in second columns' first row, the button always goes on the next line. so i have reduced the col sums to 9. I guess 10 will also be fine)

Here is the mark-up

```<code> <div class="table">
        <div class="row" style="margin-top:0px; padding-top:0px;">
            <div class="col-xs-2" style="width:70px; border:groove; margin-left: 20px">

                        @Html.ListBoxFor(m => m.cM.CategoryList, new SelectList(Model.cM.CategoryList, "CategoryID", "Description"), new { @id = "listCommentCategory", @style = "height:190px; margin-top:5px; margin-bottom: 5px;" })

            </div>
            <div class="col-xs10" style="float: right; width:1000px; border:groove; margin-right: 20px">
                <div class="row" style="margin-top:5px; padding-top:0px;">
                    <div class="col-xs-3" style=" margin-left: 5px">
                        @Html.DropDownListFor(m => m.cM.HeaderList, new SelectList(Model.cM.HeaderList, "CommentID", "Comment"), new { @id = "ddlCommentHeaders" })
                    </div>
                    <div class="col-xs-4">
                        Search:
                        @Html.TextBox("txtSearchHeader")
                        <button id="clear">X</button>
                    </div>
                    <div class="col-xs-2">
                        <button id="refresh">Refresh</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12" style="margin-left:5px">
                        Select or double-click on a comment to insert:
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12" style="margin-left:5px">
                        @Html.ListBoxFor(m => m.cM.CommentsList, new SelectList(Model.cM.CommentsList, "CommentID", "Comment"), new { @id = "listComments", @style = "height:75px; margin-bottom:5px" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

Body:
I want to properly align the controls within bootstrap divs, so that they look like

Currently there is a lot of gap between the rows and margin-bottom or padding doesnot seem to work. Also, how do i expand the list box to completely cover the length of screen? It looks like this

HTML

                @Html.ListBoxFor(m => m.cM.CategoryList, new SelectList(Model.cM.CategoryList, "CategoryID", "Description"), new { @id = "listCommentCategory" })

                        @Html.DropDownListFor(m => m.cM.HeaderList, new SelectList(Model.cM.HeaderList, "CommentID", "Comment"), new { @id = "ddlCommentHeaders" })

                        Search:
                        @Html.TextBox("txtSearchHeader")
                        <button id="clear">X</button>

                        <button id="refresh">Refresh</button>

                    Select or double-click on a comment to insert:

                    @Html.ListBoxFor(m => m.cM.CommentsList, new SelectList(Model.cM.CommentsList, "CommentID", "Comment"), "listComments")

Body:
After lots of hard-coding of height, width, padding and margin, i was able to achieve the target. (Also, if i set the col-xs-4 in second columns' first row, the button always goes on the next line. so i have reduced the col sums to 9. I guess 10 will also be fine)

Here is the mark-up

 <div class="table">
        <div class="row" style="margin-top:0px; padding-top:0px;">
            <div class="col-xs-2" style="width:70px; border:groove; margin-left: 20px">

                        @Html.ListBoxFor(m => m.cM.CategoryList, new SelectList(Model.cM.CategoryList, "CategoryID", "Description"), new { @id = "listCommentCategory", @style = "height:190px; margin-top:5px; margin-bottom: 5px;" })

            </div>
            <div class="col-xs10" style="float: right; width:1000px; border:groove; margin-right: 20px">
                <div class="row" style="margin-top:5px; padding-top:0px;">
                    <div class="col-xs-3" style=" margin-left: 5px">
                        @Html.DropDownListFor(m => m.cM.HeaderList, new SelectList(Model.cM.HeaderList, "CommentID", "Comment"), new { @id = "ddlCommentHeaders" })
                    </div>
                    <div class="col-xs-4">
                        Search:
                        @Html.TextBox("txtSearchHeader")
                        <button id="clear">X</button>
                    </div>
                    <div class="col-xs-2">
                        <button id="refresh">Refresh</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12" style="margin-left:5px">
                        Select or double-click on a comment to insert:
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12" style="margin-left:5px">
                        @Html.ListBoxFor(m => m.cM.CommentsList, new SelectList(Model.cM.CommentsList, "CommentID", "Comment"), new { @id = "listComments", @style = "height:75px; margin-bottom:5px" })
                    </div>
                </div>
            </div>
        </div>
    </div>


问:
Is it possible to remove the YouTube logo from a chromeless player?
Is it possible to remove the YouTube logo from a chromeless player?</p>

答:
You can't and you shouldn't.

If you use the Embeddable Player on
  your website, you may not modify,
  build upon, or block any portion or
  functionality of the Embeddable
  Player, including but not limited to
  links back to the YouTube website.

www.youtube.com/static?gl=US&template=terms


问:
Select values from a list that don't exist in DB Table
I have a list of values. I am trying to select from that list all values that do not occur in a table.

for instance

var_nos ['Z1234', 'Z1235,  'Z1236']
select *
from db_table
where db_idno not in var_nos
Is this possible?

** after reading, I'm not sure this makes sense.  I want to return the value from var_nos that did not appear in POHED.

Possibly SQL isn't the best way to handle this?

答:
An outer join should do it:

```<code>with var_nos (no) as ( values ('Z1234'), ('Z1235'),  ('Z1236'))
select no
from var_nos
left outer join
db_table
  on db_table.db_idno = var_nos.no
where db_table.db_idno is null
</code>```

Alternatively:

```<code>select no
from table ( values ('Z1234'), ('Z1235'),  ('Z1236')) as var_nos (no)
where not exists (
  select 1 from db_table where db_table.db_idno = var_nos.no
)
</code>```

P.S. Not tested.

Body:
An outer join should do it:

with var_nos (no) as ( values ('Z1234'), ('Z1235'),  ('Z1236'))
select no
from var_nos
left outer join
db_table
  on db_table.db_idno = var_nos.no
where db_table.db_idno is null

Alternatively:

select no
from table ( values ('Z1234'), ('Z1235'),  ('Z1236')) as var_nos (no)
where not exists (
  select 1 from db_table where db_table.db_idno = var_nos.no
)

P.S. Not tested.


问:
Error 404 when uploading a file caused by error in update function
I'm having a hard time trying to figure out what's wrong in my code. Basically, I'm using Dropzone-js's file uploader, that uses drag and drop.  I can't upload a file because it returns me a 404 error.
I searched through my logs and found that I had a problem in my controller, in the update function.

The controller :

```<code>class ChatRoomsController < ApplicationController
before_action :authenticate_user!
before_action :set_room, only: [:index, :new, :create, :show, :edit, :signal]
before_action :set_participant, only: [:signal]

def index
  @chat_rooms = ChatRoom.all
end

def show
  # Show room messages
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
  @message = Message.new

  @chat_room.participant?(current_user)

  # TODO: get participant only once
  if params[:guid]
    if @participant = User.find(params[:guid])
      @participant.joined_at = Time.now
      @chat_room.add_to_call(@participant)
    end
  elsif params[:del]
    if @participant = User.find(params[:del])
      @chat_room.remove_from_call(@participant)
    end
  end

  response = {
      room: @chat_room,
      # Get all call participants
      users: @chat_room.call_users,
      signals: deliver_signals!
  }

  respond_to do |format|
    format.html
    format.json { render json: response }
  end

end

def new
  @chat_room = ChatRoom.new
end

def edit
  # Empty
end

def create
  @chat_room = current_user.chat_rooms.build(chat_room_params)
  if @chat_room.save
    @group_room.users << current_user
    redirect_to chat_rooms_path
  else
    render 'new'
  end
end

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  if @chat_room.update_resource(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end

def signal
  signal = signal_params
  signal[:chat_room] = @chat_room
  signal[:sender] = User.find(signal[:sender])
  signal[:recipient] = @participant
  logger.info('Signal is ' + signal.to_param)
  ChatRoomSignal.create! signal
  head 204
end

def deliver_signals!
  data = ChatRoomSignal.where recipient: @participant

  # Destroy the signals as we return them, since they have been delivered
  result = []
  data.each do |signal|
    result << {
        signal_type: signal.signal_type,
        sender_guid: signal.sender_id,
        recipient_guid: signal.recipient_id,
        data: signal.data,
        chat_room_id: signal.chat_room_id,
        timestamp: signal.created_at
    }
  end
  data.delete_all
  result
end

private

def set_participant
  @participant = User.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
  # Retry with ID as GUID
  @participant = User.where(id: params[:user_id]).first
  raise unless @participant
end

def set_room
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:chat_room_id])
end

def chat_room_params
  params.require(:chat_room).permit(:title, :image)
end

def signal_params
  params.permit(:sender, :signal_type, :data)
end
</code>```

HTML code for file upload :

```<code><div class="panel-body">
  <%= form_for @chat_room, html: { multipart: true, class: "dropzone", id: "my-dropzone"} do |f| %>

    <div class="dz-message needsclick">
      <h3>Drop a file here</h3> or <strong>click</strong> to upload
    </div>

    <div class="fallback">
      <% f.file_field :image, as: :file %>
      <%= f.submit "Upload your file" %>
    </div>
 <% end %>
</div>
</code>```

The error :

```<code>[ActionCable] [test@test.com] ChatRoomsChannel is transmitting the subscription confirmation
[ActionCable] [test@test.com] ChatRoomsChannel is streaming from chat_rooms_1_channel
Started PATCH "/chat_rooms/1" for 127.0.0.1 at 2017-06-09 01:44:26 +0200
Processing by ChatRoomsController#update as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8KEWBx7fmJmEhHgINmp5rnj+PVwGXfbPHxslSaA4Z/5zA6HIJzxeBjwcz/+GcDEQKKwPwjXNJVnBtfq7xu2qw==", "chat_rooms"=>{"image"=>#    <ActionDispatch::Http::UploadedFile:0x007f640e58f5b0 @tempfile=#<Tempfile:/tmp/RackMultipart20170609-2887-1nuat54.png>, @original_filename="Screenshot from 2017-04-12 12-47-21.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"chat_rooms[image]\"; filename=\"Screenshot from 2017-04-12 12-47-21.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"1"}
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mChatRoom Load (0.2ms)[0m  [1m[34mSELECT  "chat_rooms".* FROM "chat_rooms" WHERE "chat_rooms"."id" = ? LIMIT ?[0m  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 7ms (ActiveRecord: 0.3ms)

ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>nil}):

app/controllers/chat_rooms_controller.rb:62:in `update'
</code>```

Line 62 :

```<code>@chat_room = ChatRoom.find(id: params[:chat_room_id])
</code>```

So it seems like my controller is not able to find the id parameter, but i don't understand why. And this is probably the error that causes my file to return 404 error.

Thanks for the time you will take to read my post.

答:
You are using the wrong key to get the id, try with params[:id]:

```<code>@chat_room = ChatRoom.find(params[:id])
</code>```

Also notice that the id: has been removed, since find will look for the id provided as parameter.

Also, you should update your chat_room_params method:

```<code>def chat_room_params
 params.require(:chat_rooms).permit(:title, :image)
end
</code>```

Since you are updating only 2 attributes, you could refactor your update method like this:

```<code>def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  @chat_room.title = chat_room_params[:title]
  @chat_room.image = chat_room_params[:image]

  if @chat_room.save(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end
</code>```

Body:
I'm having a hard time trying to figure out what's wrong in my code. Basically, I'm using Dropzone-js's file uploader, that uses drag and drop.  I can't upload a file because it returns me a 404 error.
I searched through my logs and found that I had a problem in my controller, in the update function.

The controller :

class ChatRoomsController < ApplicationController
before_action :authenticate_user!
before_action :set_room, only: [:index, :new, :create, :show, :edit, :signal]
before_action :set_participant, only: [:signal]

def index
  @chat_rooms = ChatRoom.all
end

def show
  # Show room messages
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
  @message = Message.new

  @chat_room.participant?(current_user)

  # TODO: get participant only once
  if params[:guid]
    if @participant = User.find(params[:guid])
      @participant.joined_at = Time.now
      @chat_room.add_to_call(@participant)
    end
  elsif params[:del]
    if @participant = User.find(params[:del])
      @chat_room.remove_from_call(@participant)
    end
  end

  response = {
      room: @chat_room,
      # Get all call participants
      users: @chat_room.call_users,
      signals: deliver_signals!
  }

  respond_to do |format|
    format.html
    format.json { render json: response }
  end

end

def new
  @chat_room = ChatRoom.new
end

def edit
  # Empty
end

def create
  @chat_room = current_user.chat_rooms.build(chat_room_params)
  if @chat_room.save
    @group_room.users << current_user
    redirect_to chat_rooms_path
  else
    render 'new'
  end
end

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  if @chat_room.update_resource(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end

def signal
  signal = signal_params
  signal[:chat_room] = @chat_room
  signal[:sender] = User.find(signal[:sender])
  signal[:recipient] = @participant
  logger.info('Signal is ' + signal.to_param)
  ChatRoomSignal.create! signal
  head 204
end

def deliver_signals!
  data = ChatRoomSignal.where recipient: @participant

  # Destroy the signals as we return them, since they have been delivered
  result = []
  data.each do |signal|
    result << {
        signal_type: signal.signal_type,
        sender_guid: signal.sender_id,
        recipient_guid: signal.recipient_id,
        data: signal.data,
        chat_room_id: signal.chat_room_id,
        timestamp: signal.created_at
    }
  end
  data.delete_all
  result
end

private

def set_participant
  @participant = User.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
  # Retry with ID as GUID
  @participant = User.where(id: params[:user_id]).first
  raise unless @participant
end

def set_room
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:chat_room_id])
end

def chat_room_params
  params.require(:chat_room).permit(:title, :image)
end

def signal_params
  params.permit(:sender, :signal_type, :data)
end

HTML code for file upload :

  <%= form_for @chat_room, html: { multipart: true, class: "dropzone", id: "my-dropzone"} do |f| %>

Drop a file here
 or click to upload

      <% f.file_field :image, as: :file %>
      <%= f.submit "Upload your file" %>

 <% end %>

The error :

[ActionCable] [test@test.com] ChatRoomsChannel is transmitting the subscription confirmation
[ActionCable] [test@test.com] ChatRoomsChannel is streaming from chat_rooms_1_channel
Started PATCH "/chat_rooms/1" for 127.0.0.1 at 2017-06-09 01:44:26 +0200
Processing by ChatRoomsController#update as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8KEWBx7fmJmEhHgINmp5rnj+PVwGXfbPHxslSaA4Z/5zA6HIJzxeBjwcz/+GcDEQKKwPwjXNJVnBtfq7xu2qw==", "chat_rooms"=>{"image"=>#    <ActionDispatch::Http::UploadedFile:0x007f640e58f5b0 @tempfile=#<Tempfile:/tmp/RackMultipart20170609-2887-1nuat54.png>, @original_filename="Screenshot from 2017-04-12 12-47-21.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"chat_rooms[image]\"; filename=\"Screenshot from 2017-04-12 12-47-21.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"1"}
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mChatRoom Load (0.2ms)[0m  [1m[34mSELECT  "chat_rooms".* FROM "chat_rooms" WHERE "chat_rooms"."id" = ? LIMIT ?[0m  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 7ms (ActiveRecord: 0.3ms)

ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>nil}):

app/controllers/chat_rooms_controller.rb:62:in `update'

Line 62 :

@chat_room = ChatRoom.find(id: params[:chat_room_id])

So it seems like my controller is not able to find the id parameter, but i don't understand why. And this is probably the error that causes my file to return 404 error.

Thanks for the time you will take to read my post.

Body:
You are using the wrong key to get the id, try with params[:id]:

@chat_room = ChatRoom.find(params[:id])

Also notice that the id: has been removed, since find will look for the id provided as parameter.

Also, you should update your chat_room_params method:

def chat_room_params
 params.require(:chat_rooms).permit(:title, :image)
end

Since you are updating only 2 attributes, you could refactor your update method like this:

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  @chat_room.title = chat_room_params[:title]
  @chat_room.image = chat_room_params[:image]

  if @chat_room.save(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end


问:
EPPLus - Excel column names not working
Question: How Can we add ws.Cells["AA"].Value = "MyColumn"; as a column name to Excel worksheet

Following works until column Z1. But I have more columns after Z column. So, if I add ws.Cells["AA"].Value = "MyColumn";, following does not work.:

```<code>ws.Cells["A1"].Value = "Number";
ws.Cells["B1"].Value = "First Name";
ws.Cells["C1"].Value = "Last Name";
ws.Cells["D1"].Value = "Country";
....
....
ws.Cells["Z1"].Value = "Country";
ws.Cells["AA"].Value = "MyColumn";
</code>```

答:
You're missing the row number?

ws.Cells["AA1"].Value = "MyColumn";

Title: EPPLus - Excel column names not working

Body:
Question: How Can we add ws.Cells["AA"].Value = "MyColumn"; as a column name to Excel worksheet

Following works until column Z1. But I have more columns after Z column. So, if I add ws.Cells["AA"].Value = "MyColumn";, following does not work.:

ws.Cells["A1"].Value = "Number";
ws.Cells["B1"].Value = "First Name";
ws.Cells["C1"].Value = "Last Name";
ws.Cells["D1"].Value = "Country";
....
....
ws.Cells["Z1"].Value = "Country";
ws.Cells["AA"].Value = "MyColumn";


问:
Mpdf - Preview the html before $mpdf->Output();
I had create a html page which has successfully created and exported as pdf using mpdf functions.

My question is, if it is possible before the

```<code>$mpdf->Output();
</code>```

to preview the html file as A4 size and edit the output with the

```<code>contenteditable="true"
</code>```

of each html element (body,tables, p, div, etc).

I had tried, but the view of html output is different than the mpdf output. (different sizes,dimension, images, tables etc)

答:
If I understand you correctly, the simplest answer (but not necessarily the true answer) is "no."

The reason for my answer is you've asked us to write a book.  Explaining all the Javascript, PHP, and HTML needed to control all the elements to a reasonable (but never infinitely variable) degree without some limitation (which you haven't provided) is a question that can't be answered here.  Consider that HTML is not designed to be printed while PDF is.  PDF can do many things HTML simply cannot.  Only one of the many problems with making a form-creation tool in a web browser is that browsers were literally designed to not care what a piece of paper is and PDF was just as literally designed to care exclusively about what a piece of paper is.

So, the true answer to your question is "yes."  But writing a full tutorial on how to do it is well beyond the scope of this forum.

If you are seeking to learn how to do this, then you need to understand both the pros and the cons.  For the pros and a starting point, you can start here.  For the cons, read this.

Body:
I had create a html page which has successfully created and exported as pdf using mpdf functions.

My question is, if it is possible before the

$mpdf->Output();

to preview the html file as A4 size and edit the output with the

contenteditable="true"

of each html element (body,tables, p, div, etc).

I had tried, but the view of html output is different than the mpdf output. (different sizes,dimension, images, tables etc)


问:
Error while executing test, if using CreateResponse extention method to return Azure Function HttpResonseMessage
My Azure Function code is like below

```<code>public static class MyHttpTriggerFunction
{
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        // some business logic

        if (valid)
        {
            return req.CreateResponse(HttpStatusCode.OK, true);
        }
        else
        {
             return req.CreateResponse(HttpStatusCode.BadRequest, "some error message");
        }
    }
}
</code>```

In my test project I am reading the result like below:

```<code>var result = await MyHttpTriggerFunction.Run(req, log).ConfigureAwait(false);
</code>```

After executing the function, when it try to return the response in result variable, the test method fails with exception.

**

System.InvalidOperationException: The request does not have an
  associated configuration object or the provided configuration was
  null.

**

I have made sure that test project has the same System.Net.Http.HttpRequestMessageExtension dll.

If I change the function  code not to use CreateResponse extension method (this extension method is from the VS 2017 template's code )
and return the response like below, I get the response in test method and  the test case  runs fine.

```<code>var res = new HttpResponseMessage();
if (valid)
{
    res.StatusCode = HttpStatusCode.OK;
    res.Content = new ObjectContent<bool>(true, new JsonMediaTypeFormatter());
    return res;
}
else
{
     res.StatusCode = HttpStatusCode.BadRequest;
     res.Content = new ObjectContent<string>("some error message", new JsonMediaTypeFormatter());
     return res;
}
</code>```

Below is the stacktrace of error

Result StackTrace:     at
  System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage
  request, HttpStatusCode statusCode, T value, HttpConfiguration
  configuration)    at
  System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage
  request, HttpStatusCode statusCode, T value)    at
  MyFunctionApp.MyHttpTriggerFunction.d__1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
  at
  MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.d__2.MoveNext()
  in
  C:\Users\rsingh\Desktop\Git_Workspace\ActivationAPI\MyFunctionAppUnitTest\MyHttpTriggerFunctionTest.cs:line
  53
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action
  action) Result Message:    Test method
  MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.MyHttpTriggerFunction_SuccessResult
  threw exception:  System.InvalidOperationException: The request does
  not have an associated configuration object or the provided
  configuration was null.

Am I missing something trivial

答:
The Error message is telling you the problem.

The request does not have an associated configuration object or the provided configuration was null.

When testing the request out side of a httpserver you need to give the request a HttpConfiguration.

```<code>// Arrange.
var configuration = new HttpConfiguration();
var request = new System.Net.Http.HttpRequestMessage();
request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

//...other code
</code>```

Body:
My Azure Function code is like below

public static class MyHttpTriggerFunction
{
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        // some business logic

        if (valid)
        {
            return req.CreateResponse(HttpStatusCode.OK, true);
        }
        else
        {
             return req.CreateResponse(HttpStatusCode.BadRequest, "some error message");
        }
    }
}

In my test project I am reading the result like below:

var result = await MyHttpTriggerFunction.Run(req, log).ConfigureAwait(false);

After executing the function, when it try to return the response in result variable, the test method fails with exception.

**

System.InvalidOperationException: The request does not have an
  associated configuration object or the provided configuration was
  null.

**

I have made sure that test project has the same System.Net.Http.HttpRequestMessageExtension dll.

If I change the function  code not to use CreateResponse extension method (this extension method is from the VS 2017 template's code )
and return the response like below, I get the response in test method and  the test case  runs fine.

var res = new HttpResponseMessage();
if (valid)
{
    res.StatusCode = HttpStatusCode.OK;
    res.Content = new ObjectContent<bool>(true, new JsonMediaTypeFormatter());
    return res;
}
else
{
     res.StatusCode = HttpStatusCode.BadRequest;
     res.Content = new ObjectContent<string>("some error message", new JsonMediaTypeFormatter());
     return res;
}

Below is the stacktrace of error

Result StackTrace:     at
  System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage
  request, HttpStatusCode statusCode, T value, HttpConfiguration
  configuration)    at
  System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage
  request, HttpStatusCode statusCode, T value)    at
  MyFunctionApp.MyHttpTriggerFunction.d__1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
  at
  MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.d__2.MoveNext()
  in
  C:\Users\rsingh\Desktop\Git_Workspace\ActivationAPI\MyFunctionAppUnitTest\MyHttpTriggerFunctionTest.cs:line
  53
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action
  action) Result Message:    Test method
  MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.MyHttpTriggerFunction_SuccessResult
  threw exception:  System.InvalidOperationException: The request does
  not have an associated configuration object or the provided
  configuration was null.

Am I missing something trivial

Body:
The Error message is telling you the problem.

The request does not have an associated configuration object or the provided configuration was null.

When testing the request out side of a httpserver you need to give the request a HttpConfiguration.

// Arrange.
var configuration = new HttpConfiguration();
var request = new System.Net.Http.HttpRequestMessage();
request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

//...other code


问:
Custom brace highlighting in Visual Studio Code
Is it possible to customize the brace highlighting in Visual Studio Code? It seems just about everything else is customizable through user and workspace settings, as well as textmate themes. Regardless of the syntax highlighting you employ, the braces always have the same light gray outline/rectangle around them. I don't see an existing user/workspace setting or a textmate scope that addresses this specific feature.

Ultimately I'd like to have a solid color highlight of matching braces, similar to what you would get with the default dark theme in Visual Studio 2013 and 2015.

答:
For future reference, vscode now has the option to change the color of bracket highlighting by adding this to settings.json:

```<code>"workbench.colorCustomizations" : {
        "editorBracketMatch.background": "#f008",
        "editorBracketMatch.border": "#f00"
}
</code>```

Formats supported are #RGB, #RGBA, #RRGGBB, #RRGGBBAA. The rgba(255,255,255,1) format that seems to work in other places in the settings file appears to not work here.

<s>Only feature that is still missing regarding this subject is bracket highlighting when the cursor is between brackets. They only highlight when one of the brackets is selected. I did not find a current solution searching trough the Settings or workbench.colorCustomizations.</s>

Update 2018.04.21
There is now a plugin called Bracket Pair Colorizer that does shows the current brackets besides the line number no matter where the cursor is placed within the brakes. But on slower hardware (3nd generation i5 laptop) i encountered slowdowns with it when editing large files (3000+ line php file). And alternate plugin that performs well on the same file and highlights the current indentation is Guides.

Update 2019.11.10
VSCode 1.40 now highlights the brackets enclosing the cursor.

Update 2021.08.09
as @desilicius mentioned in the comments Bracket Pair colorizer is no longer maintained by the author. He offers as an alternative Blockman - Highlight Nested Code Blocks  which has the same functionality but has a totally different look and Highlight Matching Tag which is a great plugin but only works on html (and jsx) tags as the name implies.

Update 2021.08.13
The VSCode team decided to add bracket pair colorization as a built in feature. It is worked on right now with improvements of 10k x the speed of BPC2. The discussion can be found here

Body:
For future reference, vscode now has the option to change the color of bracket highlighting by adding this to settings.json:

"workbench.colorCustomizations" : {
        "editorBracketMatch.background": "#f008",
        "editorBracketMatch.border": "#f00"
}

Formats supported are #RGB, #RGBA, #RRGGBB, #RRGGBBAA. The rgba(255,255,255,1) format that seems to work in other places in the settings file appears to not work here.

<s>Only feature that is still missing regarding this subject is bracket highlighting when the cursor is between brackets. They only highlight when one of the brackets is selected. I did not find a current solution searching trough the Settings or workbench.colorCustomizations.</s>

Update 2018.04.21
There is now a plugin called Bracket Pair Colorizer that does shows the current brackets besides the line number no matter where the cursor is placed within the brakes. But on slower hardware (3nd generation i5 laptop) i encountered slowdowns with it when editing large files (3000+ line php file). And alternate plugin that performs well on the same file and highlights the current indentation is Guides.

Update 2019.11.10
VSCode 1.40 now highlights the brackets enclosing the cursor.

Update 2021.08.09
as @desilicius mentioned in the comments Bracket Pair colorizer is no longer maintained by the author. He offers as an alternative Blockman - Highlight Nested Code Blocks  which has the same functionality but has a totally different look and Highlight Matching Tag which is a great plugin but only works on html (and jsx) tags as the name implies.

Update 2021.08.13
The VSCode team decided to add bracket pair colorization as a built in feature. It is worked on right now with improvements of 10k x the speed of BPC2. The discussion can be found here


答:
This is not specific to Azure Functions, but in order to execute this test outside of the context of an actual HTTP request you need to make sure you create an HttpConfiguartion instance, configure it as required (e.g. add any formatters you may need) and call SetConfiguration on the HttpRequestMessage instance with that object.

Example:

var configuration = new HttpConfiguration();
var request = new HttpRequestMessage();
request.SetConfiguration(configuration);
```

Title: Error while executing test, if using CreateResponse extention method to return Azure Function HttpResonseMessage


问:
Class accepts unspecified initilizer
I do not understand why the initialiser for Item_Base accepts another object as a valid input. I assume there is some implicit overload being used here?

```<code>class Item_Base
{
public:
  Item_Base(const std::string& item_name);
  ~Item_Base(void);
  std::string tostr();
private:
  const std::string name;
};

Item_Base::Item_Base(const std::string& item_name)
:name(item_name)
{
  std::cout << "Constructing: " << name << std::endl;
}

Item_Base::~Item_Base(void)
{
  std::cout << "Destructing: " << name << std::endl;
}

std::string Item_Base::tostr()
{
  return name;
}

int main(int argc, char **argv)
{
  Item_Base red_book("Red Book");
  Item_Base green_bow("Green Bow");
  Item_Base copy_test = red_book;
  Item_Base init_test(green_bow); // Why does this work?

  std::cout << red_book.tostr() << std::endl;
  std::cout << green_bow.tostr() << std::endl;
  std::cout << copy_test.tostr() << std::endl;
  std::cout << init_test.tostr() << std::endl;

  return 0;
}
</code>```

Output

```<code>Constructing: Red Book
Constructing: Green Bow
Red Book
Green Bow
Red Book
Green Bow
Destructing: Green Bow
Destructing: Red Book
Destructing: Green Bow
Destructing: Red Book
</code>```

答:
If you want to prevent copying and assignment, simply delete those methods:</p>

```<code>Item_Base(const Item_Base&) = delete;
Item_Base& operator=(const Item_Base&) = delete;
</code>```

Title: Class accepts unspecified initilizer

Body:
I do not understand why the initialiser for Item_Base accepts another object as a valid input. I assume there is some implicit overload being used here?

class Item_Base
{
public:
  Item_Base(const std::string& item_name);
  ~Item_Base(void);
  std::string tostr();
private:
  const std::string name;
};

Item_Base::Item_Base(const std::string& item_name)
:name(item_name)
{
  std::cout << "Constructing: " << name << std::endl;
}

Item_Base::~Item_Base(void)
{
  std::cout << "Destructing: " << name << std::endl;
}

std::string Item_Base::tostr()
{
  return name;
}

int main(int argc, char **argv)
{
  Item_Base red_book("Red Book");
  Item_Base green_bow("Green Bow");
  Item_Base copy_test = red_book;
  Item_Base init_test(green_bow); // Why does this work?

  std::cout << red_book.tostr() << std::endl;
  std::cout << green_bow.tostr() << std::endl;
  std::cout << copy_test.tostr() << std::endl;
  std::cout << init_test.tostr() << std::endl;

  return 0;
}

Output

Constructing: Red Book
Constructing: Green Bow
Red Book
Green Bow
Red Book
Green Bow
Destructing: Green Bow
Destructing: Red Book
Destructing: Green Bow
Destructing: Red Book

Body:
If you want to prevent copying and assignment, simply delete those methods:

Item_Base(const Item_Base&) = delete;
Item_Base& operator=(const Item_Base&) = delete;


问:
How does append() work behind the scenes that's causing this?
I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

```<code>func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v\n", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v\n", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors
</code>```

Try it here

So, what the heck is really going on here?

答:
append(foo[:i], foo[i+1:]...) does the following:

It takes the foo[:i] slice, which is foo[:0] and basically a slice with length 0 and capacity (at least) 3.

As soon as the capacity is enough to append the values - the underlying array is reused

You write b and c into the indexes 0 and 1 correspondingly of the underlying array.

Then you check the foo variable that uses the underlying array we just modified and that contains the b c c values.

Compare with the following:

```<code>noop(append(foo[:i], "a", "a", "a", "a", "a"))
</code>```

Here the list of values to append is longer than the current capacity. So the runtime allocates a new underlying array. And you don't mutate the foo. https://play.golang.org/p/RooYG_p9Z8

Body:
I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v\n", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v\n", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors

Try it here

So, what the heck is really going on here?

Body:
append(foo[:i], foo[i+1:]...) does the following:

It takes the foo[:i] slice, which is foo[:0] and basically a slice with length 0 and capacity (at least) 3.

As soon as the capacity is enough to append the values - the underlying array is reused

You write b and c into the indexes 0 and 1 correspondingly of the underlying array.

Then you check the foo variable that uses the underlying array we just modified and that contains the b c c values.

Compare with the following:

noop(append(foo[:i], "a", "a", "a", "a", "a"))

Here the list of values to append is longer than the current capacity. So the runtime allocates a new underlying array. And you don't mutate the foo. https://play.golang.org/p/RooYG_p9Z8


问:
Rails nested model forms: validate presence of foreign key unless user creates new record
In have a pretty simple rails app, here's my code:

```<code>class Post < ActiveRecord::Base
  belongs_to :category
  attr_accessible :category_id, :category_attributes
  accepts_nested_attributes_for :category, :reject_if => :all_blank
end

class Category < ActiveRecord::Base
  has_many :posts
end

#app/views/posts/_form.html.haml
= simple_form_for(@post) do |f|
  = f.association :category
  = f.simple_fields_for :category do |cat_f|
    = cat_f.input :name
</code>```

So when creating a new post, I have the option to choose a category (from the select menu) or create a new one (if it doesn't exist).

I want to validate that category_id is present, unless the user opts to create a new category

I'm guessing there's some kind of rails way to solve this problem - I know that I can't just add validates :category_id, :presence => true as this will cause form submission to fail when the user decides to create a new category (and doesn't select one from the drop-down).

Second Question:
I recently read a useful rails tutorial that showed you how to toggle between displaying the category select menu and the new category fields so that only one of the two is present on screen at any given time. Anyone got a link to something like that?

答:
In your PostsController, you probably want to check the incoming parameters in your create action to see if category_id is your default value (here, -1), and if so, create a new category from the text field. Something like this:

```<code>def create
  if params[:post][:category_id] != -1
    category = Category.create params[:post][:category_name]
    # make sure category is attached to post
  end

  # rest of your create action
end
</code>```

And something similar in your update action.

As for your second question, that's probably less Rails and better handled by Javascript. You could pretty easily have a radio button for 'use existing category' or 'create new category', and then use javascript to swap the DOM objects appropriately.

Body:
In have a pretty simple rails app, here's my code:

class Post < ActiveRecord::Base
  belongs_to :category
  attr_accessible :category_id, :category_attributes
  accepts_nested_attributes_for :category, :reject_if => :all_blank
end

class Category < ActiveRecord::Base
  has_many :posts
end

#app/views/posts/_form.html.haml
= simple_form_for(@post) do |f|
  = f.association :category
  = f.simple_fields_for :category do |cat_f|
    = cat_f.input :name

So when creating a new post, I have the option to choose a category (from the select menu) or create a new one (if it doesn't exist).

I want to validate that category_id is present, unless the user opts to create a new category

I'm guessing there's some kind of rails way to solve this problem - I know that I can't just add validates :category_id, :presence => true as this will cause form submission to fail when the user decides to create a new category (and doesn't select one from the drop-down).

Second Question:
I recently read a useful rails tutorial that showed you how to toggle between displaying the category select menu and the new category fields so that only one of the two is present on screen at any given time. Anyone got a link to something like that?

Body:
In your PostsController, you probably want to check the incoming parameters in your create action to see if category_id is your default value (here, -1), and if so, create a new category from the text field. Something like this:

def create
  if params[:post][:category_id] != -1
    category = Category.create params[:post][:category_name]
    # make sure category is attached to post
  end

  # rest of your create action
end

And something similar in your update action.

As for your second question, that's probably less Rails and better handled by Javascript. You could pretty easily have a radio button for 'use existing category' or 'create new category', and then use javascript to swap the DOM objects appropriately.