问:
Is it possible to change the aws iot core rules dynamically?
I'm working on Iot enabled automatic machine industry which is using aws IoT core.
Each machine has it's own benchmark temperature level which varies and I
want to trigger an AWS SNS based on their benchmark temperature level .
Each of the machine publish the data to the same topic separated by
their ID.
The topic name looks like bellow

```<code> machine/+/data
</code>```

Where the + sign indicates the machine_id
I have my rules written like bellow.

```<code> select * from machine/+/data where temperature > 25
</code>```

which works for all the topics now the problem the temperature level is
not same for all the machines for example a machine with id = 1 may
have temperature level 30 another machine with id = 2 may have 28.

My question is that, is it possible to trigger SNS based on the machine temperature
using Rules or are their any other way to do this?

Thanks in advance for your reply.

答:
The IoT rule can be made dynamic by using the get_dynamodb, aws_lambda or get_thing_shadow functions in the WHERE clause.

From https://forums.aws.amazon.com/thread.jspa?messageID=932907&#932907

You have 3 ways to fetch data in AWS IoT Topic Rule. All can be used in the WHERE clause evaluation.

aws_lambda() function (https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-func-aws-lambda) which would return data that you need from your lambda in your Rule evaluation. Most useful for getting value from another service.

get_dynamodb() function (https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-sql-function-get-dynamodb) which lets you fetch data from your DynamoDB table. You can keep a per-thing threshold values in a table.

get_thing_shadow() function (https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-sql-function-get-thing-shadow) which lets you get data from your Thing Shadow documents. If you are already using a Thing Shadow, this could be easiest to keep per-thing threshold value.

As an example, the get_thing_shadow documentation has:

```<code>SELECT * from 'a/b'
WHERE
get_thing_shadow("MyThing","arn:aws:iam::123456789012:role/AllowsThingShadowAccess")
  .state.reported.alarm = 'ON'
</code>```

If your benchmark temperature levels were in the thing registry then a rule similar to this could be used:

```<code>SELECT * FROM machine/+/data
WHERE
temperature > get_thing_shadow(topic(2),"arn:aws:iam::123456789012:role/AllowsThingShadowAccess")
  .state.threshold
</code>```

Body:
I'm working on Iot enabled automatic machine industry which is using aws IoT core.
Each machine has it's own benchmark temperature level which varies and I
want to trigger an AWS SNS based on their benchmark temperature level .
Each of the machine publish the data to the same topic separated by
their ID.
The topic name looks like bellow

 machine/+/data

Where the + sign indicates the machine_id
I have my rules written like bellow.

 select * from machine/+/data where temperature > 25

which works for all the topics now the problem the temperature level is
not same for all the machines for example a machine with id = 1 may
have temperature level 30 another machine with id = 2 may have 28.

My question is that, is it possible to trigger SNS based on the machine temperature
using Rules or are their any other way to do this?

Thanks in advance for your reply.

Body:
The IoT rule can be made dynamic by using the get_dynamodb, aws_lambda or get_thing_shadow functions in the WHERE clause.

From https://forums.aws.amazon.com/thread.jspa?messageID=932907&#932907

You have 3 ways to fetch data in AWS IoT Topic Rule. All can be used in the WHERE clause evaluation.

aws_lambda() function (https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-func-aws-lambda) which would return data that you need from your lambda in your Rule evaluation. Most useful for getting value from another service.

get_dynamodb() function (https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-sql-function-get-dynamodb) which lets you fetch data from your DynamoDB table. You can keep a per-thing threshold values in a table.

get_thing_shadow() function (https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-sql-function-get-thing-shadow) which lets you get data from your Thing Shadow documents. If you are already using a Thing Shadow, this could be easiest to keep per-thing threshold value.

As an example, the get_thing_shadow documentation has:

SELECT * from 'a/b'
WHERE
get_thing_shadow("MyThing","arn:aws:iam::123456789012:role/AllowsThingShadowAccess")
  .state.reported.alarm = 'ON'

If your benchmark temperature levels were in the thing registry then a rule similar to this could be used:

SELECT * FROM machine/+/data
WHERE
temperature > get_thing_shadow(topic(2),"arn:aws:iam::123456789012:role/AllowsThingShadowAccess")
  .state.threshold


来源: stackexchange

问:
'urllib' on an infinite loop
For a while, i have been trying to use cloud9 to give me an extra hand on repetitive tasks on my job. However, the majority of those tasks have web scraping involved, and I am having a hard time using the urllib library.

It does not work even for simple codes. It keeps running forever, and I can't find the reasons for that. I will appreciate some tips...

```<code>from urllib.request import urlopen
import json
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = ('Enter - ')
html = urlopen(url, context=ctx).read()
str_data = open(html).read()
json_data = json.loads(str_data)

for entry in json_data:

name = entry[0];
    title = entry[1];
    print((name, title))
</code>```

答:
Without providing much debug information, one can only assume that you're probably timing out, since you're not providing the urlopen function with a timeout.

To avoid this, put a reasonable timeout to your urlopen function so that it doesn't run indefinitely.

ContentLicense: CC BY-SA 4.0

Title: 'urllib' on an infinite loop

Body:
For a while, i have been trying to use cloud9 to give me an extra hand on repetitive tasks on my job. However, the majority of those tasks have web scraping involved, and I am having a hard time using the urllib library.

It does not work even for simple codes. It keeps running forever, and I can't find the reasons for that. I will appreciate some tips...

from urllib.request import urlopen
import json
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = ('Enter - ')
html = urlopen(url, context=ctx).read()
str_data = open(html).read()
json_data = json.loads(str_data)

for entry in json_data:

name = entry[0];
    title = entry[1];
    print((name, title))


问:
Can't hide Bottom Sheet, Android
I'm having problems with my bottom-sheet because when I open the activity it is on, blocking the view

This happens, I think, because of the XML attribute declaring the bottom-sheet with 350dp of height:

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="?android:attr/windowBackground"
    android:clipToPadding="true"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
</code>```

The thing is, I can't change that value to 0dp because the next time when I try to open the bottom-sheet, there is no bottom-sheet, because the height is 0dp, so it won't show anything.
My question is, is there a way to declare the bottom-sheet off? (I've tried to setState to STATE_COLLAPSED but didn't work).
Bellow is the java code that interacts with the Bottom Sheet.
 JAVA:

```<code>View bottomSheet = findViewById( R.id.bottom_sheet );
        mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    //mBottomSheetBehavior.setPeekHeight(0);
                    //mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    //mBottomSheetBehavior.isHideable();
                }
            }

            @Override
            public void onSlide(View bottomSheet, float slideOffset) {

            }
        });
</code>```

答: When Collapsed set app:behavior_hideable="false"</p>

ContentLicense: CC BY-SA 3.0

Title: Can't hide Bottom Sheet, Android

Body:
I'm having problems with my bottom-sheet because when I open the activity it is on, blocking the view

This happens, I think, because of the XML attribute declaring the bottom-sheet with 350dp of height:

<android.support.v4.widget.NestedScrollView
    android:id="@+id/bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="?android:attr/windowBackground"
    android:clipToPadding="true"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

The thing is, I can't change that value to 0dp because the next time when I try to open the bottom-sheet, there is no bottom-sheet, because the height is 0dp, so it won't show anything.
My question is, is there a way to declare the bottom-sheet off? (I've tried to setState to STATE_COLLAPSED but didn't work).
Bellow is the java code that interacts with the Bottom Sheet.
 JAVA:

View bottomSheet = findViewById( R.id.bottom_sheet );
        mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    //mBottomSheetBehavior.setPeekHeight(0);
                    //mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    //mBottomSheetBehavior.isHideable();
                }
            }

            @Override
            public void onSlide(View bottomSheet, float slideOffset) {

            }
        });


问:
Group by segments then within each group split into unique batches - SQL Challenge
I have a table with duplicate email addresses. This is where contacts have a shared (duplicate) email address. This table has various segments and I want to group all records together for each segment, then within each segment split the records into unique batches, so that each batch doesn't have a duplicate email address in them. Therefore for each segment I need a query that would need to generate enough batches until there was no more duplicate email addresses.

There's circa 20,000 records and i need a way to generate an output that will give us each segement split into batches that only have unique email addresses.

答:
You can use row_number():

```<code>select row_number() over (partition by email order by email) as batchnum,
       t.*
from t;
</code>```

The first column is a batch number.  Rows with the same batch number are guaranteed to have unique emails.

Body:
You can use row_number():

select row_number() over (partition by email order by email) as batchnum,
       t.*
from t;

The first column is a batch number.  Rows with the same batch number are guaranteed to have unique emails.


问:
Authentication Recommendation
I have a Laravel website with a table 'users' that stores the role_id, and a table 'companies' that stores custom permalinks.
The default login routes are used for the users with the ADMIN role. I need to add other views and routes for the users with the CLIENT role.
So, when a user accesses the URL '/custom-company-permalink-from-db' and he is not logged in, he should be redirected to the URL '/custom-company-permalink-from-db/login'.

Here are my routes:

```<code>Route::middleware('web')->group(function() {
    Auth::routes(['register' => false]);

    Route::get('/', ['uses' => 'HomeController@index', 'as' => 'home']);
    Route::get('/{company}', ['uses' => 'HomeController@overview', 'as' => 'overview']);
});

Route::namespace('Admin')->prefix('admin')->name('admin.')->middleware(['auth', 'check.if.admin'])->group(function() {
    Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'AdminController@dashboard']);
});
</code>```

I am thinking about adding this to the routes:

```<code>Route::get('/{company?}/login','Frontend\Auth\LoginController@showLoginForm')->name('client.login');
</code>```

And then copying the app/Http/Controllers/Auth files to app/Http/Controllers/Frontend/Auth and making the necessary edits.

Is there another way of achieving this? What's the recommended way?

答:
Since you are separating users based on roles, you can use the same login and differentiate routes based on namespace. Inside auth group, create two groups, one for admin (existing) and one for clients. You are already using a middleware to check if user is admin. Similarly you can create a new middleware to check if user is a client. </p>

```<code> Route::middleware('auth')->group....
    Route::namspace..prefix..->middleware('check.if.admin')->group(...
    ) //end check if admin group
    Route::namespace('client')->prefix('client')->middleware('check.client')->group(...)
 )//end auth group
</code>```

Title: Authentication Recommendation

Body:
I have a Laravel website with a table 'users' that stores the role_id, and a table 'companies' that stores custom permalinks.
The default login routes are used for the users with the ADMIN role. I need to add other views and routes for the users with the CLIENT role.
So, when a user accesses the URL '/custom-company-permalink-from-db' and he is not logged in, he should be redirected to the URL '/custom-company-permalink-from-db/login'.

Here are my routes:

Route::middleware('web')->group(function() {
    Auth::routes(['register' => false]);

    Route::get('/', ['uses' => 'HomeController@index', 'as' => 'home']);
    Route::get('/{company}', ['uses' => 'HomeController@overview', 'as' => 'overview']);
});

Route::namespace('Admin')->prefix('admin')->name('admin.')->middleware(['auth', 'check.if.admin'])->group(function() {
    Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'AdminController@dashboard']);
});

I am thinking about adding this to the routes:

Route::get('/{company?}/login','Frontend\Auth\LoginController@showLoginForm')->name('client.login');

And then copying the app/Http/Controllers/Auth files to app/Http/Controllers/Frontend/Auth and making the necessary edits.

Is there another way of achieving this? What's the recommended way?

Body:
Since you are separating users based on roles, you can use the same login and differentiate routes based on namespace. Inside auth group, create two groups, one for admin (existing) and one for clients. You are already using a middleware to check if user is admin. Similarly you can create a new middleware to check if user is a client.

 Route::middleware('auth')->group....
    Route::namspace..prefix..->middleware('check.if.admin')->group(...
    ) //end check if admin group
    Route::namespace('client')->prefix('client')->middleware('check.client')->group(...)
 )//end auth group


问:
Gatling - Check if response body string key is certain value
I have a scenario in Gatling and I want to check if the response body value maps to an error string. The response is a 400:

```<code>{"error": "ERROR_1"}
</code>```

The check is failing with a compilation error:

```<code> http("Some Request")
  .put("/endpoint")
  .asJson
  .check(jsonPath("$.error") == "ERROR_1")
  .check(status.is(400))
</code>```

Also tried saving the error as a variable

```<code>.check(jsonPath("$.error").saveAs("error"))
.check("${error}" == "ERROR_1")
</code>```

And realised the .check("${error}".is("ERROR_1")) won't work either since .is only works for ints. The gatling docs don't explain expressions too much either https://gatling.io/docs/current/http/http_check#validating

Any ideas?

答:
Your statement that .is only works for ints is incorrect - and this is how you should construct this check.

Here's a working example with a passing check

```<code>def test : ScenarioBuilder = scenario("test")
.exec(
  http("test call")
    .post("http://httpbin.org/anything")
    .body(StringBody("""{"error": "ERROR_1"}"""))
    .check(jsonPath("$..error").is("ERROR_1"))
)
</code>```

You can't use == as a gatling check needs one or more HttpChecks and == returns a boolean.

Body:
I have a scenario in Gatling and I want to check if the response body value maps to an error string. The response is a 400:

{"error": "ERROR_1"}

The check is failing with a compilation error:

 http("Some Request")
  .put("/endpoint")
  .asJson
  .check(jsonPath("$.error") == "ERROR_1")
  .check(status.is(400))

Also tried saving the error as a variable

.check(jsonPath("$.error").saveAs("error"))
.check("${error}" == "ERROR_1")

And realised the .check("${error}".is("ERROR_1")) won't work either since .is only works for ints. The gatling docs don't explain expressions too much either https://gatling.io/docs/current/http/http_check#validating

Any ideas?

Body:
Your statement that .is only works for ints is incorrect - and this is how you should construct this check.

Here's a working example with a passing check

def test : ScenarioBuilder = scenario("test")
.exec(
  http("test call")
    .post("http://httpbin.org/anything")
    .body(StringBody("""{"error": "ERROR_1"}"""))
    .check(jsonPath("$..error").is("ERROR_1"))
)

You can't use == as a gatling check needs one or more HttpChecks and == returns a boolean.


问:
Use Terraform v0.12 to add an aws_s3_bucket_policy to a list of buckets
I would like to create a policy template and apply it to a list of buckets but I am having a problem with getting the current bucket's name into the policy. Terraform returns the error

```<code>"Error: Error putting S3 policy: MalformedPolicy: Policy has invalid resource"
</code>```

twice. Plan is working fine, the output for the policy looks good etc.

```<code>variable "s3_bucket_list"
  {
    type        = list(string)
    description = "List of buckets to secure"
    default     = ["bucket1","bucket2"]
   }
</code>```

```<code>resource "aws_s3_bucket" "qpp-secure-bucket" {
  count  = length(var.s3_bucket_list)
  bucket = var.s3_bucket_list[count.index]
  }

resource "aws_s3_bucket_policy" "minimum_s3_bucket_policy" {
  count  = length(var.s3_bucket_list)
  bucket = var.s3_bucket_list[count.index]

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyUnencryptedCommunication",
      "Action": "s3:*",
      "Effect": "Deny",
      "Resource": [
        "${aws_s3_bucket.bucket.arn}",
        "arn:aws:s3:::${var.s3_bucket_list[count.index]}/*"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      },
      "Principal": "*"
    }
  ]
}
POLICY

}
</code>```

答:
Correct policy is</p>

```<code>resource "aws_s3_bucket_policy" "secure-bucket" {
  count  = length(var.s3_bucket_list)
  bucket = var.s3_bucket_list[count.index]

  policy = <<POLICY {   "Version": "2012-10-17",   "Statement": [
    {
      "Sid": "DenyUnencryptedCommunication",
      "Action": "s3:*",
      "Effect": "Deny",
      "Resource": [
         "arn:aws:s3:::${var.s3_bucket_list[count.index]}",
         "arn:aws:s3:::${var.s3_bucket_list[count.index]}/*"
        ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      },
      "Principal": "*"
    }   ] } POLICY

}
</code>```

Body:
I would like to create a policy template and apply it to a list of buckets but I am having a problem with getting the current bucket's name into the policy. Terraform returns the error

"Error: Error putting S3 policy: MalformedPolicy: Policy has invalid resource"

twice. Plan is working fine, the output for the policy looks good etc.

variable "s3_bucket_list"
  {
    type        = list(string)
    description = "List of buckets to secure"
    default     = ["bucket1","bucket2"]
   }

resource "aws_s3_bucket" "qpp-secure-bucket" {
  count  = length(var.s3_bucket_list)
  bucket = var.s3_bucket_list[count.index]
  }

resource "aws_s3_bucket_policy" "minimum_s3_bucket_policy" {
  count  = length(var.s3_bucket_list)
  bucket = var.s3_bucket_list[count.index]

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyUnencryptedCommunication",
      "Action": "s3:*",
      "Effect": "Deny",
      "Resource": [
        "${aws_s3_bucket.bucket.arn}",
        "arn:aws:s3:::${var.s3_bucket_list[count.index]}/*"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      },
      "Principal": "*"
    }
  ]
}
POLICY

}

Body:
Correct policy is

resource "aws_s3_bucket_policy" "secure-bucket" {
  count  = length(var.s3_bucket_list)
  bucket = var.s3_bucket_list[count.index]

  policy = <<POLICY {   "Version": "2012-10-17",   "Statement": [
    {
      "Sid": "DenyUnencryptedCommunication",
      "Action": "s3:*",
      "Effect": "Deny",
      "Resource": [
         "arn:aws:s3:::${var.s3_bucket_list[count.index]}",
         "arn:aws:s3:::${var.s3_bucket_list[count.index]}/*"
        ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      },
      "Principal": "*"
    }   ] } POLICY

}


问:
With Python, how to update multiple Mysql records with a long list of tuples?
I have a Python list that contains hundreds of tuples, and I want to update hundreds of corresponding records in a Mysql table with the data in the tuples. This is what my list of tuples looks like (shortened here):

updated_dates = [(1, '1997-12-29'), (2, '1998-01-05'), (3, '1998-01-12'), (4, '1998-01-19'), (5, '1998-01-26'), (6, '1998-02-02'), (7, '1998-02-09'), (8, '1998-02-16')]

Here is my code in which I attempt to update the Mysql records where the first value in each tuple corresponds with the id of each row to update:

```<code>for id_, date_ in updated_dates:
      sql = "UPDATE table SET date = %s WHERE id = %s"
      db_cursor.executemany(sql, (date_, id_))
      db_connection.commit()
</code>```

The error I receive is:

```<code>for id_, date_ in updated_dates:
ValueError: too many values to unpack (expected 2)
</code>```

I am sorry to ask a bad question, but I have spent much time on this without resolution. How may I update all my Mysql records with the data from the tuples in my list?

Thank you so much for your feedback.

答:
Thanks to Vir for his feedback. After more search, trial, and error, cursor.executemany actually basically is a loop on its own, so a for loop doesn't work and is not needed at all.

I flipped the position of the key and value in the tuples, so the id was second in the tuple, and this works:

```<code>updated_dates = [('1997-12-29', 1), ('1998-01-05', 2), ('1998-01-12', 3), ('1998-01-19', 4), ...etc]

sql = "UPDATE table SET date = %s WHERE id = %s"
db_cursor.executemany(sql, updated_dates)
db_connection.commit()
</code>```

Body:
I have a Python list that contains hundreds of tuples, and I want to update hundreds of corresponding records in a Mysql table with the data in the tuples. This is what my list of tuples looks like (shortened here):

updated_dates = [(1, '1997-12-29'), (2, '1998-01-05'), (3, '1998-01-12'), (4, '1998-01-19'), (5, '1998-01-26'), (6, '1998-02-02'), (7, '1998-02-09'), (8, '1998-02-16')]

Here is my code in which I attempt to update the Mysql records where the first value in each tuple corresponds with the id of each row to update:

for id_, date_ in updated_dates:
      sql = "UPDATE table SET date = %s WHERE id = %s"
      db_cursor.executemany(sql, (date_, id_))
      db_connection.commit()

The error I receive is:

for id_, date_ in updated_dates:
ValueError: too many values to unpack (expected 2)

I am sorry to ask a bad question, but I have spent much time on this without resolution. How may I update all my Mysql records with the data from the tuples in my list?

Thank you so much for your feedback.

Body:
Thanks to Vir for his feedback. After more search, trial, and error, cursor.executemany actually basically is a loop on its own, so a for loop doesn't work and is not needed at all.

I flipped the position of the key and value in the tuples, so the id was second in the tuple, and this works:

updated_dates = [('1997-12-29', 1), ('1998-01-05', 2), ('1998-01-12', 3), ('1998-01-19', 4), ...etc]

sql = "UPDATE table SET date = %s WHERE id = %s"
db_cursor.executemany(sql, updated_dates)
db_connection.commit()


问:
Adjust Height and Width of Legend Glyphs Generated by key_glyph ggplot
I was thrilled to discover that I can change the glyph used in the legend by adding key_glyph = draw_key_rect to my geom layer. I want to make the legend wider and shorter to resemble the legend in this map by Timo Grossenbacher:

I've tried adjusting scale_fill_manual(guide = guide_legend(keyheight = unit(0.01, units = "mm") , keywidth = unit(40, units = "mm"))) which changes the dimensions of the legend, but only seems to work when I make the glyphs bigger. I can't seem to make the keyheight any smaller.

Is there a better method of adjusting the legend glyphs' dimensions?

Simplified code here:

```<code>df <- data_frame(x_value = c(1:10),
                 y_value = c(rev(1:10)),
                 value = c("a","a","a","a","b","b","b","b","c","c"))
library(ggplot2)

ggplot(data = df) +
  geom_point(aes(x_value, y_value, fill = value),
             shape = 21,
             size = 9,
             key_glyph = draw_key_rect) +
  theme(legend.justification = c(0,0), # set which corner of legend legen.position references
        legend.position = c(0.05, 0.04)) +
  scale_fill_manual(values = c("red", "green", "blue"),
                    guide = guide_legend(direction = "horizontal",
                                         keyheight = unit(0.01, units = "mm"),
                                         keywidth = unit(40, units = "mm"),
                                         title.position = 'top',
                                         label.position = "bottom"))
</code>```

答:
You could create a fake legend. Or here's another mildly hacky solution.

The problem seems to be the size argument in geom_point, so you could make a fake aesthetic, in particular using lines, e.g. like this:

draw transparent lines (geom_line(alpha = 0))

make a color legend for geom_line with the same colors as your fill.

set the alpha to 1 for your color legend (override.aes)

remove the fill legend.

control the legend height in theme

library(ggplot2)

df <- data.frame(x_value = c(1:10),
                 y_value = c(rev(1:10)),
                 value = c("a","a","a","a","b","b","b","b","c","c"))

ggplot(data = df) +
  geom_point(aes(x_value, y_value, fill = value), shape = 21, size = 7,
             show.legend = FALSE) + # remove fill legend
  geom_line(aes(x_value, y_value, color = value),
            alpha = 0, #invisible line. If your data is big, you could create a very small data frame for that
            key_glyph = draw_key_rect) +
  theme(legend.justification = c(0,0),
        legend.position = c(0.05, 0.04),
        legend.key.height = unit(0.1, 'in')) + # control height
  scale_fill_manual(values = c("red", "green", "blue")) +
  scale_color_manual(values = c("red", "green", "blue")) +
  guides(color = guide_legend(override.aes = list(alpha = 1), # make line visible in legend
                              direction = "horizontal",
                              keywidth = unit(20, units = "mm"),
                              title.position = 'top',
                              label.position = "bottom"))
```

Created on 2020-02-20 by the reprex package (v0.3.0)

Another option is to remove your key_glyph argument and control the glyph height with the size argument in geom_line

Body:
I was thrilled to discover that I can change the glyph used in the legend by adding key_glyph = draw_key_rect to my geom layer. I want to make the legend wider and shorter to resemble the legend in this map by Timo Grossenbacher:

I've tried adjusting scale_fill_manual(guide = guide_legend(keyheight = unit(0.01, units = "mm") , keywidth = unit(40, units = "mm"))) which changes the dimensions of the legend, but only seems to work when I make the glyphs bigger. I can't seem to make the keyheight any smaller.

Is there a better method of adjusting the legend glyphs' dimensions?

Simplified code here:

df <- data_frame(x_value = c(1:10),
                 y_value = c(rev(1:10)),
                 value = c("a","a","a","a","b","b","b","b","c","c"))
library(ggplot2)

ggplot(data = df) +
  geom_point(aes(x_value, y_value, fill = value),
             shape = 21,
             size = 9,
             key_glyph = draw_key_rect) +
  theme(legend.justification = c(0,0), # set which corner of legend legen.position references
        legend.position = c(0.05, 0.04)) +
  scale_fill_manual(values = c("red", "green", "blue"),
                    guide = guide_legend(direction = "horizontal",
                                         keyheight = unit(0.01, units = "mm"),
                                         keywidth = unit(40, units = "mm"),
                                         title.position = 'top',
                                         label.position = "bottom"))

Body:
You could create a fake legend. Or here's another mildly hacky solution.

The problem seems to be the size argument in geom_point, so you could make a fake aesthetic, in particular using lines, e.g. like this:

draw transparent lines (geom_line(alpha = 0))

make a color legend for geom_line with the same colors as your fill.

set the alpha to 1 for your color legend (override.aes)

remove the fill legend.

control the legend height in theme

library(ggplot2)

df <- data.frame(x_value = c(1:10),
                 y_value = c(rev(1:10)),
                 value = c("a","a","a","a","b","b","b","b","c","c"))

ggplot(data = df) +
  geom_point(aes(x_value, y_value, fill = value), shape = 21, size = 7,
             show.legend = FALSE) + # remove fill legend
  geom_line(aes(x_value, y_value, color = value),
            alpha = 0, #invisible line. If your data is big, you could create a very small data frame for that
            key_glyph = draw_key_rect) +
  theme(legend.justification = c(0,0),
        legend.position = c(0.05, 0.04),
        legend.key.height = unit(0.1, 'in')) + # control height
  scale_fill_manual(values = c("red", "green", "blue")) +
  scale_color_manual(values = c("red", "green", "blue")) +
  guides(color = guide_legend(override.aes = list(alpha = 1), # make line visible in legend
                              direction = "horizontal",
                              keywidth = unit(20, units = "mm"),
                              title.position = 'top',
                              label.position = "bottom"))

Created on 2020-02-20 by the reprex package (v0.3.0)

Another option is to remove your key_glyph argument and control the glyph height with the size argument in geom_line


问:
IOT Hub connection string - Azure Digital Twin
I am doing some POC on Azure Digital Twin. So i am using some DT samples available on GitHub by azure. But those samples require IOT Hub connection string to enter. But i am not able to find the IOT hub connection string any where in Azure Digital Twin.

for example, see this following line:

IoT Hub connection string has to be set to system environment variable IOT_HUB_CONNECTION_STRING

How can i get this connection string, i can have device connection string but i can not have iot hub connection string.

I know Azure DT has its underline IOT Hub and currently developers can not access it. I want to ask is there any way we can get that ?

答:
Azure Digital Twins in preview only supports an IoT Hub created through the Digital Twins API at the root of the spatial graph. This IoT Hub instance has no management API and will not appear in any management tools (such as the Azure Portal). All interaction is via the API.

The following answer indicates that this limitation will be addressed upon GA:

https://stackoverflow.com/a/59151340/12929015


问:
Local variable is not defined within the function, but it is defined outside and above it
I havent ran into this before, if i take the code out of triangle() and put it under the while loop everything works great. if I add triangle(input_argument) it then runs but never exits the while loop even if you type a string.

...

def main():

```<code># Defining initial conditions.
input_argument = input("Enter a number or done: ")
triangle_list = []

def triangle():
    input_argument = int(input_argument)
    triangle_number = (input_argument*(input_argument+1)//2)
    triangle_list.append(triangle_number)
    print("Your number of", input_argument, "has a triangle number of",
          str(triangle_number) + ".")
    input_argument = input("Enter a new number or done: ")

# Test function for input between int or anything else.
def num_test():
    try:
        int(input_argument)
        return True
    except ValueError:
        return False

while num_test() is True:
    triangle()
    num_test()

print(triangle_list)
</code>```

main()
...

EDIT:

```<code>def num_test(input_argument):
    try:
        int(input_argument)
        return True
    except ValueError:
        return False

def triangle(input_argument, triangle_list):
    input_argument = int(input_argument)
    triangle_number = (input_argument*(input_argument+1)//2)
    triangle_list.append(triangle_number)
    print("Your number of", input_argument, "has a triangle number of",
            str(triangle_number) + ".")
    input_argument = input("Enter a new number or done: ")
    return

def main():

    input_argument = input("Enter a number or done: ")
    triangle_list = []

    while num_test(input_argument) is True:
        triangle(input_argument, triangle_list)
        num_test(input_argument)

    print(triangle_list)
main()
</code>```

答:
There's a bunch of elementary mistakes here, so let's run through a fixed version instead:

def get_input():
    try:
        value = input('Enter a number or done:')
        return int(value)
    except ValueError:
        return False

def triangle(input, list):
    triangle_number = (input*(input+1)//2)
    list.append(triangle_number)
    print(f"Your number of {input} has a triangle number of {str(triangle_number)}.")

def main():
    triangle_list = []

    while True:
        value = get_input()
        if value is False:
            break
        triangle(value, triangle_list)

    print(triangle_list)

main()
```

Let's start with main, which is conceptually really simple:

we set up a list,

then we fill it,

then we print it.

How do we fill it? We loop our input aggregation:

get a value from the user. That'll either be a number, or False

if it's False, immediately stop looping.

if it's not, call our triangle function, with the current value, and the list of previous values

How do we get a value from the user? We use input(), and then try to return the int-cast version of that input. If that fails, we know the input was number a number, but otherwise we just return a number: exactly what we needed.

What does our triangle function do? It takes the current value and list of previous values, calculates some number, adds the current value to the list of previous values, prints, and exits.

Also not the Python 3 version of formatted strings: don't use string concatenation if you want a string with values-from-variables (or even values-from-other-code-calls). Use formatted strings, they're great.

Body:
I havent ran into this before, if i take the code out of triangle() and put it under the while loop everything works great. if I add triangle(input_argument) it then runs but never exits the while loop even if you type a string.

...

def main():

# Defining initial conditions.
input_argument = input("Enter a number or done: ")
triangle_list = []

def triangle():
    input_argument = int(input_argument)
    triangle_number = (input_argument*(input_argument+1)//2)
    triangle_list.append(triangle_number)
    print("Your number of", input_argument, "has a triangle number of",
          str(triangle_number) + ".")
    input_argument = input("Enter a new number or done: ")

# Test function for input between int or anything else.
def num_test():
    try:
        int(input_argument)
        return True
    except ValueError:
        return False

while num_test() is True:
    triangle()
    num_test()

print(triangle_list)

main()
...

EDIT:

def num_test(input_argument):
    try:
        int(input_argument)
        return True
    except ValueError:
        return False

def triangle(input_argument, triangle_list):
    input_argument = int(input_argument)
    triangle_number = (input_argument*(input_argument+1)//2)
    triangle_list.append(triangle_number)
    print("Your number of", input_argument, "has a triangle number of",
            str(triangle_number) + ".")
    input_argument = input("Enter a new number or done: ")
    return

def main():

    input_argument = input("Enter a number or done: ")
    triangle_list = []

    while num_test(input_argument) is True:
        triangle(input_argument, triangle_list)
        num_test(input_argument)

    print(triangle_list)
main()

Body:
There's a bunch of elementary mistakes here, so let's run through a fixed version instead:

def get_input():
    try:
        value = input('Enter a number or done:')
        return int(value)
    except ValueError:
        return False

def triangle(input, list):
    triangle_number = (input*(input+1)//2)
    list.append(triangle_number)
    print(f"Your number of {input} has a triangle number of {str(triangle_number)}.")

def main():
    triangle_list = []

    while True:
        value = get_input()
        if value is False:
            break
        triangle(value, triangle_list)

    print(triangle_list)

main()

Let's start with main, which is conceptually really simple:

we set up a list,

then we fill it,

then we print it.

How do we fill it? We loop our input aggregation:

get a value from the user. That'll either be a number, or False

if it's False, immediately stop looping.

if it's not, call our triangle function, with the current value, and the list of previous values

How do we get a value from the user? We use input(), and then try to return the int-cast version of that input. If that fails, we know the input was number a number, but otherwise we just return a number: exactly what we needed.

What does our triangle function do? It takes the current value and list of previous values, calculates some number, adds the current value to the list of previous values, prints, and exits.

Also not the Python 3 version of formatted strings: don't use string concatenation if you want a string with values-from-variables (or even values-from-other-code-calls). Use formatted strings, they're great.


问:
dyld: Library not loaded. Reason : no suitable image found
I've looked at a bunch of answers here and none have fixed my issue.

I have an Xcode workspace with a custom framework and an iOS app project.  The project has been working fine until this morning, now it builds but immediately crashes:

```<code>dyld: Library not loaded: @rpath/ONCKit.framework/ONCKit
  Referenced from: /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/atero_t
  Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit: mmap() error 1 at address=0x100118000, size=0x000B8000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit
    /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit: mmap() error 1 at address=0x100280000, size=0x000B8000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit
</code>```

I've been experimenting with build settings all day and I'm just totally lost.

答:
Well, in my case, I'm using cocoapods, and from the pod files, change:

```<code>target 'CoreMotionExample' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!

# Pods for CoreMotionExample
pod 'Firebase/Analytics'
</code>```

to

```<code>target 'CoreMotionExample' do
# Comment the next line if you don't want to use dynamic frameworks
# use_frameworks!

# Pods for CoreMotionExample
pod 'Firebase/Analytics'
</code>```

Then things begin to work... I don't know why

Body:
I've looked at a bunch of answers here and none have fixed my issue.

I have an Xcode workspace with a custom framework and an iOS app project.  The project has been working fine until this morning, now it builds but immediately crashes:

dyld: Library not loaded: @rpath/ONCKit.framework/ONCKit
  Referenced from: /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/atero_t
  Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit: mmap() error 1 at address=0x100118000, size=0x000B8000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit
    /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit: mmap() error 1 at address=0x100280000, size=0x000B8000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit

I've been experimenting with build settings all day and I'm just totally lost.

Body:
Well, in my case, I'm using cocoapods, and from the pod files, change:

target 'CoreMotionExample' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!

# Pods for CoreMotionExample
pod 'Firebase/Analytics'

to

target 'CoreMotionExample' do
# Comment the next line if you don't want to use dynamic frameworks
# use_frameworks!

# Pods for CoreMotionExample
pod 'Firebase/Analytics'

Then things begin to work... I don't know why


问:
bootstrap buttons coming out too small
hey guys i'm a newbie to web development and i have this little problem with bootstrap that i couldn't solve, it's two buttons that i put in the end of the page and they come out so small with the value attribute not showing, if anyone could help it'd be awesome

CODE

```<code><body>
  <h1 id="title">Fiche recapitulatif</h1>
  <div class="container">
    <div class="row">
      <p ><strong>Vous êtes:</strong> <?php echo $_SESSION['nom'].' '.$_SESSION['prenom']; ?></p>
    </div>
    <div class="row">
      <p ><strong>Vous avez:</strong> <?php echo $_SESSION['age']; ?></p>
    </div>
    <div class="row">
      <p ><strong>Votre num de telephone:</strong> <?php echo $_SESSION['tel']; ?></p>
    </div>
    <div class="row">
      <p ><strong>Votre email:</strong> <?php echo $_SESSION['email']; ?></p>
    </div>
    <div class="row">
      <p ><strong>Vous êtes en:</strong> <?php echo $_SESSION['fil'];
      if ($_SESSION['année']=='1ére') {
        echo "1";
      }elseif ($_SESSION['année']=='2éme') {
        echo "2";
      }elseif ($_SESSION['année']=='3éme') {
        echo "3";
      }
      ?></p>
    </div>
    <div class="row">
      <p ><strong>Vous suivez cette année:</strong>   <?php
      echo '<ol>';
      foreach ($_SESSION['module'] as $element) {
        echo '<li>'.$element.'</li>';
      }
      echo "</ol>";
      ?></p>
    </div>
    <div class="row">
      <p ><strong>Vous avez réalisé</strong> <?php echo $_SESSION['projets']; ?> projets cette année.</p>
    </div>
    <form action="" method="post">
      <button class="btn btn-primary" value="Modifier">
      <button class="btn btn-primary" type="submit" name="val" value="Valider">
    </form>
</div>
</body>
</code>```

OUTPUT

答: You just have to close the button tags (as per my comment). </p>

Title: bootstrap buttons coming out too small

Body:
hey guys i'm a newbie to web development and i have this little problem with bootstrap that i couldn't solve, it's two buttons that i put in the end of the page and they come out so small with the value attribute not showing, if anyone could help it'd be awesome

CODE

Fiche recapitulatif

Vous êtes: <?php echo $_SESSION['nom'].' '.$_SESSION['prenom']; ?>

Vous avez: <?php echo $_SESSION['age']; ?>

Votre num de telephone: <?php echo $_SESSION['tel']; ?>

Votre email: <?php echo $_SESSION['email']; ?>

Vous êtes en: <?php echo $_SESSION['fil'];
      if ($_SESSION['année']=='1ére') {
        echo "1";
      }elseif ($_SESSION['année']=='2éme') {
        echo "2";
      }elseif ($_SESSION['année']=='3éme') {
        echo "3";
      }
      ?>

Vous suivez cette année:   <?php
      echo '
';
      foreach ($_SESSION['module'] as $element) {
        echo '
'.$element.'
';
      }
      echo "
";
      ?>

Vous avez réalisé <?php echo $_SESSION['projets']; ?> projets cette année.

    <form action="" method="post">
      <button class="btn btn-primary" value="Modifier">
      <button class="btn btn-primary" type="submit" name="val" value="Valider">
    </form>

OUTPUT


问:
Use Disposable objects inside Task
I'm developing a Web Application for process a large amount of data and create a .csv file with those items.

So far, so good, but, it occored to me that it's not really fast this proccess, so I decide to make all those things in Task (Threading).

Like This:

```<code>_ = Task.Run(() => {
    try
    {
        LetsGoCrazy(model);
    }
    catch (Exception ex)
    {
        SaveLog(model, "Error dumbass", ex);
    }
});
</code>```

My question is that, how can I update my database (Entity Framework Core) inside a Task Method?

Because, it shows me this Exception:

System.ObjectDisposedException: 'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

I believe that it must have another way to accomplish that without recreating the Entity Framework Context inside the Task.

答:
Yours is a fire-and-forget Task that other parts of your code knows nothing about.  This means that the rest of the app continues on without waiting, releasing resources it thinks aren't being used or possibly exiting.  This can happen quite easily in a console app if you aren't careful.  For web you may find the controller goes out of scope and any resources along with it.  By the looks of the error it appears to be the case.

You simply need to await the task returned from Task.Run().

```<code>try
{
   await Task.Run(() => LetsGoCrazy(model));
}
catch (SomeException ex)
{
   // ...
}
</code>```

OP:

So far, so good, but, it occored to me that it's not really fast this proccess, so I decide to make all those things in Task (Threading).

Without seeing your code, simply placing it in a child task isn't necessarily going to make it run faster.

Dependency Injection Best Practices

You should avoid injecting I/O resources such as explicit database connections; WCF client proxies; or file streams into client code.  This is because should the connection fault, the client (say a MVC Controller) has no way to re-create it.

Instead you should inject a provider object that client's invoke when a connection is required.  Like everything else DI-related, object creation is still encapsulated by the DI system but it allows for dynamic object creation and recreation should a fault occur.

In your case if your LetsGoCrazy takes a long time (say > 5 mins) you might need to recreate the DB connection because of idle timeout.

Title: Use Disposable objects inside Task

Body:
I'm developing a Web Application for process a large amount of data and create a .csv file with those items.

So far, so good, but, it occored to me that it's not really fast this proccess, so I decide to make all those things in Task (Threading).

Like This:

_ = Task.Run(() => {
    try
    {
        LetsGoCrazy(model);
    }
    catch (Exception ex)
    {
        SaveLog(model, "Error dumbass", ex);
    }
});

My question is that, how can I update my database (Entity Framework Core) inside a Task Method?

Because, it shows me this Exception:

System.ObjectDisposedException: 'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

I believe that it must have another way to accomplish that without recreating the Entity Framework Context inside the Task.

Body:
Yours is a fire-and-forget Task that other parts of your code knows nothing about.  This means that the rest of the app continues on without waiting, releasing resources it thinks aren't being used or possibly exiting.  This can happen quite easily in a console app if you aren't careful.  For web you may find the controller goes out of scope and any resources along with it.  By the looks of the error it appears to be the case.

You simply need to await the task returned from Task.Run().

try
{
   await Task.Run(() => LetsGoCrazy(model));
}
catch (SomeException ex)
{
   // ...
}

OP:

So far, so good, but, it occored to me that it's not really fast this proccess, so I decide to make all those things in Task (Threading).

Without seeing your code, simply placing it in a child task isn't necessarily going to make it run faster.

Dependency Injection Best Practices

You should avoid injecting I/O resources such as explicit database connections; WCF client proxies; or file streams into client code.  This is because should the connection fault, the client (say a MVC Controller) has no way to re-create it.

Instead you should inject a provider object that client's invoke when a connection is required.  Like everything else DI-related, object creation is still encapsulated by the DI system but it allows for dynamic object creation and recreation should a fault occur.

In your case if your LetsGoCrazy takes a long time (say > 5 mins) you might need to recreate the DB connection because of idle timeout.


问:
String Substitution Using Variables in a FOR loop Batch Syntax
I am trying to use string substitution to truncate a list of full file paths down to relative paths in an existing text file. In addition there is some basic automated renaming. The renaming works as intended but the string substitution I cannot get to work. All the documentation I could find describing string substitution used standalone strings, not strings stored in variables. So I do not know and cannot figure out the proper syntax. I have also read similar questions asked here and attempted those solutions to no avail.

Everything in my script works as intended except for this line:
SET %%I=%%%I:%Temp_Dir%=%

It does not change %%I at all. The input to the FOR loop %List% is a text file that looks like this:

```<code>C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\codesegment.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\graphic.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\helper.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\main.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\game.out
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out
</code>```

The final output I get right now is identical to the above list.
The desired output should look like this:

```<code>\out\bin\codesegment.o
\out\bin\graphic.o
\out\bin\helper.o
\out\bin\main.o
\out\bin\game.out
\out\bin
\out
</code>```

I know the syntax is supposed to be:

```<code>SET string = C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\codesegment.o
SET string = %string:C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working =%
</code>```

As I said though, I cannot get it to work using variables in a FOR loop. I am also attempting this method of string substitution because the path of %Temp_Dir% is always at the start of every line and is always found in each line once.

Here is the whole script for reference. I would prefer a one line solution like the one I was attempting. I am aware longer solutions are available but due to reasons beyond my control the one-line string substitution is required.

```<code>@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET Proj_Dir="C:\Users\UserName\Desktop\Project"
SET Temp_Dir=%temp%\Batch_Renaming_Temp\Working
SET Counter=1
SET List="%temp%\Batch_Renaming_Temp\LFN_LIST.TMP"
SET List_Final="%temp%\Batch_Renaming_Temp\LFN_LIST.TXT"

ROBOCOPY /E /MIR %Proj_Dir% "%Temp_Dir%" > NUL
CD "%Temp_Dir%"
DIR /A-D /O:N /B /S > %List%
DIR /AD /O:N /B /S | SORT /R >> %List%
TYPE NUL > %List_Final%

FOR /F "usebackq tokens=* delims=" %%I IN (%List%) DO (
    REN "%%I" !Counter!
    SET /A !Counter+=1
    SET %%I=%%%I:%Temp_Dir%=%
    ECHO %%I >> %List_Final%
)
</code>```

答:
Like @Squashman pointed out in the comments, you cannot "set" a FOR variable.

If your variable depends on other variables indirectly, you need to use CALL SET or delayed expansion.

The easiest solution so far:

```<code>(for /F "usebackq tokens=8* delims=\" %%x in (%List%) do echo \%%y) > %List_Final%
</code>```

It uses \ as a delimiter and pass the 8+th arguments to %%y, and redirects all output to %List_Final%

Tested on a Windows 10 laptop, works perfectly.

Body:
I am trying to use string substitution to truncate a list of full file paths down to relative paths in an existing text file. In addition there is some basic automated renaming. The renaming works as intended but the string substitution I cannot get to work. All the documentation I could find describing string substitution used standalone strings, not strings stored in variables. So I do not know and cannot figure out the proper syntax. I have also read similar questions asked here and attempted those solutions to no avail.

Everything in my script works as intended except for this line:
SET %%I=%%%I:%Temp_Dir%=%

It does not change %%I at all. The input to the FOR loop %List% is a text file that looks like this:

C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\codesegment.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\graphic.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\helper.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\main.o
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\game.out
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin
C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out

The final output I get right now is identical to the above list.
The desired output should look like this:

\out\bin\codesegment.o
\out\bin\graphic.o
\out\bin\helper.o
\out\bin\main.o
\out\bin\game.out
\out\bin
\out

I know the syntax is supposed to be:

SET string = C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working\out\bin\codesegment.o
SET string = %string:C:\Users\UserName\AppData\Local\Temp\Batch_Renaming_Temp\Working =%

As I said though, I cannot get it to work using variables in a FOR loop. I am also attempting this method of string substitution because the path of %Temp_Dir% is always at the start of every line and is always found in each line once.

Here is the whole script for reference. I would prefer a one line solution like the one I was attempting. I am aware longer solutions are available but due to reasons beyond my control the one-line string substitution is required.

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET Proj_Dir="C:\Users\UserName\Desktop\Project"
SET Temp_Dir=%temp%\Batch_Renaming_Temp\Working
SET Counter=1
SET List="%temp%\Batch_Renaming_Temp\LFN_LIST.TMP"
SET List_Final="%temp%\Batch_Renaming_Temp\LFN_LIST.TXT"

ROBOCOPY /E /MIR %Proj_Dir% "%Temp_Dir%" > NUL
CD "%Temp_Dir%"
DIR /A-D /O:N /B /S > %List%
DIR /AD /O:N /B /S | SORT /R >> %List%
TYPE NUL > %List_Final%

FOR /F "usebackq tokens=* delims=" %%I IN (%List%) DO (
    REN "%%I" !Counter!
    SET /A !Counter+=1
    SET %%I=%%%I:%Temp_Dir%=%
    ECHO %%I >> %List_Final%
)

Body:
Like @Squashman pointed out in the comments, you cannot "set" a FOR variable.

If your variable depends on other variables indirectly, you need to use CALL SET or delayed expansion.

The easiest solution so far:

(for /F "usebackq tokens=8* delims=\" %%x in (%List%) do echo \%%y) > %List_Final%

It uses \ as a delimiter and pass the 8+th arguments to %%y, and redirects all output to %List_Final%

Tested on a Windows 10 laptop, works perfectly.


问:
What's the preferred way to create a jQuery object with attributes?
When creating jQuery objects I've used the following syntax lately, as described here:

```<code>var $el = $('<div/>', {
   class: 'class-1 class-2'
});
</code>```

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

答:
Make the attribute name a string:

```<code>var $el = $('<div/>', {
    'class': 'class-1 class-2'
});
</code>```

JSFiddle Example

Body:
When creating jQuery objects I've used the following syntax lately, as described here:

var $el = $('
', {
   class: 'class-1 class-2'
});

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

Body:
Make the attribute name a string:

var $el = $('<div/>', {
    'class': 'class-1 class-2'
});

JSFiddle Example


问:
Why does template substitution fail on a constructor unless I add brackets?
I am trying to understand why substitution fails on the following snippet unless brackets are added:

template<typename T>
struct A {};

template<typename T>
struct B {
    B(A<T>);
};

template<typename T>
void example(A<T>, B<T>);

struct C {};

struct D {
    D(C);
};

void example2(C, D);

int main(int argc, char *argv[]) {
    example(A<int>{}, A<int>{}); // error
    example(A<int>{}, {A<int>{}}); // ok

    example2(C{}, C{}); // ok
    example2(C{}, {C{}}); // ok

    return 0;
}
```

See this example: https://godbolt.org/z/XPqHww

For example2 I am able to implicitly pass the C{} to the constructor of D without any error. For example I am not allowed to implicitly pass the A<int>{} until I add brackets.

What defines this behaviour?

答:
example is a function template and the function parameters depend on the template parameter. Therefore and since you did not specify any template arguments explicitly in the call example(A<int>{}, A<int>{});, when you call this function, template argument deduction is performed to figure out what type T should be for the call.

With a few exceptions template argument deduction requires that a T can be found such that the type of the argument in the function call matches the type in the function parameter exactly.

The issue with your call is that A<int> does clearly not match  B<T> exactly for any T (and none of the exceptions apply either), so the call will fail.

This behavior is necessary, because the compiler would otherwise need to test all possible types T to check whether the function can be called. That would be computationally infeasible or impossible.

In the call example2(C{}, C{}); no templates are involved, so no template argument deduction is performed. Because the compiler doesn't need to figure out the target type in the parameter anymore, it becomes feasible to consider implicit conversions from the known argument type to the known parameter type. One such implicit conversion is the construction of D from C via the non-explicit constructor D(C);. So the call succeeds with that conversion.

example2(C{}, {C{}}); does effectively the same.

The question then is why example(A<int>{}, {A<int>{}}); works. This is because of a specific rule that can be found e.g. in [temp.deduct.type]/5.6 of the C++17 standard (draft N4659). It says that a function argument/parameter pair for which the argument is an initializer list (i.e. {A<int>{}}) and the parameter is not a specialization of std::initializer_list or an array type (it is neither here), the function parameter is a non-deduced context.

Non-deduced context means that the function argument/parameter pair will not be used during template argument deduction to figure out the type of T. This means its type does not need to match exactly. Instead, if template argument deduction otherwise succeeds, the resulting T will simply be substituted into the non-deduced context and from there implicit conversions will be considered as before. B<T> can be constructed from {A<int>} if T = int because of the non-explicit constructor B(A<T>);.

Now the question is whether template argument deduction will succeed and deduce T = int. It can only succeed if a T can be deduced from another function parameter. And indeed there is still the first parameter, for which the types match exactly: A<int>/A<T> matches for T = int and because this function argument doesn't use an initializer list, it is a context from which T will be deduced.

So indeed for example(A<int>{}, {A<int>{}}); deduction from the first argument will yield T = int and substitution into the second parameter B<T> makes the initialization/conversion B<T>{A<int>{}} succeed, so that the call is viable.

If you were to use initializer lists for both parameters as in example({A<int>{}}, {A<int>{}});, both argument/parameter pairs become non-deduced context and there wouldn't be anything left to deduce T from and so the call would fail for failure to deduce T.

You can make all calls work by specifying T explicitly, so that template argument deduction becomes unnecessary, e.g.:

```<code>example<int>(A<int>{}, A<int>{});
</code>```

Body:
I am trying to understand why substitution fails on the following snippet unless brackets are added:

template<typename T>
struct A {};

template<typename T>
struct B {
    B(A<T>);
};

template<typename T>
void example(A<T>, B<T>);

struct C {};

struct D {
    D(C);
};

void example2(C, D);

int main(int argc, char *argv[]) {
    example(A<int>{}, A<int>{}); // error
    example(A<int>{}, {A<int>{}}); // ok

    example2(C{}, C{}); // ok
    example2(C{}, {C{}}); // ok

    return 0;
}

See this example: https://godbolt.org/z/XPqHww

For example2 I am able to implicitly pass the C{} to the constructor of D without any error. For example I am not allowed to implicitly pass the A<int>{} until I add brackets.

What defines this behaviour?

Body:
example is a function template and the function parameters depend on the template parameter. Therefore and since you did not specify any template arguments explicitly in the call example(A<int>{}, A<int>{});, when you call this function, template argument deduction is performed to figure out what type T should be for the call.

With a few exceptions template argument deduction requires that a T can be found such that the type of the argument in the function call matches the type in the function parameter exactly.

The issue with your call is that A<int> does clearly not match  B<T> exactly for any T (and none of the exceptions apply either), so the call will fail.

This behavior is necessary, because the compiler would otherwise need to test all possible types T to check whether the function can be called. That would be computationally infeasible or impossible.

In the call example2(C{}, C{}); no templates are involved, so no template argument deduction is performed. Because the compiler doesn't need to figure out the target type in the parameter anymore, it becomes feasible to consider implicit conversions from the known argument type to the known parameter type. One such implicit conversion is the construction of D from C via the non-explicit constructor D(C);. So the call succeeds with that conversion.

example2(C{}, {C{}}); does effectively the same.

The question then is why example(A<int>{}, {A<int>{}}); works. This is because of a specific rule that can be found e.g. in [temp.deduct.type]/5.6 of the C++17 standard (draft N4659). It says that a function argument/parameter pair for which the argument is an initializer list (i.e. {A<int>{}}) and the parameter is not a specialization of std::initializer_list or an array type (it is neither here), the function parameter is a non-deduced context.

Non-deduced context means that the function argument/parameter pair will not be used during template argument deduction to figure out the type of T. This means its type does not need to match exactly. Instead, if template argument deduction otherwise succeeds, the resulting T will simply be substituted into the non-deduced context and from there implicit conversions will be considered as before. B<T> can be constructed from {A<int>} if T = int because of the non-explicit constructor B(A<T>);.

Now the question is whether template argument deduction will succeed and deduce T = int. It can only succeed if a T can be deduced from another function parameter. And indeed there is still the first parameter, for which the types match exactly: A<int>/A<T> matches for T = int and because this function argument doesn't use an initializer list, it is a context from which T will be deduced.

So indeed for example(A<int>{}, {A<int>{}}); deduction from the first argument will yield T = int and substitution into the second parameter B<T> makes the initialization/conversion B<T>{A<int>{}} succeed, so that the call is viable.

If you were to use initializer lists for both parameters as in example({A<int>{}}, {A<int>{}});, both argument/parameter pairs become non-deduced context and there wouldn't be anything left to deduce T from and so the call would fail for failure to deduce T.

You can make all calls work by specifying T explicitly, so that template argument deduction becomes unnecessary, e.g.:

example<int>(A<int>{}, A<int>{});


问:
Scrape information from multiple URLs listed in a CSV using BeautifulSoup and then export these results to a new CSV file
I have a 45k+ rows CSV file, each one containing a different path of the same domain - which are structurally identical to each other - and every single one is clickable. I managed to use BeautifulSoup to scrape the title and content of each one and through the print function, I was able to validate the scraper. However, when I try to export the information gathered to a new CSV file, I only get the last URL's street name and description, and not all of them as I expected.

```<code>from bs4 import BeautifulSoup
import requests
import csv

with open('URLs.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        site = requests.get(row['addresses']).text
        soup = BeautifulSoup(site, 'lxml')
        StreetName = soup.find('div', class_='hist-title').text
        Description = soup.find('div', class_='hist-content').text
with open('OutputList.csv','w', newline='') as output:
    Header = ['StreetName', 'Description']
    writer = csv.DictWriter(output, fieldnames=Header)

    writer.writeheader()
    writer.writerow({'StreetName' : StreetName, 'Description' : Description})
</code>```

How can the output CSV have on each row the street name and description for the respective URL row in the input CSV file?

答:
You need to open both files on the same level and then read and write on each iteration. Something like this:

from bs4 import BeautifulSoup
import requests
import csv

with open('URLs.csv') as a, open('OutputList.csv', 'w') as b:

    reader = csv.reader(a)

    writer = csv.writer(b, quoting=csv.QUOTE_ALL)
    writer.writerow(['StreetName', 'Description'])

    # Assuming url is the first field in the CSV
    for url, *_ in reader:
        r = requests.get(url)
        if r.ok:
            soup = BeautifulSoup(r.text, 'lxml')
            street_name = soup.find('div', class_='hist-title').text.strip()
            description = soup.find('div', class_='hist-content').text.strip()
            writer.writerow([street_name, description])
```

I hope it helps.

Body:
I have a 45k+ rows CSV file, each one containing a different path of the same domain - which are structurally identical to each other - and every single one is clickable. I managed to use BeautifulSoup to scrape the title and content of each one and through the print function, I was able to validate the scraper. However, when I try to export the information gathered to a new CSV file, I only get the last URL's street name and description, and not all of them as I expected.

from bs4 import BeautifulSoup
import requests
import csv

with open('URLs.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        site = requests.get(row['addresses']).text
        soup = BeautifulSoup(site, 'lxml')
        StreetName = soup.find('div', class_='hist-title').text
        Description = soup.find('div', class_='hist-content').text
with open('OutputList.csv','w', newline='') as output:
    Header = ['StreetName', 'Description']
    writer = csv.DictWriter(output, fieldnames=Header)

    writer.writeheader()
    writer.writerow({'StreetName' : StreetName, 'Description' : Description})

How can the output CSV have on each row the street name and description for the respective URL row in the input CSV file?

Body:
You need to open both files on the same level and then read and write on each iteration. Something like this:

from bs4 import BeautifulSoup
import requests
import csv

with open('URLs.csv') as a, open('OutputList.csv', 'w') as b:

    reader = csv.reader(a)

    writer = csv.writer(b, quoting=csv.QUOTE_ALL)
    writer.writerow(['StreetName', 'Description'])

    # Assuming url is the first field in the CSV
    for url, *_ in reader:
        r = requests.get(url)
        if r.ok:
            soup = BeautifulSoup(r.text, 'lxml')
            street_name = soup.find('div', class_='hist-title').text.strip()
            description = soup.find('div', class_='hist-content').text.strip()
            writer.writerow([street_name, description])

I hope it helps.


问:
Ruby Axlsx true auto-width for columns?
I'm using Axlsx to create an Excel file with one worksheet. I cannot figure out how to get all of the column widths to automatically resize to fit all of the data. Consider the following code where I add rows to a worksheet ws:

```<code>  ws.add_row ["this is just a test to see how far it will go because column will not show", "test", "this is also a testtt"]
  ws.add_row [""]
</code>```

By default, columns seem to use auto-width, but even if not, I tried adding the :widths=>[:auto, :auto, :auto] to my add_row code. It seems like some kind of auto fit is applied to my columns because that first long column is expanding to fit most of the cell. But it does not fit entire cell, just expands enough to fit most but leaves off the last word or two.

Any way to achieve a true autofit functionality?

答:
How about the next cord ?</p>

```<code>wb = Axlsx::Package.new.workbook
wb.use_autowidth = true
wb.add_worksheet(name: 'sheet_name') do |sheet|
  ws.add_row ["this is just a test to see how far it will go because column will not show", "test", "this is also a testtt"]
end
</code>```

Title: Ruby Axlsx true auto-width for columns?

Body:
I'm using Axlsx to create an Excel file with one worksheet. I cannot figure out how to get all of the column widths to automatically resize to fit all of the data. Consider the following code where I add rows to a worksheet ws:

  ws.add_row ["this is just a test to see how far it will go because column will not show", "test", "this is also a testtt"]
  ws.add_row [""]

By default, columns seem to use auto-width, but even if not, I tried adding the :widths=>[:auto, :auto, :auto] to my add_row code. It seems like some kind of auto fit is applied to my columns because that first long column is expanding to fit most of the cell. But it does not fit entire cell, just expands enough to fit most but leaves off the last word or two.

Any way to achieve a true autofit functionality?

Body:
How about the next cord ?

wb = Axlsx::Package.new.workbook
wb.use_autowidth = true
wb.add_worksheet(name: 'sheet_name') do |sheet|
  ws.add_row ["this is just a test to see how far it will go because column will not show", "test", "this is also a testtt"]
end


问:
Istio sidecar injection fails with no route to host
My goal is to have a simple Istio setup on a Kubernetes cluster. I was able to achieve this using Docker Desktop on my laptop.

As a next step, thought of doing this on a Kubernetes cluster hosted on CentOS VMs in my company's internal data center. I have a simple Kubernetes cluster setup and am able to deploy a few sample services there. I then setup Istio and created a new namespace with istio-injection=enabled. When I try to deploy a service in the new namespace, I get the below error.

```<code>> Error creating: Internal error occurred: failed calling webhook
> "sidecar-injector.istio.io": Post
> https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s:
> dial tcp 10.109.98.58:443: connect: no route to host
</code>```

I am not sure what I am doing wrong, or if I am missing any configuration.

Any help or pointers would be appreciated.

Below is the output of kubectl get pods --all-namespaces

```<code>NAMESPACE      NAME                                     READY   STATUS             RESTARTS   AGE
istio-system   grafana-6c8f45499-hv4tq                  1/1     Running            0          10d
istio-system   istio-citadel-db8578cc4-bsdcj            1/1     Running            0          10d
istio-system   istio-egressgateway-f9c7b6669-h9tvh      0/1     Running            0          10d
istio-system   istio-galley-786ff7f89b-42snm            1/1     Running            0          10d
istio-system   istio-ingressgateway-5654f8bf65-6bg7n    0/1     Running            0          10d
istio-system   istio-pilot-c565b478c-j4f8c              0/1     Running            0          10d
istio-system   istio-policy-7d5f97776c-n4c96            0/1     CrashLoopBackOff   5031       10d
istio-system   istio-sidecar-injector-c7ff9dd99-wh9nf   1/1     Running            0          14h
istio-system   istio-telemetry-55dd49cf85-f26hp         0/1     CrashLoopBackOff   5117       10d
istio-system   istio-tracing-78548677bc-zqz5j           1/1     Running            0          10d
istio-system   kiali-fb5f485fb-ll6bz                    1/1     Running            0          10d
istio-system   prometheus-685585888b-rwl2r              1/1     Running            0          10d
kube-system    coredns-5d4dd4b4db-cj927                 1/1     Running            0          11d
kube-system    coredns-5d4dd4b4db-kwcqf                 1/1     Running            0          11d
kube-system    etcd-master-node                         1/1     Running            0          11d
kube-system    kube-apiserver-master-node               1/1     Running            0          11d
kube-system    kube-controller-manager-master-node      1/1     Running            0          11d
kube-system    kube-proxy-49qdq                         1/1     Running            0          11d
kube-system    kube-proxy-h2p7c                         1/1     Running            1          10d
kube-system    kube-proxy-ncwnx                         1/1     Running            1          10d
kube-system    kube-scheduler-master-node               1/1     Running            0          11d
kube-system    weave-net-67r6x                          2/2     Running            0          11d
kube-system    weave-net-kxvbc                          2/2     Running            2          10d
kube-system    weave-net-spv99                          2/2     Running            3          10d
</code>```

The logs of executing kubectl --v=9 apply -f https://raw.githubusercontent.com/istio/istio/release-1.4/samples/bookinfo/networking/bookinfo-gateway.yaml are available here (It's too huge to be attached to the post).

Thank you.

PS: I used the word service loosely earlier.

-Anoop

答: Kindly check the connection between your api-server and sidecar-injector. I have faced this issue before and it was that the ports were not open on host level. So, you can check node ports if they are open and also if there are any network policy that you need to open to establish the connection. Check sidecar-injector pod logs if it received any request.</p>

Body:
My goal is to have a simple Istio setup on a Kubernetes cluster. I was able to achieve this using Docker Desktop on my laptop.

As a next step, thought of doing this on a Kubernetes cluster hosted on CentOS VMs in my company's internal data center. I have a simple Kubernetes cluster setup and am able to deploy a few sample services there. I then setup Istio and created a new namespace with istio-injection=enabled. When I try to deploy a service in the new namespace, I get the below error.

> Error creating: Internal error occurred: failed calling webhook
> "sidecar-injector.istio.io": Post
> https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s:
> dial tcp 10.109.98.58:443: connect: no route to host

I am not sure what I am doing wrong, or if I am missing any configuration.

Any help or pointers would be appreciated.

Below is the output of kubectl get pods --all-namespaces

NAMESPACE      NAME                                     READY   STATUS             RESTARTS   AGE
istio-system   grafana-6c8f45499-hv4tq                  1/1     Running            0          10d
istio-system   istio-citadel-db8578cc4-bsdcj            1/1     Running            0          10d
istio-system   istio-egressgateway-f9c7b6669-h9tvh      0/1     Running            0          10d
istio-system   istio-galley-786ff7f89b-42snm            1/1     Running            0          10d
istio-system   istio-ingressgateway-5654f8bf65-6bg7n    0/1     Running            0          10d
istio-system   istio-pilot-c565b478c-j4f8c              0/1     Running            0          10d
istio-system   istio-policy-7d5f97776c-n4c96            0/1     CrashLoopBackOff   5031       10d
istio-system   istio-sidecar-injector-c7ff9dd99-wh9nf   1/1     Running            0          14h
istio-system   istio-telemetry-55dd49cf85-f26hp         0/1     CrashLoopBackOff   5117       10d
istio-system   istio-tracing-78548677bc-zqz5j           1/1     Running            0          10d
istio-system   kiali-fb5f485fb-ll6bz                    1/1     Running            0          10d
istio-system   prometheus-685585888b-rwl2r              1/1     Running            0          10d
kube-system    coredns-5d4dd4b4db-cj927                 1/1     Running            0          11d
kube-system    coredns-5d4dd4b4db-kwcqf                 1/1     Running            0          11d
kube-system    etcd-master-node                         1/1     Running            0          11d
kube-system    kube-apiserver-master-node               1/1     Running            0          11d
kube-system    kube-controller-manager-master-node      1/1     Running            0          11d
kube-system    kube-proxy-49qdq                         1/1     Running            0          11d
kube-system    kube-proxy-h2p7c                         1/1     Running            1          10d
kube-system    kube-proxy-ncwnx                         1/1     Running            1          10d
kube-system    kube-scheduler-master-node               1/1     Running            0          11d
kube-system    weave-net-67r6x                          2/2     Running            0          11d
kube-system    weave-net-kxvbc                          2/2     Running            2          10d
kube-system    weave-net-spv99                          2/2     Running            3          10d

The logs of executing kubectl --v=9 apply -f https://raw.githubusercontent.com/istio/istio/release-1.4/samples/bookinfo/networking/bookinfo-gateway.yaml are available here (It's too huge to be attached to the post).

Thank you.

PS: I used the word service loosely earlier.

-Anoop


问:
How can I make this sidenav menu be fixed in computers, but collapsible in phones / tablets? See the gifs on the links down there 2 understand
I want THIS (I mean, the same menu system): https://i.stack.imgur.com/O5EtV.gif

I have THIS (I mean, the same menu system): https://i.stack.imgur.com/ChI3e.gif

Here's the code I got:

     body {
          margin: 0;
          font-family: Helvetica;
        }
        .topnav {
          overflow: hidden;
          background-color: rgb(159,44,40);
          height: 48px;
        }

        .topnav a {
          float: left;
          display: block;
          color: #f2f2f2;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
          font-size: 17px;
        }
        #myprofile {
            position: absolute;
            right: 12.5px;
        }
        #mailshortcut {
            position: absolute;
            right: 57.5px;
        }
        #notif {
            position: absolute;
            right: 102.5px;
            width: 69px;
            padding: 14px 16px;
            text-align: left;
        }
        #calendarshortcut {
            position: absolute;
            right: 170px;
            text-align: left;
        }
        #search {
            position: absolute;
            right: 215.5px;
            width: 50px;
            padding: 14px 14px;
        }
        .topnav .unee {
          color: #CDB26E;
          text-transform: lowercase;
          font-weight: 800;
        }
        .active {
          font-weight: 800;
          text-transform: lowercase;
          position: absolute;
          left: 54px;
        }
        #univlogo {
          left: 25px;
          top: 4px;
          position: absolute;
        }
        .thelogo {
          position: absolute;
          right: 285px;
          top: 4px;
        }
        .badge {
         position: absolute;
         top:12px;
         right: 8px;
         padding: 5px 8px;
         border-radius: 50%;
         background-color: rgb(209,91,71);
         color: white;
         font-size: 10px;
         }
         #phonetablet {display: none;}
         @media screen and (max-width: 990px) {
            .column {
                 float: left;
                width: 100%;
                padding: 10px;
                height: 300px;
            }
            #phonetablet {
                display: block;
            }
            .topnav .responsive a .active {
              display: none;
            }
            #desktop {
              display: none;
            }
            #myprofile {
            position: absolute;
            right: 0px;
            width: 57px;
        }
        .sidenav {padding-top: 15px;}
        .sidenav a {font-size: 18px;}
        #univlogo {
          left: 40px;
          top: 4px;
          position: absolute;
        }
        .thelogo {
          position: absolute;
          right: 285px;
          top: 4px;

        }
        }
        #archive {
            background: #6e8cd0;
            color: white;
            margin-top: 0;
        }
        .sidenav {
        height: 100%;
        width: 200px;
        position: fixed;
        z-index: 1;
        top: 48px;
        left: 0;
        background-color: #ddd;
        overflow-x: hidden;
        padding-top: 20px;
        border-right: solid 1px #ccc;
        }

        .sidenav a {
        padding: 6px 6px 6px 32px;
        text-decoration: none;
        font-size: 25px;
        color: rgb(88,88,88);
        display: block;
        font-size: 20px;
        border-top: #ccc solid 1px;
        }
        .first {
        position: absolute;
        top: 0;
        width: 200px;
        border: none;
        border-top: none;
        border-bottom: none;
        }
        .second {
        position: absolute;
        top: 37px;
        width: 200px;
        }
        .secondhalf {
        position: absolute;
        top: 74px;
        width: 200px;
        }
        .third {
        position: absolute;
        top: 111px;
        width: 200px;
        }
        .fourth {
        position: absolute;
        top: 148px;
        width: 200px;
        }
        .fifth {
        position: absolute;
        top: 185px;
        width: 200px;
        }
        .sixth {
        position: absolute;
        top: 222px;
        width: 200px;
        border-bottom: #ccc solid 1px;
        }
        .seventh {
        position: absolute;
        top: 259px;
        width: 200px;
        border-bottom: #ccc solid 1px;
        }
        .sidenav a:hover {
        color: rgb(159,44,40);
        background: white;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <!DOCTYPE html>
   <head>
   <link rel="stylesheet" href="style.css">
   </head>
   <body>
    <div class="topnav" id="myTopnav">
        <img id="univlogo" src="file:///Users/Ari/Library/Mobile%20Documents/com~apple~CloudDocs/SIMON/SIMON%20TRABAJOS/ai%20doll%20face/Renault%202006/NewLogo.jpg" width="40" height="40">
        <img class="thelogo" id="desktop"src="file:///Users/Ari/Library/Mobile%20Documents/com~apple~CloudDocs/SIMON/SIMON%20TRABAJOS/ai%20doll%20face/Renault%202006/thelogo.png" height="40" width="60">
        <img class="thelogo" id="phonetablet" src="file:///Users/Ari/Library/Mobile%20Documents/com~apple~CloudDocs/SIMON/SIMON%20TRABAJOS/ai%20doll%20face/Renault%202006/shortened%20logo.png" height="40" width="60">
        UNEE
      </div>

      <div class="sidenav">
        <!-- Add font awesome icons -->
         <i class="fa fa-archive"></i><strong> Histórico</strong>
          <i class="fa fa-tachometer"></i> <strong>Mi espacio</strong>
          <i class="fa fa-comments-o"></i> uneeChat
          <i class="fa fa-cloud"></i> uneeCloud
          <i class="fa fa-calendar"></i> Asistencia
          <i class="fa fa-check-square-o"></i> Evaluaciones
          <i class="fa fa-film"></i> Cuatrimestres
          <i style="font-style: italic !important;"class="fa fa-book"></i> Comisiones
        </div>
</body></code>```

"style.css" is the css code up here.

So, tell me what can I do to get the desired menu.

And I have tried once with a code made by myself, but I couldn't make it work.
Plus, I have searched for the solution in all forums on the internet and in coding websites, but I still cannot find the answer.

Please. Will you be able to solve my problem? Thank u in advance!

PS: The links in there are the pictures.

答: you can use media queries for making your website content responsive for screen sizes , and for the collapse nav it's available in bootstrap if you like to build the code using it</p>

Body:
I want THIS (I mean, the same menu system): https://i.stack.imgur.com/O5EtV.gif

I have THIS (I mean, the same menu system): https://i.stack.imgur.com/ChI3e.gif

Here's the code I got:

     body {
          margin: 0;
          font-family: Helvetica;
        }
        .topnav {
          overflow: hidden;
          background-color: rgb(159,44,40);
          height: 48px;
        }

        .topnav a {
          float: left;
          display: block;
          color: #f2f2f2;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
          font-size: 17px;
        }
        #myprofile {
            position: absolute;
            right: 12.5px;
        }
        #mailshortcut {
            position: absolute;
            right: 57.5px;
        }
        #notif {
            position: absolute;
            right: 102.5px;
            width: 69px;
            padding: 14px 16px;
            text-align: left;
        }
        #calendarshortcut {
            position: absolute;
            right: 170px;
            text-align: left;
        }
        #search {
            position: absolute;
            right: 215.5px;
            width: 50px;
            padding: 14px 14px;
        }
        .topnav .unee {
          color: #CDB26E;
          text-transform: lowercase;
          font-weight: 800;
        }
        .active {
          font-weight: 800;
          text-transform: lowercase;
          position: absolute;
          left: 54px;
        }
        #univlogo {
          left: 25px;
          top: 4px;
          position: absolute;
        }
        .thelogo {
          position: absolute;
          right: 285px;
          top: 4px;
        }
        .badge {
         position: absolute;
         top:12px;
         right: 8px;
         padding: 5px 8px;
         border-radius: 50%;
         background-color: rgb(209,91,71);
         color: white;
         font-size: 10px;
         }
         #phonetablet {display: none;}
         @media screen and (max-width: 990px) {
            .column {
                 float: left;
                width: 100%;
                padding: 10px;
                height: 300px;
            }
            #phonetablet {
                display: block;
            }
            .topnav .responsive a .active {
              display: none;
            }
            #desktop {
              display: none;
            }
            #myprofile {
            position: absolute;
            right: 0px;
            width: 57px;
        }
        .sidenav {padding-top: 15px;}
        .sidenav a {font-size: 18px;}
        #univlogo {
          left: 40px;
          top: 4px;
          position: absolute;
        }
        .thelogo {
          position: absolute;
          right: 285px;
          top: 4px;

        }
        }
        #archive {
            background: #6e8cd0;
            color: white;
            margin-top: 0;
        }
        .sidenav {
        height: 100%;
        width: 200px;
        position: fixed;
        z-index: 1;
        top: 48px;
        left: 0;
        background-color: #ddd;
        overflow-x: hidden;
        padding-top: 20px;
        border-right: solid 1px #ccc;
        }

        .sidenav a {
        padding: 6px 6px 6px 32px;
        text-decoration: none;
        font-size: 25px;
        color: rgb(88,88,88);
        display: block;
        font-size: 20px;
        border-top: #ccc solid 1px;
        }
        .first {
        position: absolute;
        top: 0;
        width: 200px;
        border: none;
        border-top: none;
        border-bottom: none;
        }
        .second {
        position: absolute;
        top: 37px;
        width: 200px;
        }
        .secondhalf {
        position: absolute;
        top: 74px;
        width: 200px;
        }
        .third {
        position: absolute;
        top: 111px;
        width: 200px;
        }
        .fourth {
        position: absolute;
        top: 148px;
        width: 200px;
        }
        .fifth {
        position: absolute;
        top: 185px;
        width: 200px;
        }
        .sixth {
        position: absolute;
        top: 222px;
        width: 200px;
        border-bottom: #ccc solid 1px;
        }
        .seventh {
        position: absolute;
        top: 259px;
        width: 200px;
        border-bottom: #ccc solid 1px;
        }
        .sidenav a:hover {
        color: rgb(159,44,40);
        background: white;
        }

   <!DOCTYPE html>

   <link rel="stylesheet" href="style.css">

        UNEE

          Histórico
           Mi espacio
           uneeChat
           uneeCloud
           Asistencia
           Evaluaciones
           Cuatrimestres
           Comisiones

"style.css" is the css code up here.

So, tell me what can I do to get the desired menu.

And I have tried once with a code made by myself, but I couldn't make it work.
Plus, I have searched for the solution in all forums on the internet and in coding websites, but I still cannot find the answer.

Please. Will you be able to solve my problem? Thank u in advance!

PS: The links in there are the pictures.