问:
How to call azure function with params
I am trying to use Azure function with to invoke the same function with different time and different param(url).
I didn't find any good example that shows how to pass some data. I want to pass link to function.
My code is:

```<code>var rp = require('request-promise');
var request = require('request');

module.exports = function (context //need to get the url) {
</code>```

and the function

```<code>{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 0 */1 * * *"
    }
  ],
  "disabled": false
}
</code>```

答:
If your settings are relatively static (but you still don't want to hard code them), you may use app settings to store them, and then read e.g.

```<code>let url = process.env['MyUrl'];
</code>```

If URL should be determined per request, you may use HTTP trigger and read the URL from query parameters:

```<code>let url = req.query.myurl;
</code>```

I'm not sure what exactly you are trying to achieve with parameterized timer-triggered function.

Title: How to call azure function with params

Body:
I am trying to use Azure function with to invoke the same function with different time and different param(url).
I didn't find any good example that shows how to pass some data. I want to pass link to function.
My code is:

var rp = require('request-promise');
var request = require('request');

module.exports = function (context //need to get the url) {

and the function

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 0 */1 * * *"
    }
  ],
  "disabled": false
}

Body:
If your settings are relatively static (but you still don't want to hard code them), you may use app settings to store them, and then read e.g.

let url = process.env['MyUrl'];

If URL should be determined per request, you may use HTTP trigger and read the URL from query parameters:

let url = req.query.myurl;

I'm not sure what exactly you are trying to achieve with parameterized timer-triggered function.


来源: stackexchange

问:
Finding the largest array index with negative value
Given an array of positive elements (1 based indexing), you have to process two types of queries:

(V) find the sum of numbers in the range 1:V (both inclusive)

(V, X)  subtract the number X to from all in the range 1:V and report the largest index i in range 1:V such that the value at that index is negative, where the answer for this query is 0 if no such index exists.

I can do the first query using fenwick tree or segment tree but how do i support second query? I have already tried an O(n) time per query approach just checking each element in range 1...V but it times out. I need to process 10^5 such queries over an array of size 10^5.

答:
Use a segment tree, such that every node stores the minimum value in its range and also the sum of the elements in its range. First query can be done directly in logn time complexity. For the second query, first subtract the given value from every element in the range (logn again) and then query for the rightmost value less than 0 (logn too).

EDIT: A better explanation

So first build a segment tree such that the leaves store the original value in the array. Every other node is built with two values: totalsum and minval. Build that easily with this equation:

```<code>segment_tree[id].minval = min(segment_tree[id*2].minval, segment_tree[id*2+1].minval)
segment_tree[id].totalsum = segment_tree[id*2].totalsum + segment_tree[id*2+1].totalsum
</code>```

The build takes O(n).

Query A: Finding the sum in some range is easy, just find the topmost ranges relevant to your query range and add them up. Time O(logn) per query.

Query B: Separate this query into two operations:

A) Subtracting X from a range: Let's say you subtract X from some range [a,b]. So the total sum of [a,b] becomes old_totalsum[a,b] - (b+1-a)*X and the new minimum value becomes old_minval[a,b] - X. The key is you again do it only on the topmost ranges of your segment tree that are under the query range, so that the operation takes only logn complexity. There's slightly more to this technique, you should read it online if you aren't familiar with it already (it's called Lazy Propagation).

B) Check the rightmost index with value < 0: Start your query on the root of the segment tree. Is the minimum value of the rightchild < 0? Then go there. Else is the minval of the leftchild < 0? Then go to the left child. If children have minval > 0, return -1. Once you reach a leaf, just return the index the leaf corresponds to. So you traverse once along the height of the tree, again O(logn).

So total complexity of the program would be O(n + Q.logn), where Q is the number of queries.

ContentLicense: CC BY-SA 3.0

Body:
Use a segment tree, such that every node stores the minimum value in its range and also the sum of the elements in its range. First query can be done directly in logn time complexity. For the second query, first subtract the given value from every element in the range (logn again) and then query for the rightmost value less than 0 (logn too).

EDIT: A better explanation

So first build a segment tree such that the leaves store the original value in the array. Every other node is built with two values: totalsum and minval. Build that easily with this equation:

segment_tree[id].minval = min(segment_tree[id*2].minval, segment_tree[id*2+1].minval)
segment_tree[id].totalsum = segment_tree[id*2].totalsum + segment_tree[id*2+1].totalsum

The build takes O(n).

Query A: Finding the sum in some range is easy, just find the topmost ranges relevant to your query range and add them up. Time O(logn) per query.

Query B: Separate this query into two operations:

A) Subtracting X from a range: Let's say you subtract X from some range [a,b]. So the total sum of [a,b] becomes old_totalsum[a,b] - (b+1-a)*X and the new minimum value becomes old_minval[a,b] - X. The key is you again do it only on the topmost ranges of your segment tree that are under the query range, so that the operation takes only logn complexity. There's slightly more to this technique, you should read it online if you aren't familiar with it already (it's called Lazy Propagation).

B) Check the rightmost index with value < 0: Start your query on the root of the segment tree. Is the minimum value of the rightchild < 0? Then go there. Else is the minval of the leftchild < 0? Then go to the left child. If children have minval > 0, return -1. Once you reach a leaf, just return the index the leaf corresponds to. So you traverse once along the height of the tree, again O(logn).

So total complexity of the program would be O(n + Q.logn), where Q is the number of queries.


问:
Unable to call @Html.Action() in jQuery
I'm trying to get the html from one of my partial views into a div tag with the id "searchpage" in my main view. However, when I follow the syntax in this answer, How to append an Html.Action to the jquery, I get the error in chrome developer tools,

```<code>Uncaught SyntaxError: Invalid or unexpected token
</code>```

The code is

```<code>$("#searchbutton").click(function () {
    $("#searchpage").html('@Html.Action("Search", "Employees")');
});
</code>```

The error is highlighted at (' specifically.

答:
I would suggest using an Ajax call, and loading the response:

```<code>$("#searchbutton").click(function () {

    var url = '@Url.Action("Search", "Employees")';

    $.get(url)
        .done(function(response, status, jqxhr){
            $("#searchpage").html(response);
        });
});
</code>```

If you are loading a static form, load it into a template script and copy it as needed:

```<code><script type="text/template" id="search-template">
    @Html.Action("Search", "Employees")
</script>
</code>```

Somewhere in your scripts:

```<code>$("#searchbutton").click(function () {

    var template = $('#search-template').clone().html();

    $("#searchpage").html(template);
});
</code>```

I'm assuming the error you're seeing is because your HTML is formatted, so the "string" you think you're building is actually invalid in the generated markup - it'll have newlines, which are a problem in JavaScript strings.

Title: Unable to call @Html.Action() in jQuery

Body:
I'm trying to get the html from one of my partial views into a div tag with the id "searchpage" in my main view. However, when I follow the syntax in this answer, How to append an Html.Action to the jquery, I get the error in chrome developer tools,

Uncaught SyntaxError: Invalid or unexpected token

The code is

$("#searchbutton").click(function () {
    $("#searchpage").html('@Html.Action("Search", "Employees")');
});

The error is highlighted at (' specifically.

Body:
I would suggest using an Ajax call, and loading the response:

$("#searchbutton").click(function () {

    var url = '@Url.Action("Search", "Employees")';

    $.get(url)
        .done(function(response, status, jqxhr){
            $("#searchpage").html(response);
        });
});

If you are loading a static form, load it into a template script and copy it as needed:

<script type="text/template" id="search-template">
    @Html.Action("Search", "Employees")
</script>

Somewhere in your scripts:

$("#searchbutton").click(function () {

    var template = $('#search-template').clone().html();

    $("#searchpage").html(template);
});

I'm assuming the error you're seeing is because your HTML is formatted, so the "string" you think you're building is actually invalid in the generated markup - it'll have newlines, which are a problem in JavaScript strings.


问:
How do I get CKEditor to work for inline editing
I want to use CKEditor to edit pages on my site.  The inline editing feature looks cool however I can't get it to work.

I copied the example on their website to one of my pages and i can edit the text but the CKEditor doesn't appear?  There are no errors in the console.

What is wrong.

答:
It turned out after a bit of research on the CKEditor website that CKEditor has a restricted set of Tags that it will pop up on.  You can see the list here on the CKEDITOR.dtd.$editable object

By default it only will pop up on the following tags

```<code>{address: 1, article: 1, aside: 1, blockquote: 1, body: 1, details: 1,
div: 1, fieldset: 1, figcaption: 1, footer: 1, form: 1,
h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1, header: 1, hgroup: 1, main: 1,
nav: 1, p: 1, pre: 1, section: 1}
</code>```

I was using  so it wasn't working.  Changed it to
 and it worked.

Body:
It turned out after a bit of research on the CKEditor website that CKEditor has a restricted set of Tags that it will pop up on.  You can see the list here on the CKEDITOR.dtd.$editable object

By default it only will pop up on the following tags

{address: 1, article: 1, aside: 1, blockquote: 1, body: 1, details: 1,
div: 1, fieldset: 1, figcaption: 1, footer: 1, form: 1,
h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1, header: 1, hgroup: 1, main: 1,
nav: 1, p: 1, pre: 1, section: 1}

I was using <span> so it wasn't working.  Changed it to <div> and it worked.


问:
SQL Server 2016 polybase error using hadoop
I have a simple pipe delimited file (newfile.txt) on my hdfs and I have configured my polybase correctly. I am having a tough time to import this file into my SQL Server using Polybase. Here are the queries:

At first an external file format is created:

```<code>CREATE EXTERNAL FILE FORMAT TextFile
WITH (
    FORMAT_TYPE = DELIMITEDTEXT
    , FORMAT_OPTIONS ( Field_Terminator = '|',
      USE_TYPE_DEFAULT = TRUE));
</code>```

Second, the data source for Hadoopcluster is created:

```<code>CREATE EXTERNAL DATA SOURCE HadoopCluster
    WITH (
        TYPE = HADOOP,
        LOCATION = 'hdfs://10.153.14.11:8020'
    )
</code>```

Finally, the external table is created which imports the data from hdfs:

```<code>create external table tmpExternal
(
    patientEncounter varchar(8000),
    PtAcctNo varchar(200))
    with (location = '/user/newfolder/',
          data_source = HadoopCluster,
          file_format = TextFile,
          reject_type = value,
          reject_value = 0);
</code>```

After running the above query, here is the error which I end up getting:

Msg 596, Level 21, State 1, Line 26

  Cannot continue the execution because the session is in the kill state.

Msg 0, Level 20, State 0, Line 26

  A severe error occurred on the current command.  The results, if any, should be discarded.

I am sure that there is no issue with disk space. Please assist.

UPDATE:
HDP 2.5 version is being used. I have installed Polybase successfully and this is my first external table I am trying to import from hdfs.

Format of the txt file has 2 rows and 2 columns:

1234|abcd

5676|efgh

答:
Did you get this fixed? I just spent 3 weeks with the SQL Product group to track down this issue.

In my case, we had EVENT NOTIFICATIONS set up to notify of DDL changes. It is a bug in their code and will be a future CU. If you have event notifications, drop them and try again.

Hope this helps.

Body:
I have a simple pipe delimited file (newfile.txt) on my hdfs and I have configured my polybase correctly. I am having a tough time to import this file into my SQL Server using Polybase. Here are the queries:

At first an external file format is created:

CREATE EXTERNAL FILE FORMAT TextFile
WITH (
    FORMAT_TYPE = DELIMITEDTEXT
    , FORMAT_OPTIONS ( Field_Terminator = '|',
      USE_TYPE_DEFAULT = TRUE));

Second, the data source for Hadoopcluster is created:

CREATE EXTERNAL DATA SOURCE HadoopCluster
    WITH (
        TYPE = HADOOP,
        LOCATION = 'hdfs://10.153.14.11:8020'
    )

Finally, the external table is created which imports the data from hdfs:

create external table tmpExternal
(
    patientEncounter varchar(8000),
    PtAcctNo varchar(200))
    with (location = '/user/newfolder/',
          data_source = HadoopCluster,
          file_format = TextFile,
          reject_type = value,
          reject_value = 0);

After running the above query, here is the error which I end up getting:

Msg 596, Level 21, State 1, Line 26

  Cannot continue the execution because the session is in the kill state.

Msg 0, Level 20, State 0, Line 26

  A severe error occurred on the current command.  The results, if any, should be discarded.

I am sure that there is no issue with disk space. Please assist.

UPDATE:
HDP 2.5 version is being used. I have installed Polybase successfully and this is my first external table I am trying to import from hdfs.

Format of the txt file has 2 rows and 2 columns:

1234|abcd

5676|efgh


问:
Transparent actionbar
Hi guys new Android developer here.

I'm currently trying to make my action bar transparent/translucent. I've already changed the background of my view to see if I'm doing this properly.

I've seen the numerous threads here but none of it is working for me.

I've tried making a custom style for my action bar and using: <item name="android:background">#55CC00CC</item> but this didn't work. I got a solid white color as background instead.

I also tried getting the ActionBar instance inside my activity and doing actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#55CC00CC"))); and I got this instead:

I'm trying to see if I can do this programmatically inside my activity. Some code to look at:

styles.xml:

```<code><resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="android:windowActionBarOverlay">true</item>
    </style>
</resources>
</code>```

MainActivity.java:

```<code>public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        setContentView(R.layout.activity_main);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#55CC00CC")));
    }
</code>```

Am I missing something obvious here? Thanks in advance.

答:
Had just fixed the same problem

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.AppBarOverlay"/>

</android.support.design.widget.AppBarLayout>
</code>```

And java side part

```<code>  mToolbar.getBackground().setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP);
                mToolbar.getBackground().setAlpha(0);
                mToolbarLayout.getBackground().setAlpha(0);
</code>```

Title: Transparent actionbar

Body:
Hi guys new Android developer here.

I'm currently trying to make my action bar transparent/translucent. I've already changed the background of my view to see if I'm doing this properly.

I've seen the numerous threads here but none of it is working for me.

I've tried making a custom style for my action bar and using: <item name="android:background">#55CC00CC</item> but this didn't work. I got a solid white color as background instead.

I also tried getting the ActionBar instance inside my activity and doing actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#55CC00CC"))); and I got this instead:

I'm trying to see if I can do this programmatically inside my activity. Some code to look at:

styles.xml:

<resources>

</resources>

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        setContentView(R.layout.activity_main);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#55CC00CC")));
    }

Am I missing something obvious here? Thanks in advance.

Body:
Had just fixed the same problem

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.AppBarOverlay"/>

</android.support.design.widget.AppBarLayout>

And java side part

  mToolbar.getBackground().setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP);
                mToolbar.getBackground().setAlpha(0);
                mToolbarLayout.getBackground().setAlpha(0);


问:
Does the compiler do the same action for all inline function calls?
Does C++ compiler take different decisions regarding inlining two different calls for the same inline function ?

consider a code like this:

```<code>inline func(int x) {
    return x + (x << 1) + (x << 2) + (x << 3) + (x << 4);
}

int main() {
    int y = func(1) + func(2) + func(3) + func(4);
    for(int i = 0; i < 100000000; ++i)
        y += func(i % 10);
    cout << y << endl;
    return 0;
}
</code>```

would the compiler do the same action with the calls before the loop and the one inside the loop ?
if we considered code length along with speed optimization then the calls before the loop shouldn't be inlined and the one inside should.

答:
It depends on your compiler. Let's say you use gcc 5.4.0 with -O2 optimization level. The first line inside the main function

```<code>int y = func(1) + func(2) + func(3) + func(4);
</code>```

will be calculated at compile time due to integer literals and the code inside the for loop will be inlined. But if you use another compiler or another optimization level the outcome can be different.

If you wish to inspect the assembly output of your code use the Compiler Explorer which is an online and free tool.

Body:
Does C++ compiler take different decisions regarding inlining two different calls for the same inline function ?

consider a code like this:

inline func(int x) {
    return x + (x << 1) + (x << 2) + (x << 3) + (x << 4);
}

int main() {
    int y = func(1) + func(2) + func(3) + func(4);
    for(int i = 0; i < 100000000; ++i)
        y += func(i % 10);
    cout << y << endl;
    return 0;
}

would the compiler do the same action with the calls before the loop and the one inside the loop ?
if we considered code length along with speed optimization then the calls before the loop shouldn't be inlined and the one inside should.

Body:
It depends on your compiler. Let's say you use gcc 5.4.0 with -O2 optimization level. The first line inside the main function

int y = func(1) + func(2) + func(3) + func(4);

will be calculated at compile time due to integer literals and the code inside the for loop will be inlined. But if you use another compiler or another optimization level the outcome can be different.

If you wish to inspect the assembly output of your code use the Compiler Explorer which is an online and free tool.


问:
MySQL JOIN two tables
I'm sorry about the ambiguous title - I couldn't come up with an explanation for the behaviour I want without giving examples. Also, if this is a duplicate thread, please point me to the correct one and I'll delete it. I couldn't search for what I wanted because, as I said above, it's hard to explain...

Anyway, I want to select data from two tables. One holds a bunch of projects, whereas another holds multiple checklist items for each project. I have a very primitive LEFT JOIN query at the moment, which returns this (there is only one project, at the moment):

```
name                    description
Project file symlinks   One
Project file symlinks   Two
Project file symlinks   seven
Project file symlinks   ahahahahaha
Project file symlinks   many
Project file symlinks   ANOTHER ONE
```

What I'd like to happen is this, for each project in the projects table:

```
name                    description
Project file symlinks   One
                        Two
                        seven
                        ahahahahaha
                        many
                        ANOTHER ONE
```

Or null, it doesn't matter. Essentially, I want to only print the project name once, but print all it's corresponding checklist items.

Here is the query I currently have:

```
SELECT Projects.name, DevProgress.description
FROM DevProgress
LEFT JOIN Projects
ON Projects.id = DevProgress.projectID
```

Can anyone offer a MySQL JOIN query so that I can get the behaviour I want? Thanks for any help,

EDIT

Thanks very much to dcp for helping me out. I eventually came up with this LEFT JOIN query, posted as reference:

```
SELECT name, GROUP_CONCAT(description) AS checklist
FROM Projects LEFT JOIN DevProgress ON Projects.id = DevProgress.projectID
GROUP BY name;
```

And the output:

```
name                      checklist
Project file symlinks     One,Two,seven,ahahahahaha,many,ANOTHER ONE
Testing Project numer 1   NULL
```

James

答:
You could use group_concat to get all the descriptions together for each project:

```<code>SELECT name,GROUP_CONCAT(description) FROM project GROUP BY name;
</code>```

So this will print the distinct project name, along with all the descriptions of that project on a single row, and each description will be comma delimited.

Sample:

```<code>create table project (name varchar(100), description varchar(100));

insert into project values ('Project file symlinks', 'One');
insert into project values ('Project file symlinks', 'Two');
insert into project values ('Project file symlinks', 'seven');
insert into project values ('Project file symlinks', 'ahahahahaha');
insert into project values ('Project file symlinks', 'many');
insert into project values ('Project file symlinks', 'ANOTHER ONE');

SELECT name,GROUP_CONCAT(description) FROM project GROUP BY name;
</code>```

Results:

```<code>name                       GROUP_CONCAT(description)
'Project file symlinks'    'One,Two,seven,ahahahahaha,many,ANOTHER ONE'
</code>```

ContentLicense: CC BY-SA 2.5

Title: MySQL JOIN two tables

Body:
I'm sorry about the ambiguous title - I couldn't come up with an explanation for the behaviour I want without giving examples. Also, if this is a duplicate thread, please point me to the correct one and I'll delete it. I couldn't search for what I wanted because, as I said above, it's hard to explain...

Anyway, I want to select data from two tables. One holds a bunch of projects, whereas another holds multiple checklist items for each project. I have a very primitive LEFT JOIN query at the moment, which returns this (there is only one project, at the moment):

name                    description
Project file symlinks   One
Project file symlinks   Two
Project file symlinks   seven
Project file symlinks   ahahahahaha
Project file symlinks   many
Project file symlinks   ANOTHER ONE

What I'd like to happen is this, for each project in the projects table:

name                    description
Project file symlinks   One
                        Two
                        seven
                        ahahahahaha
                        many
                        ANOTHER ONE

Or null, it doesn't matter. Essentially, I want to only print the project name once, but print all it's corresponding checklist items.

Here is the query I currently have:

SELECT Projects.name, DevProgress.description
FROM DevProgress
LEFT JOIN Projects
ON Projects.id = DevProgress.projectID

Can anyone offer a MySQL JOIN query so that I can get the behaviour I want? Thanks for any help,

EDIT

Thanks very much to dcp for helping me out. I eventually came up with this LEFT JOIN query, posted as reference:

SELECT name, GROUP_CONCAT(description) AS checklist
FROM Projects LEFT JOIN DevProgress ON Projects.id = DevProgress.projectID
GROUP BY name;

And the output:

name                      checklist
Project file symlinks     One,Two,seven,ahahahahaha,many,ANOTHER ONE
Testing Project numer 1   NULL

James

Body:
You could use group_concat to get all the descriptions together for each project:

SELECT name,GROUP_CONCAT(description) FROM project GROUP BY name;

So this will print the distinct project name, along with all the descriptions of that project on a single row, and each description will be comma delimited.

Sample:

create table project (name varchar(100), description varchar(100));

insert into project values ('Project file symlinks', 'One');
insert into project values ('Project file symlinks', 'Two');
insert into project values ('Project file symlinks', 'seven');
insert into project values ('Project file symlinks', 'ahahahahaha');
insert into project values ('Project file symlinks', 'many');
insert into project values ('Project file symlinks', 'ANOTHER ONE');

SELECT name,GROUP_CONCAT(description) FROM project GROUP BY name;

Results:

name                       GROUP_CONCAT(description)
'Project file symlinks'    'One,Two,seven,ahahahahaha,many,ANOTHER ONE'


问:
Full-height sidebar in Responsive Layout
I am trying to create a responsive layout with a full height sidebar. On desktop the sidebar should float left of the main content and on tablet/mobile, the sidebar should overlap the main content (when activated). I have managed to get this layout working fine for desktop, although I am using the background-color of the main content to make it "look" like the sidebar is full-height, which is not ideal, but can't seem to wrap my ahead around how to get this working for tablet/mobile. See pic to better explain what I am trying to accomplish. When window is shrunk down less than 980px, the body seems to want to stay at 980. Any help would be very appreciated

#sidebar {
  background: #FFF8DC;
  width: 300px;
  float: left;
  height: 100vh;
  margin-right: -300px;
  position: absolute;
  top: 0;
  left: 0;
}
#main-content {
  float: left;
  width: 100%;
  padding-left: 300px;
  background: #2373DE;
}
@media screen and (max-width: 991px) and (min-width: 768px) {
  #main-content {
    padding-left: 0;
  }
  #sidebar {
    z-index: 9;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <section id="sidebar">
    sidebar stuff
  </section>

  <section id="main-content">
    main content stuff
    <footer>
      footer stuff
    </footer>
  </section>
</body></code>```

答:
Here is a solution for making sidebar fixed on left side with 100% screen height and main-content with scrolling. You can change the properties (width, margin-left) of sidebar and main-content inside the media query to get the desired layout.

#sidebar {
  background: #FFF8DC;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
  overflow-y: auto;
  position: fixed;
  width: 300px;
}

#main-content {
  margin-left: 300px;
}

@media screen and (max-width: 991px) and (min-width: 768px) {
  #sidebar {
    width: 200px;
  }
  #main-content {
    margin-left: 200px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <section id="sidebar">
    sidebar stuff
  </section>

  <section id="main-content">
    main content stuff
    <footer>
      footer stuff
    </footer>
  </section>
</body></code>```

Body:
I am trying to create a responsive layout with a full height sidebar. On desktop the sidebar should float left of the main content and on tablet/mobile, the sidebar should overlap the main content (when activated). I have managed to get this layout working fine for desktop, although I am using the background-color of the main content to make it "look" like the sidebar is full-height, which is not ideal, but can't seem to wrap my ahead around how to get this working for tablet/mobile. See pic to better explain what I am trying to accomplish. When window is shrunk down less than 980px, the body seems to want to stay at 980. Any help would be very appreciated

#sidebar {
  background: #FFF8DC;
  width: 300px;
  float: left;
  height: 100vh;
  margin-right: -300px;
  position: absolute;
  top: 0;
  left: 0;
}
#main-content {
  float: left;
  width: 100%;
  padding-left: 300px;
  background: #2373DE;
}
@media screen and (max-width: 991px) and (min-width: 768px) {
  #main-content {
    padding-left: 0;
  }
  #sidebar {
    z-index: 9;
  }
}

    sidebar stuff

    main content stuff

      footer stuff

Body:
Here is a solution for making sidebar fixed on left side with 100% screen height and main-content with scrolling. You can change the properties (width, margin-left) of sidebar and main-content inside the media query to get the desired layout.

#sidebar {
  background: #FFF8DC;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
  overflow-y: auto;
  position: fixed;
  width: 300px;
}

#main-content {
  margin-left: 300px;
}

@media screen and (max-width: 991px) and (min-width: 768px) {
  #sidebar {
    width: 200px;
  }
  #main-content {
    margin-left: 200px;
  }
}

<body>
  <section id="sidebar">
    sidebar stuff
  </section>

  <section id="main-content">
    main content stuff
    <footer>
      footer stuff
    </footer>
  </section>
</body>


问:
Not getting the final output in the python program for web dev
I wrote the following code for printing the rot13 code for a string. Rot13 code is where you shift the letters of the string by 13 places. But for some reason, the textbox printed is always blank. Can someone please help me with this code?</p>

```<code>import os
import webapp2
import jinja2
import cgi
import string

template_dir= os.path.join(os.path.dirname(__file__), 'templates')
jinja_env= jinja2.Environment(loader= jinja2.FileSystemLoader(template_dir),
                                                                         autoescape= True) # automatically escapes all the variables

form="""
<form method="post">
      <textarea name="text" style="height: 100px; width: 400px;">%(val)s</textarea>
      <br>
      <input type="submit">
    </form>
"""

class Handler(webapp2.RequestHandler):
    def write(self,*a,**kw):
        self.response.out.write(*a,**kw)

    def render_str(self,template,**params):
        #Causes Jinja to load that file creating jinja template
        t=jinja_env.get_template(template)
        return t.render(params)

    def render(self,template,**kw):
        self.write(self.render_str(template,**kw))

class MainPage(webapp2.RequestHandler):

    def escape_html(self,s):
        return cgi.escape(s, quote=True)

    def write_form(self, s=''):
        self.response.out.write(form % {"val":s})

    def get(self):
        self.write_form()

    def rot13(self, s):
        out=""
        str1 =  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        str2 = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
        for c in s:
            if c in str1:
                k = str1.index(c)
                out += string.replace( s,c, str2[k])
            else:
                out += c
        return out

    def post(self):
        user_text = self.request.get('text')
        user_text = self.escape_html(user_text)
        user_text = self.rot13(user_text)

        self.write_form(user_text)

app = webapp2.WSGIApplication([
('/', MainPage)
], debug=True)
</code>```

答:
You can use:

```<code>import codecs
</code>```

and then into the POST you can convert directly the string to rot_13 using:

```<code>text = codecs.encode(user_text, 'rot_13')
</code>```

Here the the code modified:

```<code>import os
import webapp2
import jinja2
import cgi
import string
import codecs

template_dir= os.path.join(os.path.dirname(__file__), 'templates')
jinja_env= jinja2.Environment(loader=
jinja2.FileSystemLoader(template_dir),

autoescape= True) # automatically escapes all the variables

form="""
<form method="post">
  <textarea name="text" style="height: 100px; width: 400px;">%
  (val)s</textarea>
  <br>
  <input type="submit">
</form>
"""

class Handler(webapp2.RequestHandler):
   def write(self,*a,**kw):
      self.response.out.write(*a,**kw)

   def render_str(self,template,**params):
      #Causes Jinja to load that file creating jinja template
      t=jinja_env.get_template(template)
      return t.render(params)

   def render(self,template,**kw):
      self.write(self.render_str(template,**kw))

class MainPage(webapp2.RequestHandler):

    def escape_html(self,s):
        return cgi.escape(s, quote=True)

    def write_form(self, s=''):
        self.response.out.write(form % {"val":s})

    def get(self):
       self.write_form()

def post(self):
    user_text = self.request.get('text')
    text = codecs.encode(user_text, 'rot_13')
    self.write_form(text)

app = webapp2.WSGIApplication([
('/', MainPage)
], debug=True)
</code>```

Here the result animation with the app working:

Edits:
If you wants use your routine:

```<code>def rot13(self, s):
    out = ""
    str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    str2 = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
    for c in s:
        if c in str1:
            k = str1.index(c)
            #out += string.replace(s, c, str2[k])
            out += str2[k]
        else:
            out += c
    return out
</code>```

Body:
I wrote the following code for printing the rot13 code for a string. Rot13 code is where you shift the letters of the string by 13 places. But for some reason, the textbox printed is always blank. Can someone please help me with this code?

import os
import webapp2
import jinja2
import cgi
import string

template_dir= os.path.join(os.path.dirname(__file__), 'templates')
jinja_env= jinja2.Environment(loader= jinja2.FileSystemLoader(template_dir),
                                                                         autoescape= True) # automatically escapes all the variables

form="""
<form method="post">
      <textarea name="text" style="height: 100px; width: 400px;">%(val)s</textarea>

      <input type="submit">
    </form>
"""

class Handler(webapp2.RequestHandler):
    def write(self,*a,**kw):
        self.response.out.write(*a,**kw)

    def render_str(self,template,**params):
        #Causes Jinja to load that file creating jinja template
        t=jinja_env.get_template(template)
        return t.render(params)

    def render(self,template,**kw):
        self.write(self.render_str(template,**kw))

class MainPage(webapp2.RequestHandler):

    def escape_html(self,s):
        return cgi.escape(s, quote=True)

    def write_form(self, s=''):
        self.response.out.write(form % {"val":s})

    def get(self):
        self.write_form()

    def rot13(self, s):
        out=""
        str1 =  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        str2 = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
        for c in s:
            if c in str1:
                k = str1.index(c)
                out += string.replace( s,c, str2[k])
            else:
                out += c
        return out

    def post(self):
        user_text = self.request.get('text')
        user_text = self.escape_html(user_text)
        user_text = self.rot13(user_text)

        self.write_form(user_text)

app = webapp2.WSGIApplication([
('/', MainPage)
], debug=True)

Body:
You can use:

import codecs

and then into the POST you can convert directly the string to rot_13 using:

text = codecs.encode(user_text, 'rot_13')

Here the the code modified:

import os
import webapp2
import jinja2
import cgi
import string
import codecs

template_dir= os.path.join(os.path.dirname(__file__), 'templates')
jinja_env= jinja2.Environment(loader=
jinja2.FileSystemLoader(template_dir),

autoescape= True) # automatically escapes all the variables

form="""
<form method="post">
  <textarea name="text" style="height: 100px; width: 400px;">%
  (val)s</textarea>
  <br>
  <input type="submit">
</form>
"""

class Handler(webapp2.RequestHandler):
   def write(self,*a,**kw):
      self.response.out.write(*a,**kw)

   def render_str(self,template,**params):
      #Causes Jinja to load that file creating jinja template
      t=jinja_env.get_template(template)
      return t.render(params)

   def render(self,template,**kw):
      self.write(self.render_str(template,**kw))

class MainPage(webapp2.RequestHandler):

    def escape_html(self,s):
        return cgi.escape(s, quote=True)

    def write_form(self, s=''):
        self.response.out.write(form % {"val":s})

    def get(self):
       self.write_form()

def post(self):
    user_text = self.request.get('text')
    text = codecs.encode(user_text, 'rot_13')
    self.write_form(text)

app = webapp2.WSGIApplication([
('/', MainPage)
], debug=True)

Here the result animation with the app working:

Edits:
If you wants use your routine:

def rot13(self, s):
    out = ""
    str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    str2 = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
    for c in s:
        if c in str1:
            k = str1.index(c)
            #out += string.replace(s, c, str2[k])
            out += str2[k]
        else:
            out += c
    return out


问:
VIsual Studio 2017 NuGet package installs well but is not recognized
I have Solution A which has a .NET Core 1.1 class library project. In the Package properties I filled all NuGet fields and selected to create the NuGet upon successful build. This project builds just fine and the NUPKG is created. BTW How can I automatically copy the generated NUPKG to a local directory (my own repository)?

Then I have Solution B which is an ASP.NET Core 1.1 web application. In it I browse to my local repository (where I have manually copied the NUPKG built by Solution A) and install my SolutionA.MyPackage into the web application. VS.2017 says it was successful at installing it. I see it listed in the project's NuGet dependencies.

However, when I try to use ANY of the objects defined in that NuGet package I get a red highlight saying it is not found as if there was no NuGet or assembly reference to that DLL but there is!

What is causing this Visual Studio generated Nuget package to be installed and yet act as if it has not even been referenced?

UPDATE - CSPROJ TARGET
As for copying to my local repository, I added this to CSPROJ but it was not working (somebody had suggested it as I put it). I finally figured out why it did not work, the ItemGroup must be inside the Task.

```<code>  <Target Name="CopyPackage" AfterTargets="GenerateNuspec">
     <ItemGroup>
        <MyPackageFiles Include="bin\Release\PackageId.*.nupkg" />
     </ItemGroup>
     <Copy SourceFiles="@(MyPackageFiles)" DestinationFolder="D:\My Repository\MyNugget\Publish" />
  </Target>
</code>```

UPDATE NuGet Inspection
I opened the NUPKG with NuGet Package Explorer and it shows this more or less:

```<code>content\
        Properties\
           launchSettings.json
        Views\
           Shared\
              rest of my stuff here
contentFiles\
   any\
     netcoreapp1.1\
        Properties\
           launchSettings.json
        Views\
           Shared\
              rest of my stuff here
lib\
   netcoreapp1.1 (.NEtCoreApp, Version=v1.1)
         MyPackage.dll
</code>```

UPDATE 3
Since NuGet seems to have stopped working (used to work well earlier) I opted for using an Assembly Reference rather than a NuGet (for now). In this situation something odd happens, when coding I can reference ALL the objects in the referenced assembly (former NuGet) and therefore no compilation errors on the main project BUT when I then run the web application I get an internal error because it says

```<code>FileNotFoundException: Could not load file or assembly
'MyPackage, Version=0.0.3.0, Culture=neutral, PublicKeyToken=null'.
The system cannot find the file specified.

 Unknown location
</code>```

Which is strange because in the Solution Explorer I see the assembly reference and when I click on it (main application) I can navigate to all the objects that I have defined in that assembly. Why it cannot find it anymore?

答:
It is working again (as it was before!). Today I could open the solutions but when I tried to download an extension (Tools | Extensions) I got an error message about an Access Denied or something like that. It has happened before since I installed to VS.2017.

Of all the Visual Studios I have used since 2002 this has been the most unstable! (and I have update 15.2).

When I saw this error happening again I knew how to get rid of it and thought, "hey, maybe that is what is keeping the NuGet package to be installed but not found or the problem with a direct assembly reference".

So I went to my C:\Users\AppData\USER\Local\Microsoft\VisualStudio\15.2* folder and removed it completely.

After that I the ACCESS DENIED issue went away with the side effect that I had to reinstall all extensions again. I attempted again to install my own NuGet, it did so successfully and as expected (was not happening during the long glitch) the objects were found and the web application worked again.

Body:
I have Solution A which has a .NET Core 1.1 class library project. In the Package properties I filled all NuGet fields and selected to create the NuGet upon successful build. This project builds just fine and the NUPKG is created. BTW How can I automatically copy the generated NUPKG to a local directory (my own repository)?

Then I have Solution B which is an ASP.NET Core 1.1 web application. In it I browse to my local repository (where I have manually copied the NUPKG built by Solution A) and install my SolutionA.MyPackage into the web application. VS.2017 says it was successful at installing it. I see it listed in the project's NuGet dependencies.

However, when I try to use ANY of the objects defined in that NuGet package I get a red highlight saying it is not found as if there was no NuGet or assembly reference to that DLL but there is!

What is causing this Visual Studio generated Nuget package to be installed and yet act as if it has not even been referenced?

UPDATE - CSPROJ TARGET
As for copying to my local repository, I added this to CSPROJ but it was not working (somebody had suggested it as I put it). I finally figured out why it did not work, the ItemGroup must be inside the Task.

  <Target Name="CopyPackage" AfterTargets="GenerateNuspec">
     <ItemGroup>
        <MyPackageFiles Include="bin\Release\PackageId.*.nupkg" />
     </ItemGroup>
     <Copy SourceFiles="@(MyPackageFiles)" DestinationFolder="D:\My Repository\MyNugget\Publish" />
  </Target>

UPDATE NuGet Inspection
I opened the NUPKG with NuGet Package Explorer and it shows this more or less:

content\
        Properties\
           launchSettings.json
        Views\
           Shared\
              rest of my stuff here
contentFiles\
   any\
     netcoreapp1.1\
        Properties\
           launchSettings.json
        Views\
           Shared\
              rest of my stuff here
lib\
   netcoreapp1.1 (.NEtCoreApp, Version=v1.1)
         MyPackage.dll

UPDATE 3
Since NuGet seems to have stopped working (used to work well earlier) I opted for using an Assembly Reference rather than a NuGet (for now). In this situation something odd happens, when coding I can reference ALL the objects in the referenced assembly (former NuGet) and therefore no compilation errors on the main project BUT when I then run the web application I get an internal error because it says

FileNotFoundException: Could not load file or assembly
'MyPackage, Version=0.0.3.0, Culture=neutral, PublicKeyToken=null'.
The system cannot find the file specified.

 Unknown location

Which is strange because in the Solution Explorer I see the assembly reference and when I click on it (main application) I can navigate to all the objects that I have defined in that assembly. Why it cannot find it anymore?


问:
Tcsh and/or bash directory completion with variable hidden root prefix
I'm trying to set up directory completion in tcsh and/or bash (both are used at my site) with a slight twist: for a particular command "foo", I'd like to have completion use a custom function to match the first /-delimited term to an actual subtree node, and then follow normal directory completion for any successive terms.  It is sort of a combination of cdpath and completion, or I suppose a form of directory completion where the starting point is controlled by the completion script.  It would work as follows:

```<code>$ foo xxx<TAB>
(custom completion function produces choices it finds at arbitrary levels in the dir tree)
xxxYYY xxxZZZ xxxBLAH ...
foo xxxYYY/<TAB>
(normal directory completion proceeds from this point on, to produce something like:)
foo scene/shot/element/workspace/user/...
</code>```

We'd like to do this because we have a large production development tree (this is a CGI production facility), that shell-savvy users are navigating and jumping around in all the time.  The complaint is that the upper levels of the tree are cumbersome and redundant; they just need a quick search on the first term to find possible "head" choices and do directory completion from there.  It seems like programmable completion could offer a way to do this, but it is turning out to be pretty elusive.

I've made several attempts of custom bash and tcsh completion to do this, but the closest I've gotten is a form of "word completion" where the user must treat the directory levels as separate words with spaces (e.g. foo scene/ shot/ element/ workspace/ ...).  I could continue hacking at my current scripts--but I've been wondering if there's something I'm not understanding--this is my first attempt to program completion, and the docs and examples are pretty thin in shell books and on the internet.  If there's any completion-guru's out there that can get me on the right track, I'd appreciate it.

FWIW: here is what I've got so far (in tcsh first, then bash).  Note that the static root '/root/sub1/sub2/sub3' is just a placeholder for a search function that would find different matches in different levels.  If I can get that to work, I can sub in the search feature later.  Again, both examples do word completion, which requires user to type a space after each matching term (I also have to remove the spaces in the function to construct an actual path, yuck!)

TCSH EXAMPLE (note the function is actually a bash script):

```<code>complete complete_p2 'C@*@`./complete.p2.list.bash $:1 $:2 $:3 $:4 $:5 $:6 $:7 $:8 $:9`@@'

#!/bin/bash --norc

# complete.p2.list.bash - Completion prototype "p2" for shotc command

# Remove spaces from input arguments
ppath=`echo $@ | sed -e 's/ //g'`

# Print basenames (with trailing slashes) of matching dirs for completion
ls -1 -d /root/sub1/sub2/sub3/$ppath* 2>/dev/null | sed -e 's#^.*/##' | awk '{print $1 "/"}'
</code>```

BASH EXAMPLE:

```<code>_foo()
{
    local cur prev opts flist
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # Get all command words so far (omit command [0] element itself), remove spaces
    terms=`echo ${COMP_WORDS[@]:1} | sed -e 's/ //g'`

    # Get basenames (with trailing slashes) of matching dirs for completion
    flist=`ls -1 -d /root/sub1/sub2/sub3/${terms}* 2>/dev/null | sed -e 's#^.*/##' | awk '{print $1 "/"}' | xargs echo`

    COMPREPLY=( $(compgen -W "${flist}" ${cur}) )
    return 0
}
complete -F _foo foo
</code>```

答:
So, here is a tcsh solution.  Adds full $cdpath searching for autocompleting directories.  The complete command is:

```<code>complete cd 'C@/@d@''p@1@`source $HOME/bin/mycdpathcomplete.csh $:1`@/@'
</code>```

I am a bit of a tcsh hack, so the string manipulation is a bit crude.  But it works with negligible overhead... mycdpathcomplete.csh looks like this:

```<code>#!/bin/tcsh -f

set psuf=""
set tail=""

if ( $1 !~ "*/*" ) then
    set tail="/$1"
else
    set argsplit=(`echo "$1" | sed -r "s@(.*)(/[^/]*\')@\1 \2@"`)
    set psuf=$argsplit[1]
    set tail=$argsplit[2]
endif

set mycdpath=(. $cdpath)
set mod_cdpath=($mycdpath)

if ($psuf !~ "") then
    foreach i (`seq 1 1 $#mycdpath`)
        set mod_cdpath[$i]="$mycdpath[$i]/$psuf"
        if ( ! -d $mod_cdpath[$i] ) then
            set mod_cdpath[$i]=""
        endif
    end
endif

# debug statements
#echo "mycdpath = $mycdpath"
#echo "mod_cdpath = $mod_cdpath"
#echo "tail = $tail"
#echo "psuf = $psuf"

set matches=(`find -L $mod_cdpath -maxdepth 1 -type d -regex ".*${tail}[^/]*" | sed -r "s@.*(/?${psuf}${tail}[^/]*)\'@\1@" | sort -u`)

# prune self matches
if ($psuf =~ "") then
    foreach match (`seq 1 1 $#matches`)
        set found=0
        foreach cdp ($mod_cdpath)
            if ( -e "${cdp}${matches[$match]}" ) then
                set found=1;
                break;
            endif
        end
        if ( $found == 0 ) then
            set matches[$match]=""
        else
            set matches[$match]=`echo "$matches[$match]" | sed -r "s@^/@@"`
        endif
    end
endif

echo "$matches"
</code>```

OwnerDisplayName: Jeremy Y.

Body:
I'm trying to set up directory completion in tcsh and/or bash (both are used at my site) with a slight twist: for a particular command "foo", I'd like to have completion use a custom function to match the first /-delimited term to an actual subtree node, and then follow normal directory completion for any successive terms.  It is sort of a combination of cdpath and completion, or I suppose a form of directory completion where the starting point is controlled by the completion script.  It would work as follows:

$ foo xxx<TAB>
(custom completion function produces choices it finds at arbitrary levels in the dir tree)
xxxYYY xxxZZZ xxxBLAH ...
foo xxxYYY/<TAB>
(normal directory completion proceeds from this point on, to produce something like:)
foo scene/shot/element/workspace/user/...

We'd like to do this because we have a large production development tree (this is a CGI production facility), that shell-savvy users are navigating and jumping around in all the time.  The complaint is that the upper levels of the tree are cumbersome and redundant; they just need a quick search on the first term to find possible "head" choices and do directory completion from there.  It seems like programmable completion could offer a way to do this, but it is turning out to be pretty elusive.

I've made several attempts of custom bash and tcsh completion to do this, but the closest I've gotten is a form of "word completion" where the user must treat the directory levels as separate words with spaces (e.g. foo scene/ shot/ element/ workspace/ ...).  I could continue hacking at my current scripts--but I've been wondering if there's something I'm not understanding--this is my first attempt to program completion, and the docs and examples are pretty thin in shell books and on the internet.  If there's any completion-guru's out there that can get me on the right track, I'd appreciate it.

FWIW: here is what I've got so far (in tcsh first, then bash).  Note that the static root '/root/sub1/sub2/sub3' is just a placeholder for a search function that would find different matches in different levels.  If I can get that to work, I can sub in the search feature later.  Again, both examples do word completion, which requires user to type a space after each matching term (I also have to remove the spaces in the function to construct an actual path, yuck!)

TCSH EXAMPLE (note the function is actually a bash script):

complete complete_p2 'C@*@`./complete.p2.list.bash $:1 $:2 $:3 $:4 $:5 $:6 $:7 $:8 $:9`@@'

#!/bin/bash --norc

# complete.p2.list.bash - Completion prototype "p2" for shotc command

# Remove spaces from input arguments
ppath=`echo $@ | sed -e 's/ //g'`

# Print basenames (with trailing slashes) of matching dirs for completion
ls -1 -d /root/sub1/sub2/sub3/$ppath* 2>/dev/null | sed -e 's#^.*/##' | awk '{print $1 "/"}'

BASH EXAMPLE:

_foo()
{
    local cur prev opts flist
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # Get all command words so far (omit command [0] element itself), remove spaces
    terms=`echo ${COMP_WORDS[@]:1} | sed -e 's/ //g'`

    # Get basenames (with trailing slashes) of matching dirs for completion
    flist=`ls -1 -d /root/sub1/sub2/sub3/${terms}* 2>/dev/null | sed -e 's#^.*/##' | awk '{print $1 "/"}' | xargs echo`

    COMPREPLY=( $(compgen -W "${flist}" ${cur}) )
    return 0
}
complete -F _foo foo

Body:
So, here is a tcsh solution.  Adds full $cdpath searching for autocompleting directories.  The complete command is:

complete cd 'C@/@d@''p@1@`source $HOME/bin/mycdpathcomplete.csh $:1`@/@'

I am a bit of a tcsh hack, so the string manipulation is a bit crude.  But it works with negligible overhead... mycdpathcomplete.csh looks like this:

#!/bin/tcsh -f

set psuf=""
set tail=""

if ( $1 !~ "*/*" ) then
    set tail="/$1"
else
    set argsplit=(`echo "$1" | sed -r "s@(.*)(/[^/]*\')@\1 \2@"`)
    set psuf=$argsplit[1]
    set tail=$argsplit[2]
endif

set mycdpath=(. $cdpath)
set mod_cdpath=($mycdpath)

if ($psuf !~ "") then
    foreach i (`seq 1 1 $#mycdpath`)
        set mod_cdpath[$i]="$mycdpath[$i]/$psuf"
        if ( ! -d $mod_cdpath[$i] ) then
            set mod_cdpath[$i]=""
        endif
    end
endif

# debug statements
#echo "mycdpath = $mycdpath"
#echo "mod_cdpath = $mod_cdpath"
#echo "tail = $tail"
#echo "psuf = $psuf"

set matches=(`find -L $mod_cdpath -maxdepth 1 -type d -regex ".*${tail}[^/]*" | sed -r "s@.*(/?${psuf}${tail}[^/]*)\'@\1@" | sort -u`)

# prune self matches
if ($psuf =~ "") then
    foreach match (`seq 1 1 $#matches`)
        set found=0
        foreach cdp ($mod_cdpath)
            if ( -e "${cdp}${matches[$match]}" ) then
                set found=1;
                break;
            endif
        end
        if ( $found == 0 ) then
            set matches[$match]=""
        else
            set matches[$match]=`echo "$matches[$match]" | sed -r "s@^/@@"`
        endif
    end
endif

echo "$matches"


问:
How to enable JSON calls in my ASP.NET MVC 2 application?
I'm trying to make a dynamic chart using HighCharts, but as it seems to be, is impossible to include ASP tags inside a JavaScript, so I'm trying to use JSon. I followed this tutorual step-by-step, but when I try to load the page, I get the following message:

This request has been blocked because
  sensitive information could be
  disclosed to third party web sites
  when this is used in a GET request. To
  allow GET requests, set
  JsonRequestBehavior to AllowGet.

So now I'm wondering if I have to set something in Web.Config or somewhere else.

Could you guys help me?

答:
There is a pretty simple fix.  In your request-handling functions, where you would have:

```<code>return Json(myStuff);
</code>```

Replace it with the overload that takes a JsonRequestBehavior:

```<code>return Json(myStuff, JsonRequestBehavior.AllowGet);
</code>```

Body:
There is a pretty simple fix.  In your request-handling functions, where you would have:

return Json(myStuff);

Replace it with the overload that takes a JsonRequestBehavior:

return Json(myStuff, JsonRequestBehavior.AllowGet);


问:
Bash - while inside for loop not exiting
I'm a beginner getting started with bash scripting.

I have 10 directories in current working directory dir1-dir10 + script.sh + a file called "tocopyfile".

Dir1-10 are empty.
tocopyfile is a test text file to be used for the purpose of my training
script.sh contains the following code:

```<code>dir=`pwd`
i="0"
for directory in `ls $dir`;do
        while [ $i -le 10 ]
        do
        cp tocopyfile $directory/file$i &
        i=$[$i+1]
        done
done
</code>```

The script should copy 10 copies of the file "tocopyfile" to every dir (dir1-10) in the naming convention file#. The problem is that ones the script is exists after the first directory without executing the while loop to the remaining remaining dirs.

Can someone explain what I'm doing wrong please?

Help is greatly appreciated.

答:
You need to initialize $i inside the for loop, such that $i == 0 upon each iteration of your while:

```<code>dir=`pwd`
for directory in `ls $dir`;do
    i="0" # <===== notice the change here
    while [ $i -le 10 ]
    do
    cp tocopyfile $directory/file$i &
    i=$[$i+1]
    done
done
</code>```

Other things you might want to change:

Double-quote all your variables (in the event they have spaces in them).

Use $() instead of the long-deprecated back-tick syntax.

Use $(()) instead of the deprecated $[] syntax.

Tidy up your indentation.

Body:
I'm a beginner getting started with bash scripting.

I have 10 directories in current working directory dir1-dir10 + script.sh + a file called "tocopyfile".

Dir1-10 are empty.
tocopyfile is a test text file to be used for the purpose of my training
script.sh contains the following code:

dir=`pwd`
i="0"
for directory in `ls $dir`;do
        while [ $i -le 10 ]
        do
        cp tocopyfile $directory/file$i &
        i=$[$i+1]
        done
done

The script should copy 10 copies of the file "tocopyfile" to every dir (dir1-10) in the naming convention file#. The problem is that ones the script is exists after the first directory without executing the while loop to the remaining remaining dirs.

Can someone explain what I'm doing wrong please?

Help is greatly appreciated.

Body:
You need to initialize $i inside the for loop, such that $i == 0 upon each iteration of your while:

dir=`pwd`
for directory in `ls $dir`;do
    i="0" # <===== notice the change here
    while [ $i -le 10 ]
    do
    cp tocopyfile $directory/file$i &
    i=$[$i+1]
    done
done

Other things you might want to change:

Double-quote all your variables (in the event they have spaces in them).

Use $() instead of the long-deprecated back-tick syntax.

Use $(()) instead of the deprecated $[] syntax.

Tidy up your indentation.


问:
IronPython error, "'TextBox' object has no attribute 'text'" when using a ShowDialog() method created in SharpDevelop
I am trying to call a form designed in SharpDevelop within another IDE. I get the following error message: 'TextBox' object has no attribute 'text'. This happens when I run the script which includes the lines shown below in the other IDE. Is the problem in the script itself or in the Form1 class written in SharpDevelop? How can I resolve this? </p>

```<code>import myform
import System

f = myform.Form1()
if f.ShowDialog() == System.Windows.Forms.DialogResult.OK:
    dx = f._directionx.text
    dy = f._directiony.text
    dz = f._directionz.text
    nb = f._nbofiterations.text
    w = f._width.text
    h = f._height.text
</code>```

答:
change .text to .Text
dx = f._directionx.Text
and so on
C sharp is case sensitive language </p>

Body:
I am trying to call a form designed in SharpDevelop within another IDE. I get the following error message: 'TextBox' object has no attribute 'text'. This happens when I run the script which includes the lines shown below in the other IDE. Is the problem in the script itself or in the Form1 class written in SharpDevelop? How can I resolve this?

import myform
import System

f = myform.Form1()
if f.ShowDialog() == System.Windows.Forms.DialogResult.OK:
    dx = f._directionx.text
    dy = f._directiony.text
    dz = f._directionz.text
    nb = f._nbofiterations.text
    w = f._width.text
    h = f._height.text


问:
Stacking md-chips vertically while keeping input on top
I have been trying out md-chips provided by angular and have been trying to stack them vertically. I looked at demos and also at this answer:

Stack md-chips vertically angularjs

The issue with that answer is that the input field keeps moving as more chips are added. I wish to keep the input field at the top while stacking the chips underneath the input field. Is there any way that can be done by possibly changing any aspect of css or having another input field there or does md-chips not allow that?

答:
Almost same answer as you mentioned, but with float: none; to the container.

```<code>md-chip {
  clear: left;
}

.md-chip-input-container {
    float: none;
}
</code>```

CSS is in a

    <md-chips ng-model="myChips">
      <md-chip-template>
        {{$chip}}
      </md-chip-template>
    </md-chips>

```

Body:
Almost same answer as you mentioned, but with float: none; to the container.

md-chip {
  clear: left;
}

.md-chip-input-container {
    float: none;
}

CSS is in a <style> tag because it needs to be loaded after stylesheets

angular
  .module('MyApp', ['ngMaterial'])
  .controller('demoCtrl', function($scope) {

    $scope.myChips = ['AAA', 'BBB', 'CCC'];
  });

<head>
  <link rel="stylesheet" href="https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.3/angular-material.css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
  <script src="https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.3/angular-material.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
  <style>
    md-chip {
      clear: left;
    }

    .md-chips {
      background-color: beige;
    }

    .md-chips .md-chip-input-container {
      float: none;
    }

    .md-chip-input-container .md-input {
      border: 1px solid black !important;
      margin-top: 8px;
    }
  </style>
</head>

<body>
  <div ng-controller="demoCtrl" ng-app="MyApp">
    <md-chips ng-model="myChips">
      <md-chip-template>
        <strong>{{$chip}}</strong>
      </md-chip-template>
    </md-chips>
  </div>
</body>


问:
How to extract only text from HTML in Golang?
To extract text from HTML, I use a fully HTML5-compliant tokenizer and parser, like this

```<code>    s := `
<p>Links:</p><ul><li><a href="foo">Foo</a><li>
<a href="/bar/baz">BarBaz</a></ul><span>TEXT <b>I</b> WANT</span>
<script type='text/javascript'>
/* <![CDATA[ */
var post_notif_widget_ajax_obj = {"ajax_url":"http:\/\/site.com\/wp-admin\/admin-ajax.php","nonce":"9b8270e2ef","processing_msg":"Processing..."};
/* ]]> */
</script>`

    domDocTest := html.NewTokenizer(strings.NewReader(s))
    for tokenType := domDocTest.Next(); tokenType != html.ErrorToken; {
        if tokenType != html.TextToken {
            tokenType = domDocTest.Next()
            continue
        }
        TxtContent := strings.TrimSpace(html.UnescapeString(string(domDocTest.Text())))
        if len(TxtContent) > 0 {
            fmt.Printf("%s\n", TxtContent)
        }
        tokenType = domDocTest.Next()
    }
</code>```

but I got this result

```<code>Links:
Foo
BarBaz
TEXT
I
WANT
/* <![CDATA[ */
var post_notif_widget_ajax_obj = {"ajax_url":"http:\/\/site.com\/wp-admin\/admin-ajax.php","nonce":"9b8270e2ef","processing_msg":"Processing..."};
/* ]]> */
</code>```

I don't want CDATA content. Some idea, how to get only the text content?

答:
If you use github.com/PuerkitoBio/goquery it's pretty easy to achieve what you want.

You first need to use document.Find() to identify the element you want to remove, in your case scripts, so document.Find(scripts)

Then, you need to remove it from the document using element.Remove()

Finally, you print/get the text using document.Text()

So, the final code would be

```<code>package main

import (
  "fmt"
  "strings"
  "github.com/PuerkitoBio/goquery"
)

func main(){
  s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul><span>TEXT <b>I</b> WANT</span><script type='text/javascript'>/* <![CDATA[ */var post_notif_widget_ajax_obj = {"ajax_url":"http:\/\/site.com\/wp-admin\/admin-ajax.php","nonce":"9b8270e2ef","processing_msg":"Processing..."};/* ]]> */</script>`

  p := strings.NewReader(s)
  doc, _ := goquery.NewDocumentFromReader(p)

  doc.Find("script").Each(func(i int, el *goquery.Selection) {
      el.Remove()
  })

  fmt.Println(doc.Text()) // Links:FooBarBazTEXT I WANT

}
</code>```

Body:
To extract text from HTML, I use a fully HTML5-compliant tokenizer and parser, like this

    s := `

Links:

Foo

BarBaz
TEXT I WANT
`

    domDocTest := html.NewTokenizer(strings.NewReader(s))
    for tokenType := domDocTest.Next(); tokenType != html.ErrorToken; {
        if tokenType != html.TextToken {
            tokenType = domDocTest.Next()
            continue
        }
        TxtContent := strings.TrimSpace(html.UnescapeString(string(domDocTest.Text())))
        if len(TxtContent) > 0 {
            fmt.Printf("%s\n", TxtContent)
        }
        tokenType = domDocTest.Next()
    }

but I got this result

Links:
Foo
BarBaz
TEXT
I
WANT
/* <![CDATA[ */
var post_notif_widget_ajax_obj = {"ajax_url":"http:\/\/site.com\/wp-admin\/admin-ajax.php","nonce":"9b8270e2ef","processing_msg":"Processing..."};
/* ]]> */

I don't want CDATA content. Some idea, how to get only the text content?

Body:
If you use github.com/PuerkitoBio/goquery it's pretty easy to achieve what you want.

You first need to use document.Find() to identify the element you want to remove, in your case scripts, so document.Find(scripts)

Then, you need to remove it from the document using element.Remove()

Finally, you print/get the text using document.Text()

So, the final code would be

package main

import (
  "fmt"
  "strings"
  "github.com/PuerkitoBio/goquery"
)

func main(){
  s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul><span>TEXT <b>I</b> WANT</span><script type='text/javascript'>/* <![CDATA[ */var post_notif_widget_ajax_obj = {"ajax_url":"http:\/\/site.com\/wp-admin\/admin-ajax.php","nonce":"9b8270e2ef","processing_msg":"Processing..."};/* ]]> */</script>`

  p := strings.NewReader(s)
  doc, _ := goquery.NewDocumentFromReader(p)

  doc.Find("script").Each(func(i int, el *goquery.Selection) {
      el.Remove()
  })

  fmt.Println(doc.Text()) // Links:FooBarBazTEXT I WANT

}


问:
"Position: fixed" in CSS changes "justify-content-end"
I'm trying to make a navigation bar with the content on the right of the page. This worked until I added position:fixed in CSS. After I added position:fixed, the content got relocated to the left of the page. Can someone tell me why this happened?

.header {
  position: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <ul class="nav nav-pills justify-content-end">
    <li class="active">About</li>
    <li> Portfolio</li>
    <li>Contact</li>
  </ul>
</div></code>```

答:
https://developer.mozilla.org/en-US/docs/Web/CSS/position?v=control

Fixed: Do not leave space for the element. Instead, position it at a specified position relative to the screen's viewport and don't move it when scrolled. [...]

The specified position by default will be at the top/left of the screen without any additional positioning in the CSS. To move it around, use the top left right bottom properties. To move it to the right, specify a value for right that matches the distance you want the menu to be from the right side of the page.

.header {
  position: fixed;
  top: 1em; right: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <ul class="nav nav-pills justify-content-end">
    <li class="active">About</li>
    <li> Portfolio</li>
    <li>Contact</li>
  </ul>
</div></code>```

Body:
I'm trying to make a navigation bar with the content on the right of the page. This worked until I added position:fixed in CSS. After I added position:fixed, the content got relocated to the left of the page. Can someone tell me why this happened?

.header {
  position: fixed;
}

About

 Portfolio

Contact

Body:
https://developer.mozilla.org/en-US/docs/Web/CSS/position?v=control

Fixed: Do not leave space for the element. Instead, position it at a specified position relative to the screen's viewport and don't move it when scrolled. [...]

The specified position by default will be at the top/left of the screen without any additional positioning in the CSS. To move it around, use the top left right bottom properties. To move it to the right, specify a value for right that matches the distance you want the menu to be from the right side of the page.

.header {
  position: fixed;
  top: 1em; right: 1em;
}

<div class="header">
  <ul class="nav nav-pills justify-content-end">
    <li class="active"><a data-toggle="pill" class="nav-link active" href="#">About</a></li>
    <li> <a data-toggle="pill" class="nav-link" href="#">Portfolio</a></li>
    <li><a data-toggle="pill" class="nav-link" href="#">Contact</a></li>
  </ul>
</div>


问:
Mercurial Error. Not under root
I'm getting the following error when trying to add files to my mercurial repo.

```<code>abort: /HRTRL/img not under root
</code>```

This started when a developer here decided to ignore our normal workflow and made changes directly to the production server instead of making them in his working directory and then pushing them to the test repo. I then needed to sync the test repo with his changes, so what I ended up doing was just copying his changes over to my working directory, which was current, and then pushing to the central repository. I did not use mercurial when copying and removing files. I now have untracked files in my directory and would like to add them so I can commit. I end up with the above error.

This is the output of hg status

```<code>! HRTRL/css/grid.css
! HRTRL/css/ie.css
! HRTRL/css/ie7.css
! HRTRL/css/jquery.lightbox-0.5.css
! HRTRL/css/layout.css
! HRTRL/css/productPages.css
! HRTRL/css/reset.css
! HRTRL/css/typography.css
? HRTRL/img/webheadercenter.jpg
? HRTRL/img/webheaderleft.jpg
? HRTRL/img/webheaderright.jpg
? HRTRL/includes/CallLog/tests/all_tests.php
? HRTRL/includes/CallLog/views/index.php
? HRTRL/includes/CallLog/views/styles/style.css
</code>```

答:
If you want:

All those with status ! (file is tracked in repository, but missing on disk), to be removed

All those with status ? (file is unknown), to be added

Then you can simply issue the following command:

```<code>hg addremove --similarity 90
</code>```

You can, if you want to, drop the --similarity 90 part, but if you leave it will try to find out if you have renamed the added files from some of the missing ones.

If you can, I would try using TortoiseHg to do the addremove, since it can also do the similarity check to see if you've copied the files, this might make history for those files more correct if they are copies from existing (and still tracked) files. The addremove --similarity 90 part will only check for renames/moves, not for copies.

Or, if you only want some of the files, you can do it manually. For each of the files with status !, you can issue the following command:

```<code>hg remove --after X
</code>```

where X is the path to and name of the file, for instance:

```<code>hg remove --after HRTRL/css/grid.css
</code>```

and then for each of the status ? files you want added:

```<code>hg add X
</code>```

example:

```<code>hg add HRTRL/img/webheadercenter.jpg
</code>```

Title: Mercurial Error. Not under root

Body:
I'm getting the following error when trying to add files to my mercurial repo.

abort: /HRTRL/img not under root

This started when a developer here decided to ignore our normal workflow and made changes directly to the production server instead of making them in his working directory and then pushing them to the test repo. I then needed to sync the test repo with his changes, so what I ended up doing was just copying his changes over to my working directory, which was current, and then pushing to the central repository. I did not use mercurial when copying and removing files. I now have untracked files in my directory and would like to add them so I can commit. I end up with the above error.

This is the output of hg status

! HRTRL/css/grid.css
! HRTRL/css/ie.css
! HRTRL/css/ie7.css
! HRTRL/css/jquery.lightbox-0.5.css
! HRTRL/css/layout.css
! HRTRL/css/productPages.css
! HRTRL/css/reset.css
! HRTRL/css/typography.css
? HRTRL/img/webheadercenter.jpg
? HRTRL/img/webheaderleft.jpg
? HRTRL/img/webheaderright.jpg
? HRTRL/includes/CallLog/tests/all_tests.php
? HRTRL/includes/CallLog/views/index.php
? HRTRL/includes/CallLog/views/styles/style.css

Body:
If you want:

All those with status ! (file is tracked in repository, but missing on disk), to be removed

All those with status ? (file is unknown), to be added

Then you can simply issue the following command:

hg addremove --similarity 90

You can, if you want to, drop the --similarity 90 part, but if you leave it will try to find out if you have renamed the added files from some of the missing ones.

If you can, I would try using TortoiseHg to do the addremove, since it can also do the similarity check to see if you've copied the files, this might make history for those files more correct if they are copies from existing (and still tracked) files. The addremove --similarity 90 part will only check for renames/moves, not for copies.

Or, if you only want some of the files, you can do it manually. For each of the files with status !, you can issue the following command:

hg remove --after X

where X is the path to and name of the file, for instance:

hg remove --after HRTRL/css/grid.css

and then for each of the status ? files you want added:

hg add X

example:

hg add HRTRL/img/webheadercenter.jpg


问:
C/C++: uint8_t bitfields behave incorrectly and inconsistently
I have the following code:

```<code>struct Foo {
  uint16_t a:5;
  uint16_t b:5;
  uint16_t c:5;
};
uint16_t bits = 0xdae;
const Foo& foo = *reinterpret_cast<const Foo*>(&bits);

printf("%x %x %x\n", foo.a, foo.b, foo.c);
</code>```

The output is what I expect when I work it out on paper:

e d 3

If I use uint32_t instead of uint16_t bitfields, I get the same result.

But when I use uint8_t bitfields instead of uint16_t, I get an inconsistent result that is either:

e d 6

or

e d 16

Neither is correct. Why does using uint8_t for bitfields cause this strange behavior?

答: The compiler may add padding between structure members (or it may not, at its discretion) and you don't account for that when you just try to access the entire struct as a bunch of bits. Basically you can't just do that (the behaviour is undefined and your code is simply buggy). You need to access the structure members by name or use compiler specific extensions to control the layout/padding.

Body:
I have the following code:

struct Foo {
  uint16_t a:5;
  uint16_t b:5;
  uint16_t c:5;
};
uint16_t bits = 0xdae;
const Foo& foo = *reinterpret_cast<const Foo*>(&bits);

printf("%x %x %x\n", foo.a, foo.b, foo.c);

The output is what I expect when I work it out on paper:

e d 3

If I use uint32_t instead of uint16_t bitfields, I get the same result.

But when I use uint8_t bitfields instead of uint16_t, I get an inconsistent result that is either:

e d 6

or

e d 16

Neither is correct. Why does using uint8_t for bitfields cause this strange behavior?


问:
PHP running 1 query for multiple variables from array
Using the below code in an attempt to run a single query with exploded array variables:

```<code> <?php
 $containers = $_POST['cntnum'];
 $containersArray = preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$containers)));
 $count = count($containersArray);

 for($i = 0; $i < $count; $i++)
 {
   $container = $containersArray[$i];
   $cntFixed = "'".$container."',";
 }

 $select = "SELECT container, date, pool FROM inventory WHERE container IN (".$ctnFixed.")";

 $query = mysqli_query($dbc, $select) or die(mysqli_error());

 ?>
</code>```

When I pass $cntFixed into the query.  I don't get all of the variables that were in the array.  Instead, I only get the last of the variables with an ending comma, as shown when I print to the console here:

```<code>  "SELECT container, date, pool FROM inventory WHERE container IN ('variable3',)"
</code>```

Of course, the ending comma will throw the query off, so I need to take that into consideration.

I cannot put the query into the for loop, because that runs the query the same amount of times as the array count.

What I need to do is run the query 1 time with all of the variables passed into the query.

The query should look like this when I print it to the console:

```<code> "SELECT container, date, pool FROM inventory WHERE container IN ('variable1', 'variable2', 'variable3')"
</code>```

答:
You must use the .= operator,

PHP documentation here:
http://php.net/manual/en/language.operators.assignment.php

Then remember to delete the last ,

ContentLicense: CC BY-SA 4.0

Body:
Using the below code in an attempt to run a single query with exploded array variables:

 <?php
 $containers = $_POST['cntnum'];
 $containersArray = preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$containers)));
 $count = count($containersArray);

 for($i = 0; $i < $count; $i++)
 {
   $container = $containersArray[$i];
   $cntFixed = "'".$container."',";
 }

 $select = "SELECT container, date, pool FROM inventory WHERE container IN (".$ctnFixed.")";

 $query = mysqli_query($dbc, $select) or die(mysqli_error());

 ?>

When I pass $cntFixed into the query.  I don't get all of the variables that were in the array.  Instead, I only get the last of the variables with an ending comma, as shown when I print to the console here:

  "SELECT container, date, pool FROM inventory WHERE container IN ('variable3',)"

Of course, the ending comma will throw the query off, so I need to take that into consideration.

I cannot put the query into the for loop, because that runs the query the same amount of times as the array count.

What I need to do is run the query 1 time with all of the variables passed into the query.

The query should look like this when I print it to the console:

 "SELECT container, date, pool FROM inventory WHERE container IN ('variable1', 'variable2', 'variable3')"


问:
Array of Structs value lost in memory
So, I'm pretty new to C and ran across something a few hours ago that I thought was puzzling.

I'm basically working on a csv file parser in C. I've got the following struct for holding a single value from a csv file. (ex. "5.13" or "Test1").

```<code>struct CSV_DATA {
    enum { is_int, is_float, is_char } type;
    int ival;
    char cval[10];
    float fval;
};
</code>```

Inside main is the following (Note: lines 40 and 41 are the important ones):

```<code>int main()
{

   struct CSV_DATA csv_data[500][50];

   char buffer[1024] ;
   char *record,*line;

   int i = 0;
   int j = 0;

   FILE *fstream = fopen("iris.csv","r");

   if(fstream == NULL)
   {
      printf("\n file opening failed ");
      return -1 ;
   }

   while((line=fgets(buffer,sizeof(buffer),fstream))!=NULL)
   {
     record = strtok(line,",");
     printf("%s", record);
     while(record != NULL)
     {

        csv_data[i][j].type = is_char;
        for (int k=0; k < strlen(record); k++){
          csv_data[i][j].cval[k] = record[k];//record;
        }

        j++;

     record = strtok(NULL,",");
     printf("%s", record);

     }
     ++i;
   }

   return 0 ;
 }
</code>```

The point of this code is to read in values from a csv file and store each one of them inside one instance of CSV_DATA. I then store that value inside a 2d array to be able to access the data later.

Now, this actually stores values into memory. I know because I can see them with GDB, but the problem is that the data is Offset in memory from the actual index of the array.

The following command: x/200ub csv_data ...yeilds the following:

```<code>(gdb) x/200ub csv_data
0x7ffffff6b1f0: 2   0   0   0   0   0   0   0
0x7ffffff6b1f8: 53  46  49  0   0   0   0   0
0x7ffffff6b200: 0   0   0   0   0   0   0   0
0x7ffffff6b208: 2   0   0   0   0   0   0   0
0x7ffffff6b210: 51  46  53  0   0   0   0   0
0x7ffffff6b218: 0   0   0   0   0   0   0   0
</code>```

Similarly, x/200ub csv_data[0] yields the same thing...as expected.

However, x/200ub csv_data[1] is looking at the wrong index in memory for the values!! However, I can see them stored in memory, but the index of the array is pointed to the wrong memory location for 1..n. Any suggestions or ideas would be greatly appreciated!

答:
Inner loop index is only initialized once.  Move j index

Other ideas incorporated too

```<code>int main() {
  struct CSV_DATA csv_data[500][50];
  char buffer[1024];

  //  **FROM**
  //   int j = 0;
  size_t i = 0;

  FILE *fstream = fopen("iris.csv", "r");

  if (fstream == NULL) {
    printf("\n file opening failed ");
    return -1;
  }

  while (fgets(buffer, sizeof buffer, fstream)) {
    char *record = strtok(buffer, ",");

    // **TO**
    size_t j = 0;

    while (record) {
      printf("%s", record);
      csv_data[i][j].type = is_char;

      csv_data[i][j].cval[0] = `\0`;
      // strncat(csv_data[i][j].cval, record, sizeof csv_data[i][j].cval);
      strncat(csv_data[i][j].cval, record, sizeof csv_data[i][j].cval - 1);
      j++;

      record = strtok(NULL, ",");
    }
    ++i;
  }
  fclose(fstream);  // add
  return 0;
}
</code>```

[Edit] Corrected code

Title: Array of Structs value lost in memory

Body:
So, I'm pretty new to C and ran across something a few hours ago that I thought was puzzling.

I'm basically working on a csv file parser in C. I've got the following struct for holding a single value from a csv file. (ex. "5.13" or "Test1").

struct CSV_DATA {
    enum { is_int, is_float, is_char } type;
    int ival;
    char cval[10];
    float fval;
};

Inside main is the following (Note: lines 40 and 41 are the important ones):

int main()
{

   struct CSV_DATA csv_data[500][50];

   char buffer[1024] ;
   char *record,*line;

   int i = 0;
   int j = 0;

   FILE *fstream = fopen("iris.csv","r");

   if(fstream == NULL)
   {
      printf("\n file opening failed ");
      return -1 ;
   }

   while((line=fgets(buffer,sizeof(buffer),fstream))!=NULL)
   {
     record = strtok(line,",");
     printf("%s", record);
     while(record != NULL)
     {

        csv_data[i][j].type = is_char;
        for (int k=0; k < strlen(record); k++){
          csv_data[i][j].cval[k] = record[k];//record;
        }

        j++;

     record = strtok(NULL,",");
     printf("%s", record);

     }
     ++i;
   }

   return 0 ;
 }

The point of this code is to read in values from a csv file and store each one of them inside one instance of CSV_DATA. I then store that value inside a 2d array to be able to access the data later.

Now, this actually stores values into memory. I know because I can see them with GDB, but the problem is that the data is Offset in memory from the actual index of the array.

The following command: x/200ub csv_data ...yeilds the following:

(gdb) x/200ub csv_data
0x7ffffff6b1f0: 2   0   0   0   0   0   0   0
0x7ffffff6b1f8: 53  46  49  0   0   0   0   0
0x7ffffff6b200: 0   0   0   0   0   0   0   0
0x7ffffff6b208: 2   0   0   0   0   0   0   0
0x7ffffff6b210: 51  46  53  0   0   0   0   0
0x7ffffff6b218: 0   0   0   0   0   0   0   0

Similarly, x/200ub csv_data[0] yields the same thing...as expected.

However, x/200ub csv_data[1] is looking at the wrong index in memory for the values!! However, I can see them stored in memory, but the index of the array is pointed to the wrong memory location for 1..n. Any suggestions or ideas would be greatly appreciated!

Body:
Inner loop index is only initialized once.  Move j index

Other ideas incorporated too

int main() {
  struct CSV_DATA csv_data[500][50];
  char buffer[1024];

  //  **FROM**
  //   int j = 0;
  size_t i = 0;

  FILE *fstream = fopen("iris.csv", "r");

  if (fstream == NULL) {
    printf("\n file opening failed ");
    return -1;
  }

  while (fgets(buffer, sizeof buffer, fstream)) {
    char *record = strtok(buffer, ",");

    // **TO**
    size_t j = 0;

    while (record) {
      printf("%s", record);
      csv_data[i][j].type = is_char;

      csv_data[i][j].cval[0] = `\0`;
      // strncat(csv_data[i][j].cval, record, sizeof csv_data[i][j].cval);
      strncat(csv_data[i][j].cval, record, sizeof csv_data[i][j].cval - 1);
      j++;

      record = strtok(NULL, ",");
    }
    ++i;
  }
  fclose(fstream);  // add
  return 0;
}

[Edit] Corrected code


问:
webpack extract text plugin prints a lot
I am using the webpack extract text plugin to extract styles into a css file. It prints a lot of stuff like this:

Child extract-text-webpack-plugin:
          + 2 hidden modules

Child extract-text-webpack-plugin:
          + 7 hidden modules

Child extract-text-webpack-plugin:
          + 7 hidden modules

Child extract-text-webpack-plugin:
          + 2 hidden modules

Child extract-text-webpack-plugin:
          + 2 hidden modules

Child extract-text-webpack-plugin:
          + 4 hidden modules

Is there any way to surpress it via config? It's pretty useless and cramps the terminal window.

答:
The answer using stats suppresses output from all children, including everything if the config is an array.

Call webpack with --hide-modules at the command line instead.


问:
Can an ASP.NET WebAPI action parameter be excluded from Swashbuckle/Swagger UI?
My actual case is I've allowed dependency injection using parameter binding on API controllers implementing a custom parameter binding.

For example, a controller action may look as follows:

```<code>public async Task<IHttpActionResult> GetByIdAsync(Guid id, ICustomerFacade customerFacade)
</code>```

When I explore my API using Swagger UI generated by Swashbuckle, customerFacade is specified as an actual and required resource action parameter.

Do you know any way of excluding controller action parameters from generated Swagger UI?

Note: I know that a workaround could be injecting dependencies using constructor injection, but I still prefer to be able to both do constructor and regular method dependency injection.

答:
I'm not positive but I think you should be injecting the dependency into the controllers constructor and not the Get method.

So, your class would have:

```<code>private ICustomerFacade _customerFacade;

public MyController(ICustomerFacade customerFacade)
{
     _customerFacade = customerFacade;
}

public async Task<IHttpActionResult> GetByIdAsync(Guid id){
     return Ok(_customerFacade.getCustomer(id));
}
</code>```

Unless you want the client calling your api to be responsible for injecting the customerFacade...

Body:
My actual case is I've allowed dependency injection using parameter binding on API controllers implementing a custom parameter binding.

For example, a controller action may look as follows:

public async Task<IHttpActionResult> GetByIdAsync(Guid id, ICustomerFacade customerFacade)

When I explore my API using Swagger UI generated by Swashbuckle, customerFacade is specified as an actual and required resource action parameter.

Do you know any way of excluding controller action parameters from generated Swagger UI?

Note: I know that a workaround could be injecting dependencies using constructor injection, but I still prefer to be able to both do constructor and regular method dependency injection.

Body:
I'm not positive but I think you should be injecting the dependency into the controllers constructor and not the Get method.

So, your class would have:

private ICustomerFacade _customerFacade;

public MyController(ICustomerFacade customerFacade)
{
     _customerFacade = customerFacade;
}

public async Task<IHttpActionResult> GetByIdAsync(Guid id){
     return Ok(_customerFacade.getCustomer(id));
}

Unless you want the client calling your api to be responsible for injecting the customerFacade...


问:
Add to ArrayList from different WebForms
I have 2 web forms in webform1 I have 2 buttons (Add and Show_WebForm2) and a textbox. In WebForm1, when the user types in the names in the textbox and clicks add button the name is added to the ArrayList. When the user is done typing in the names in WebForm1 they open WebForms2. In WebForms2 there is also a textbox and an add button. When the user types in the names in this TextBox I want it to be added to the same ArrayList variable which I used in WebForm1. How can I achieve this?

```<code>    public ArrayList FullNameApplicantArray = new ArrayList();
    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text +")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/WebForm2.aspx");

    }
</code>```

```<code>    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }
</code>```

答:
You already have the solution in your code, just use session across different WebForms.

In the second WebForm page, in click event, just assign the session to the array,
add to the array, then save to the session.

```<code>protected void Button2_Click(object sender, EventArgs e)
{
    ArrayList FullNameApplicantArray2 = new ArrayList();
    FullNameApplicantArray2 = Session["ListOfApplicants"];
    FullNameApplicantArray2.Add("(" + TextBox1.Text + ")");
    Session["ListOfApplicants"] = FullNameApplicantArray2;

    foreach (var item in Session["ListOfApplicants"].ToString())
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
}
</code>```

Also in your Button1_click, you need to save the entire list instead of only the first element:

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    FullNameApplicantArray.Add("(" + TextBox1.Text +")");
    Session["ListOfApplicants"] = FullNameApplicantArray;

    foreach (var item in Session["ListOfApplicants"].ToString())
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
}
</code>```

Body:
I have 2 web forms in webform1 I have 2 buttons (Add and Show_WebForm2) and a textbox. In WebForm1, when the user types in the names in the textbox and clicks add button the name is added to the ArrayList. When the user is done typing in the names in WebForm1 they open WebForms2. In WebForms2 there is also a textbox and an add button. When the user types in the names in this TextBox I want it to be added to the same ArrayList variable which I used in WebForm1. How can I achieve this?

    public ArrayList FullNameApplicantArray = new ArrayList();
    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text +")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/WebForm2.aspx");

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

Body:
You already have the solution in your code, just use session across different WebForms.

In the second WebForm page, in click event, just assign the session to the array,
add to the array, then save to the session.

protected void Button2_Click(object sender, EventArgs e)
{
    ArrayList FullNameApplicantArray2 = new ArrayList();
    FullNameApplicantArray2 = Session["ListOfApplicants"];
    FullNameApplicantArray2.Add("(" + TextBox1.Text + ")");
    Session["ListOfApplicants"] = FullNameApplicantArray2;

    foreach (var item in Session["ListOfApplicants"].ToString())
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
}

Also in your Button1_click, you need to save the entire list instead of only the first element:

protected void Button1_Click(object sender, EventArgs e)
{
    FullNameApplicantArray.Add("(" + TextBox1.Text +")");
    Session["ListOfApplicants"] = FullNameApplicantArray;

    foreach (var item in Session["ListOfApplicants"].ToString())
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
}


问:
javascript function to round current time (from epoch) to nearest minute
I've been banging my head against the wall trying to get a JavaScript equivalent to this php snippet:

```<code><?php
$id  = 'uniqueID'
$now = round(time()/60);
$lock = md5($now . $id);
?>
</code>```

I've been trying variations on this:

```<code>var timeInMin = new Date().getTime() / 60000;
var timestamp = Math.round(timeInMin);
var key = md5(timestamp + 'uniqueID');
</code>```

utilizing an md5 script from here

I merely need lock and key to match. Seems simple to me. What am I doing wrong?

答:
As said before me, if time not matching it will not create the same hash. What I do in situations like that is to find way to pass the time from php to the client side so they can use the same exact time.

PHP side:

```<code><?php
    $id  = 'uniqueID';
    $now = round(time()/60);
    $lock = md5($now . $id);
    print $lock;
    setcookie("time",$now);
?>
</code>```

Client Side:

```<code><script type="text/javascript">
    var timestamp = getCookie("time");
    var key = md5(timestamp + 'uniqueID');
    console.log(key);
</script>
</code>```

Note that getCookie is a shortcut function

The following example is here to present the idea in a simple form. I would not use time as the name of the cookie nor give access to the vars (wrap in function). Uglify scripts goes a long way in cases like this.

Body:
I've been banging my head against the wall trying to get a JavaScript equivalent to this php snippet:

<?php
$id  = 'uniqueID'
$now = round(time()/60);
$lock = md5($now . $id);
?>

I've been trying variations on this:

var timeInMin = new Date().getTime() / 60000;
var timestamp = Math.round(timeInMin);
var key = md5(timestamp + 'uniqueID');

utilizing an md5 script from here

I merely need lock and key to match. Seems simple to me. What am I doing wrong?

Body:
As said before me, if time not matching it will not create the same hash. What I do in situations like that is to find way to pass the time from php to the client side so they can use the same exact time.

PHP side:

<?php
    $id  = 'uniqueID';
    $now = round(time()/60);
    $lock = md5($now . $id);
    print $lock;
    setcookie("time",$now);
?>

Client Side:

<script type="text/javascript">
    var timestamp = getCookie("time");
    var key = md5(timestamp + 'uniqueID');
    console.log(key);
</script>

Note that getCookie is a shortcut function

The following example is here to present the idea in a simple form. I would not use time as the name of the cookie nor give access to the vars (wrap in function). Uglify scripts goes a long way in cases like this.


问:
ASP.NET Core Find All Class Types In All Assemblies
I am trying to make a modular based .NET core app, and I need to find all classes of a specific type(s) across all assemblies. As each module will be built in it's own project.

But I can't see/find how to do that in ASP.NET Core? Any pointers would be appreciated.

答:
I probably found a way of achieving this,

```<code>var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}
</code>```

I am worried about the cost of the Assembly.Load part, but this will probably get my work done for now - as I only need the Fully Qualified Name of all the classes that implements ICloudProvider.

Body:
I probably found a way of achieving this,

var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}

I am worried about the cost of the Assembly.Load part, but this will probably get my work done for now - as I only need the Fully Qualified Name of all the classes that implements ICloudProvider.