问:
Read an XML standard config file selected from console
I created a CLI application which actually uses the standard config app.Config file.

In this file I put some subsections, like

```<code> <typicsTable>
    <mainSettings>
      <add key="sheetNumber" value="1"/>
      <add key="firstDataRow" value="2"/>
    </mainSettings>
 </typicsTable>
</code>```

I actually read these settings with

```<code>NameValueCollection TypicsConversionTableSettings = (NameValueCollection)ConfigurationManager.GetSection("typicsTable/mainSettings");

int ctSheetNumber =     Int32.Parse(TypicsConversionTableSettings["sheetNumber"]);
int ctFirstDataRow =    Int32.Parse(TypicsConversionTableSettings["firstDataRow"]);
</code>```

Everything works fine in this way.

What I want to do now is

1) I want different config files with custom names (i.e. test1.config , test2.config) and take via CLI the right config file;

2) switch to a less ".net config file", and take data from a standard XML file.

I'm now focusing on the point 1, I tried different attempts, I used

```<code>ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = @"C:\folderTest\conf1.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
</code>```

But I absolutely don't get how to read sections AND subsections in the file. How can I do that?

答:
The class that is going to help you, I believe, is System.Xml.Linq.

```<code>using System.Xml.Linq;
</code>```

So Part 1 would be load the file into an XElement:

```<code>XElement xConfig = XElement.Load("app.simulated.config");
</code>```

Here's a quick demo of how you can iterate through everything and also find a single element using a matching condition.

```<code>class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("Iterating the config file values and attributes...");
        Console.WriteLine("==================================================");
        XElement xConfig = XElement.Load("app.simulated.config");
        foreach (var element in xConfig.DescendantsAndSelf())
        {
            Console.WriteLine(element.Name);
            foreach (var attribute in element.Attributes())
            {
                Console.WriteLine("\t" + attribute.Name + "," + attribute.Value);
            }
        }

        Console.WriteLine();
        Console.WriteLine("Finding a value using matching conditions.");
        Console.WriteLine("==========================================");

        XElement xel =
            xConfig
            .DescendantsAndSelf()
            .FirstOrDefault(match =>
                (match.Attribute("key") != null) &&
                (match.Attribute("key").Value == "sheetNumber"));

        Console.WriteLine(
            "The value of 'sheetNumber' is " +
            xel.Attribute("value").Value
         );

        // Pause
        Console.ReadKey();
    }
}
</code>```

Clone or Download this example from GitHub.

Body:
I created a CLI application which actually uses the standard config app.Config file.

In this file I put some subsections, like

 <typicsTable>
    <mainSettings>
      <add key="sheetNumber" value="1"/>
      <add key="firstDataRow" value="2"/>
    </mainSettings>
 </typicsTable>

I actually read these settings with

NameValueCollection TypicsConversionTableSettings = (NameValueCollection)ConfigurationManager.GetSection("typicsTable/mainSettings");

int ctSheetNumber =     Int32.Parse(TypicsConversionTableSettings["sheetNumber"]);
int ctFirstDataRow =    Int32.Parse(TypicsConversionTableSettings["firstDataRow"]);

Everything works fine in this way.

What I want to do now is

1) I want different config files with custom names (i.e. test1.config , test2.config) and take via CLI the right config file;

2) switch to a less ".net config file", and take data from a standard XML file.

I'm now focusing on the point 1, I tried different attempts, I used

ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = @"C:\folderTest\conf1.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

But I absolutely don't get how to read sections AND subsections in the file. How can I do that?

Body:
The class that is going to help you, I believe, is System.Xml.Linq.

using System.Xml.Linq;

So Part 1 would be load the file into an XElement:

XElement xConfig = XElement.Load("app.simulated.config");

Here's a quick demo of how you can iterate through everything and also find a single element using a matching condition.

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("Iterating the config file values and attributes...");
        Console.WriteLine("==================================================");
        XElement xConfig = XElement.Load("app.simulated.config");
        foreach (var element in xConfig.DescendantsAndSelf())
        {
            Console.WriteLine(element.Name);
            foreach (var attribute in element.Attributes())
            {
                Console.WriteLine("\t" + attribute.Name + "," + attribute.Value);
            }
        }

        Console.WriteLine();
        Console.WriteLine("Finding a value using matching conditions.");
        Console.WriteLine("==========================================");

        XElement xel =
            xConfig
            .DescendantsAndSelf()
            .FirstOrDefault(match =>
                (match.Attribute("key") != null) &&
                (match.Attribute("key").Value == "sheetNumber"));

        Console.WriteLine(
            "The value of 'sheetNumber' is " +
            xel.Attribute("value").Value
         );

        // Pause
        Console.ReadKey();
    }
}

Clone or Download this example from GitHub.


来源: stackexchange

问:
pymongo.errors.OperationFailure: Authentication failed. I need to save files from html forms
This error arises when I try to run the code below. It works fine when I remove mongo.save command. Anyway the text data is still getting saved in the database. I need to store images too. How to do that?

Python Code:

```<code>from flask import Flask, render_template, request, redirect, url_for

import pymongo
from pymongo import MongoClient
from flask_pymongo import PyMongo

app = Flask(__name__)

# configuration
app.config["MONGO_URI"] = "mongodb://Aayushi:Aayushi4799@localhost:27017/Test_Db"
app.config["DB_NAME"] = "Test_Db"
app.config["SECRET_KEY"] = "Aayushi4799"
print("configured")

# connect to mongodb
mongo1 = PyMongo(app)
db = mongo1.db
col = mongo1.db["Test_Db"]
print("connected")

# create new database
my_client = pymongo.MongoClient("mongodb://localhost:27017/")
my_db = my_client["Test_Db"]
print(my_client.list_database_names())

#connect to collections
my_col = my_db["Test_Col"]

@app.route('/')
def home():
    return render_template("forms.html")

@app.route('/view', methods=['POST'])
def view():
    form_details = {'name': request.form["name"], 'email': request.form["email"], 'pass': request.form["pass"]}
    form_img = request.files["file"]
    x = my_col.insert_one(form_details)
    y = mongo1.save_file(form_img.filename, form_img)
    if x and y:
        return redirect(url_for("thank_you"))
    else:
         return "Try Again"

@app.route('/thankyou')
def thank_you():
    return render_template("thankyou.html")

if __name__ == '__main__':
    app.run(host='192.168.1.7', port=int(5000), debug=True)
</code>```

答:
I discovered the answer to my above question myself so I'm sharing it here for anyone who might face the same issue.
  Follow the link provided and I think you'll be good to go.
  https://pythonise.com/series/learning-flask/flask-uploading-files

ContentLicense: CC BY-SA 4.0

Body:
This error arises when I try to run the code below. It works fine when I remove mongo.save command. Anyway the text data is still getting saved in the database. I need to store images too. How to do that?

Python Code:

from flask import Flask, render_template, request, redirect, url_for

import pymongo
from pymongo import MongoClient
from flask_pymongo import PyMongo

app = Flask(__name__)

# configuration
app.config["MONGO_URI"] = "mongodb://Aayushi:Aayushi4799@localhost:27017/Test_Db"
app.config["DB_NAME"] = "Test_Db"
app.config["SECRET_KEY"] = "Aayushi4799"
print("configured")

# connect to mongodb
mongo1 = PyMongo(app)
db = mongo1.db
col = mongo1.db["Test_Db"]
print("connected")

# create new database
my_client = pymongo.MongoClient("mongodb://localhost:27017/")
my_db = my_client["Test_Db"]
print(my_client.list_database_names())

#connect to collections
my_col = my_db["Test_Col"]

@app.route('/')
def home():
    return render_template("forms.html")

@app.route('/view', methods=['POST'])
def view():
    form_details = {'name': request.form["name"], 'email': request.form["email"], 'pass': request.form["pass"]}
    form_img = request.files["file"]
    x = my_col.insert_one(form_details)
    y = mongo1.save_file(form_img.filename, form_img)
    if x and y:
        return redirect(url_for("thank_you"))
    else:
         return "Try Again"

@app.route('/thankyou')
def thank_you():
    return render_template("thankyou.html")

if __name__ == '__main__':
    app.run(host='192.168.1.7', port=int(5000), debug=True)


问:
What is the default date style used by an instance of SQL Server when converting from varchar to datetime?
I've run this SQL query on two different servers:

```<code>declare @test as datetime='2020-05-06 00:00:00'
select Convert (nvarchar,@test)
</code>```

The results were different on the two servers:

May  6 2020 12:00AM

Jun  5 2020 12:00AM

I know the reason behind this, when SQL Server is reading the string that I passed 2020-05-06 00:00:00 and converting it to DateTime in the declare statement, it's using the default date style.

Am I able to configure this default style, or in other words, how is default date style chosen in SQL Server when converting the varchar to datetime? Is it from the windows regional settings or some other configurations inside SQL Server?

答:
It uses a style based on the language. Basically, for the date above, if you're American then the date will be read as yyyy-MM-dd hh:mm:ss, however, if use over languages, then it's be (stupidly) read as yyyy-dd-MM hh:mm:ss.

If you are using strings for dates (like your literal here) then aim to use an unambiguous format. In SQL Server, regardless of data type and language, those are yyyy-MM-ddThh:mm:ss.nnnnnnn and yyyyMMdd.

If you're convert to an (n)varchar, always use a style code (and a length for your varchar) for consistent results.

So, for your value, you can run the below to find out what the default conversion value would be for all the languages on your instance:

```<code>DECLARE Languages CURSOR FOR
SELECT alias
FROM sys.syslanguages;

DECLARE @Alias sysname,
        @SQL nvarchar(MAX);

CREATE TABLE #ConvertedDates (Alias sysname, dt datetime, converted nvarchar(25));

DECLARE @dt datetime = '2020-05-06T00:00:00'

OPEN Languages

FETCH NEXT FROM Languages
INTO @Alias;

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @SQL = N'SET LANGUAGE ' + QUOTENAME(@Alias) + N'; INSERT INTO #ConvertedDates(Alias,dt,converted) VALUES(N' + QUOTENAME(@Alias,'''') + ',@dt,CONVERT(nvarchar(25),@dt));';

    EXEC sys.sp_executesql @SQL, N'@dt datetime', @dt;

    FETCH NEXT FROM Languages
    INTO @Alias;

END;

CLOSE Languages;
DEALLOCATE Languages;

SELECT *
FROM #ConvertedDates;

DROP TABLE #ConvertedDates;
</code>```

Yes, that is a Cursor. I wanted to ensure that each dynamic statement ran by itself, to ensure language was preserved for each conversion.

Body:
I've run this SQL query on two different servers:

declare @test as datetime='2020-05-06 00:00:00'
select Convert (nvarchar,@test)

The results were different on the two servers:

May  6 2020 12:00AM

Jun  5 2020 12:00AM

I know the reason behind this, when SQL Server is reading the string that I passed 2020-05-06 00:00:00 and converting it to DateTime in the declare statement, it's using the default date style.

Am I able to configure this default style, or in other words, how is default date style chosen in SQL Server when converting the varchar to datetime? Is it from the windows regional settings or some other configurations inside SQL Server?

Body:
It uses a style based on the language. Basically, for the date above, if you're American then the date will be read as yyyy-MM-dd hh:mm:ss, however, if use over languages, then it's be (stupidly) read as yyyy-dd-MM hh:mm:ss.

If you are using strings for dates (like your literal here) then aim to use an unambiguous format. In SQL Server, regardless of data type and language, those are yyyy-MM-ddThh:mm:ss.nnnnnnn and yyyyMMdd.

If you're convert to an (n)varchar, always use a style code (and a length for your varchar) for consistent results.

So, for your value, you can run the below to find out what the default conversion value would be for all the languages on your instance:

DECLARE Languages CURSOR FOR
SELECT alias
FROM sys.syslanguages;

DECLARE @Alias sysname,
        @SQL nvarchar(MAX);

CREATE TABLE #ConvertedDates (Alias sysname, dt datetime, converted nvarchar(25));

DECLARE @dt datetime = '2020-05-06T00:00:00'

OPEN Languages

FETCH NEXT FROM Languages
INTO @Alias;

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @SQL = N'SET LANGUAGE ' + QUOTENAME(@Alias) + N'; INSERT INTO #ConvertedDates(Alias,dt,converted) VALUES(N' + QUOTENAME(@Alias,'''') + ',@dt,CONVERT(nvarchar(25),@dt));';

    EXEC sys.sp_executesql @SQL, N'@dt datetime', @dt;

    FETCH NEXT FROM Languages
    INTO @Alias;

END;

CLOSE Languages;
DEALLOCATE Languages;

SELECT *
FROM #ConvertedDates;

DROP TABLE #ConvertedDates;

Yes, that is a Cursor. I wanted to ensure that each dynamic statement ran by itself, to ensure language was preserved for each conversion.


问:
Is it possible to get color name in swift
I am trying to get color name from UIButton in swift instead of value is there any way to do that. Thanks

I am using tintColor to set value as well to get value

```<code>    clickButton.tintColor = UIColor.blue

    var color = clickButton.tintColor
</code>```

when I am printing color value I get (UIExtendedSRGBColorSpace 0 0 1 1) is there anyway I can get blue instead of value

答:
You can use this extension to get name of color created via Color Assets in XCode.

```<code>extension UIColor {
    /// Name of color. Only colors created with XCode Color Assets will return actual name, colors created programatically will always return nil.
    var name: String? {
        let str = String(describing: self).dropLast()
        guard let nameRange = str.range(of: "name = ") else {
            return nil
        }
        let cropped = str[nameRange.upperBound ..< str.endIndex]
        if cropped.isEmpty {
            return nil
        }
        return String(cropped)
    }
}
</code>```

Result:

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get color name from UIButton in swift instead of value is there any way to do that. Thanks

I am using tintColor to set value as well to get value

    clickButton.tintColor = UIColor.blue

    var color = clickButton.tintColor

when I am printing color value I get (UIExtendedSRGBColorSpace 0 0 1 1) is there anyway I can get blue instead of value

Body:
You can use this extension to get name of color created via Color Assets in XCode.

extension UIColor {
    /// Name of color. Only colors created with XCode Color Assets will return actual name, colors created programatically will always return nil.
    var name: String? {
        let str = String(describing: self).dropLast()
        guard let nameRange = str.range(of: "name = ") else {
            return nil
        }
        let cropped = str[nameRange.upperBound ..< str.endIndex]
        if cropped.isEmpty {
            return nil
        }
        return String(cropped)
    }
}

Result:


问:
Override padding in smaller devices React material UI
I have a grid of column 3,6,3 & I have also given a grid spacing of 3.

For lg, md screen devices sizes it looks okay i.e spacing between grid. But when I reduce the screen size spacing between Grid remains the same which does not look okay

What I want is spacing between Grid for lg & md devices to be 3 but for sm & xs devices to be 0 so I don't see any padding around Grid.

I have inspected the DOM & have seen padding to be 12px for Grid spacing 3.

I have tried this

```<code>const theme = createMuiTheme({
  ..., // Other default things
  overrides: {
    MuiGrid: {
      'spacing-xs-3': {
        '& > $item': {
          padding: 'none',
        },
      },
    },
  },
});
</code>```

This does the job of removing padding which is none obviously but for all device sizes but I want this padding to be removed only for smaller size devices.

I used this inside the component like this

```<code>  const useStyles = makeStyles(theme => ({
     ...,
     overrides: { // This part , I tried both with and without overrides key
       MuiGrid: {
        'spacing-xs-3': {
          '& > $item': {
            [theme.breakpoints.down('md')]: {
              padding: 'none',
            }
          },
        },
      },
    },
  }));
</code>```

None really seems to work, Where am I making mistake?

答:
You just need to use $root element instead of $item, like this

```<code>MuiGrid: {
            'spacing-xs-3': {
                '& > $root': {
                   [Your styles go here]
                },
            },
        },
</code>```

Body:
I have a grid of column 3,6,3 & I have also given a grid spacing of 3.

For lg, md screen devices sizes it looks okay i.e spacing between grid. But when I reduce the screen size spacing between Grid remains the same which does not look okay

What I want is spacing between Grid for lg & md devices to be 3 but for sm & xs devices to be 0 so I don't see any padding around Grid.

I have inspected the DOM & have seen padding to be 12px for Grid spacing 3.

I have tried this

const theme = createMuiTheme({
  ..., // Other default things
  overrides: {
    MuiGrid: {
      'spacing-xs-3': {
        '& > $item': {
          padding: 'none',
        },
      },
    },
  },
});

This does the job of removing padding which is none obviously but for all device sizes but I want this padding to be removed only for smaller size devices.

I used this inside the component like this

  const useStyles = makeStyles(theme => ({
     ...,
     overrides: { // This part , I tried both with and without overrides key
       MuiGrid: {
        'spacing-xs-3': {
          '& > $item': {
            [theme.breakpoints.down('md')]: {
              padding: 'none',
            }
          },
        },
      },
    },
  }));

None really seems to work, Where am I making mistake?

Body:
You just need to use $root element instead of $item, like this

MuiGrid: {
            'spacing-xs-3': {
                '& > $root': {
                   [Your styles go here]
                },
            },
        },


问:
Why is there no optimization for checking for empty string via "" comparison?
This google-benchmark code checked on Quick Bench, shows that string::empty() runs a lot faster than comparing with an empty-string literal. However, creating a name string of "" actually makes the compiler optimize away the check:

bool compareWithNamedConst(const std::string& target) {
    const std::string emptyString = "";
    return emptyString == target;
}

bool compareWithLiteral(const std::string& target) {
    return "" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{""} == target;
}

bool checkForEmpty(const std::string& target) {
    return target.empty();
}
```

<p>The performance for each of the calls is shown here:</p>

<p><img src="https://i.stack.imgur.com/Ye0MU.png" width="600" /></p>

<p>As you can see, comparing with <code>""</code> is very slow compared to all the other options. I wonder why it is the case? It must be somehow related to SSO not being applied on <code>const char*</code>, as testing this:</p>

<pre class="lang-cpp prettyprint-override"><code>bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{"test with a longer string not optimized"} == target;
}
</code>```

Results comparing with a literal actually being faster:

I find that checking for string emptiness, the easiest syntax to read is "" == myVariable as it clearly indicates that myVariable is a std::string with no unneccesary clutter. Why can't we have it optimized as we have all the other cases?

答:
For emptyness check, if you really like the literal syntax, you may help your compiler by using namespace std::string_literals;, and replacing "" with ""s. In that case compareWithLiteral, compareWithRvalue and checkForEmpty would be essentially the same, since the operator== between const std::string& usually checks the sizes before the content, and the size of ""s is trivial.

```<code>bool compareWithLiteral(const std::string& target) {
    using namespace std::string_literals;
    return ""s == target;
}
</code>```

For strings not falling into the SSO, you should try with std::string_view and its operator""sv, even if unfortunately is available only since C++17. Boost has boost::string_view. No user string literal is provided for compile time creation (essential because the test string length would be hardcoded in the binary), but you can easily define one:

```<code>#include <boost/utility/string_view.hpp>

constexpr auto operator""_sv(const char* str, std::size_t len) noexcept {
    return boost::basic_string_view<char>{str, len};
}

bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized"_sv == target;
}
</code>```

This version runs much faster than your compareWithLiteral version, at least when target size is different.

Body:
This google-benchmark code checked on Quick Bench, shows that string::empty() runs a lot faster than comparing with an empty-string literal. However, creating a name string of "" actually makes the compiler optimize away the check:

bool compareWithNamedConst(const std::string& target) {
    const std::string emptyString = "";
    return emptyString == target;
}

bool compareWithLiteral(const std::string& target) {
    return "" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{""} == target;
}

bool checkForEmpty(const std::string& target) {
    return target.empty();
}

The performance for each of the calls is shown here:

As you can see, comparing with "" is very slow compared to all the other options. I wonder why it is the case? It must be somehow related to SSO not being applied on const char*, as testing this:

bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{"test with a longer string not optimized"} == target;
}

Results comparing with a literal actually being faster:

I find that checking for string emptiness, the easiest syntax to read is "" == myVariable as it clearly indicates that myVariable is a std::string with no unneccesary clutter. Why can't we have it optimized as we have all the other cases?

Body:
For emptyness check, if you really like the literal syntax, you may help your compiler by using namespace std::string_literals;, and replacing "" with ""s. In that case compareWithLiteral, compareWithRvalue and checkForEmpty would be essentially the same, since the operator== between const std::string& usually checks the sizes before the content, and the size of ""s is trivial.

bool compareWithLiteral(const std::string& target) {
    using namespace std::string_literals;
    return ""s == target;
}

For strings not falling into the SSO, you should try with std::string_view and its operator""sv, even if unfortunately is available only since C++17. Boost has boost::string_view. No user string literal is provided for compile time creation (essential because the test string length would be hardcoded in the binary), but you can easily define one:

#include <boost/utility/string_view.hpp>

constexpr auto operator""_sv(const char* str, std::size_t len) noexcept {
    return boost::basic_string_view<char>{str, len};
}

bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized"_sv == target;
}

This version runs much faster than your compareWithLiteral version, at least when target size is different.


问:
Different sort-by by one key Clojure
Hey I have this Code but I would like to reverse only the :a key.

```<code>(sort-by (juxt :a :b) [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> [{:a 1 :b 2} {:a 1 :b 3} {:a 2 :b 1}]
</code>```

I tried this but this was in the wrong order.

```<code>(sort-by (juxt :a :b) #(compare %2 %1)  [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> ({:a 2, :b 1} {:a 1, :b 3} {:a 1, :b 2})
</code>```

I would like to get.

```<code>;;=> ({:a 2, :b 1} {:a 1, :b 2} {:a 1, :b 3})
</code>```

Any Ideas?
Can I do this also in juxt?

答:
You can try the thread last macro to sort first by :b then sort in reverse by :a.

```<code>(->> [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}]
     (sort-by :b)
     (sort-by :a #(compare %2 %1)))
</code>```

Title: Different sort-by by one key Clojure

Body:
Hey I have this Code but I would like to reverse only the :a key.

(sort-by (juxt :a :b) [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> [{:a 1 :b 2} {:a 1 :b 3} {:a 2 :b 1}]

I tried this but this was in the wrong order.

(sort-by (juxt :a :b) #(compare %2 %1)  [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> ({:a 2, :b 1} {:a 1, :b 3} {:a 1, :b 2})

I would like to get.

;;=> ({:a 2, :b 1} {:a 1, :b 2} {:a 1, :b 3})

Any Ideas?
Can I do this also in juxt?

Body:
You can try the thread last macro to sort first by :b then sort in reverse by :a.

(->> [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}]
     (sort-by :b)
     (sort-by :a #(compare %2 %1)))


问:
model.show is not working correctly not getting the id into the controller laravel
so my route is this

```<code>Route::resource('/rentals', 'RentalsController',);
</code>```

and my model is this

```<code>
namespace App;

use Illuminate\Database\Eloquent\Model;

class rentals extends Model
{
    public function avaliablities() {
        return $this->hasMany('\App\avaliablities');
    }
    public function reviews() {
        return $this->hasMany('\App\reviews');
    }
    public function reservations() {
        return $this->hasMany('\App\reservations');
    }
}
</code>```

and the part of the controller in function is this

```<code>    public function show(rentals $rentals)
    {
        dd($rentals);
        $rental = \App\Rentals::with('reviews')->find($rental->id);

        dd($rental);
        return view('detail', compact('rentals'));
    }

</code>```

but when i do the dump and die $rentals there is nothing in it but it also gives no error. (edit it does say it is an int and is an id)

so i am stuck at this and have no idee to fix it probaly something with my routes but i tried the get but that just broke everything when i did

```<code>Route::get('/rentals/{id}','RentalsController@show', );
</code>```

and i am totaly out of idee's

and in previous projects where i used laravel this did work. and as shown here i get the data of the id again from the database so you can go to the page via a link and it doesn't break and also gets updated

and checked if i didn't make a custom id by accedent in the seeder but it looked fine

答:
You can try this</p>

```<code>Route::get('/Rentals/{rentals}','RentalsController@show', );
</code>```

Body:
so my route is this

Route::resource('/rentals', 'RentalsController',);

and my model is this

namespace App;

use Illuminate\Database\Eloquent\Model;

class rentals extends Model
{
    public function avaliablities() {
        return $this->hasMany('\App\avaliablities');
    }
    public function reviews() {
        return $this->hasMany('\App\reviews');
    }
    public function reservations() {
        return $this->hasMany('\App\reservations');
    }
}

and the part of the controller in function is this

    public function show(rentals $rentals)
    {
        dd($rentals);
        $rental = \App\Rentals::with('reviews')->find($rental->id);

        dd($rental);
        return view('detail', compact('rentals'));
    }

but when i do the dump and die $rentals there is nothing in it but it also gives no error. (edit it does say it is an int and is an id)

so i am stuck at this and have no idee to fix it probaly something with my routes but i tried the get but that just broke everything when i did

Route::get('/rentals/{id}','RentalsController@show', );

and i am totaly out of idee's

and in previous projects where i used laravel this did work. and as shown here i get the data of the id again from the database so you can go to the page via a link and it doesn't break and also gets updated

and checked if i didn't make a custom id by accedent in the seeder but it looked fine

Body:
You can try this

Route::get('/Rentals/{rentals}','RentalsController@show', );


问:
Is there a way to check if folder exists in s3 using aws cli?
Let's say I have a bucket named Test which has folder Alpha/TestingOne,Alpha/TestingTwo . I want to check if a folder named Alpha/TestingThree is present in my bucket using aws cli . I did try aws

s3api head-object --bucket Test --key Alpha/TestingThree

But seems the head-object is for files and not for folders . So is there a way to check if a folder exists in aws s3 using aws cli api .

答:
There seem to be no way to test if a 'folder' exists in s3 bucket. That should be somehow related to the fact that everything is an 'object' with a key/value.

As an option, you could utilize list-objects-v2 or list-objects to check for the 'contents' of a prefix (aka 'folder'):

```<code>$ aws s3api list-objects-v2 --bucket <bucket_name> --prefix <non_exist_prefix_name> --query 'Contents[]'
null
</code>```

Prefix (aka 'folder') that doesn't exist will always return 'null' for such query. Then you can use comparison against 'null' value:

```<code>$ test "$result" == "null" && echo 'yes' || echo 'no'
</code>```

Body:
There seem to be no way to test if a 'folder' exists in s3 bucket. That should be somehow related to the fact that everything is an 'object' with a key/value.

As an option, you could utilize list-objects-v2 or list-objects to check for the 'contents' of a prefix (aka 'folder'):

$ aws s3api list-objects-v2 --bucket <bucket_name> --prefix <non_exist_prefix_name> --query 'Contents[]'
null

Prefix (aka 'folder') that doesn't exist will always return 'null' for such query. Then you can use comparison against 'null' value:

$ test "$result" == "null" && echo 'yes' || echo 'no'


问:
how do i make something which moves with Velocity jump in Unity?
I was hoping I could get some help! I've been trying to make a platformer using velocity to move but I can't find a good way to do jumping using the system. Every frame the velocity's y just resets itself and I don't know how to create a jump. I have tried using ForceMode.VelocityChange and I have tried to write out equations. The player falls extremely slowly even with gravity turned on.
 playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);

I have the same issues when I try to set the y velocity to change with gravity

```<code>float MoveDirectionY = jumpForce * Physics.gravity.y;
</code>```

enter image description here

Nothing seems to be working here. When i play the game gravity still pulls the object down slowly but if i turn off gravity it doesnt pull the object down at all.

The game does log the statement letting me know that it does know the space button was pressed.alt text

I want to also provide my code here:

```<code>using System.Collections;
 using System.Collections.Generic;
 using System.Transactions;
 using Unity.Collections.LowLevel.Unsafe;
 using UnityEngine;

 public class PlayerMovement : MonoBehaviour
 {
     [SerializeField] private Rigidbody playerBody;
     [SerializeField] private Vector3 inputVector;
     [SerializeField] public float speed = 0.01f;
     [SerializeField] public bool jump;
     [SerializeField] private float turnSpeed = 45;
     [SerializeField] public float jumpForce = 35000f;
     [SerializeField] private bool isOnGround = true;
     [SerializeField] float enemyPushForce = 100;
     public int ingredient;
     public GameManager gameManager;
     public camSwitch cs;
     public float horizontalInput;
     public float verticalInput;
     float playerFacingAngleY;
     private GameObject FocalPoint;

     // Start is called before the first frame update
     void Start()
     {
         //Just making sure we have the rigid body of the game object the script is attached to so we can move it later
         playerBody = gameObject.GetComponent<Rigidbody>();
         FocalPoint = GameObject.Find("Focal Point");
     }

     // Update is called once per frame
     //This is where the player script should be realizing we are using inputs
     void Update()
     {
         horizontalInput = Input.GetAxis("Horizontal");
         verticalInput = Input.GetAxis("Vertical");
         playerFacingAngleY += horizontalInput * turnSpeed;
         Vector3 playerFacingDirection = new Vector3(0, playerFacingAngleY, 0);
         playerBody.rotation = Quaternion.Euler(playerFacingDirection);
         float moveDirectionX = (FocalPoint.transform.position.x - gameObject.transform.position.x) *speed * verticalInput * Time.deltaTime;
         float MoveDirectionY = jumpForce * Physics.gravity.y;
         float moveDirectionZ = (FocalPoint.transform.position.z - gameObject.transform.position.z) * speed * verticalInput * Time.deltaTime;
         Vector3 moveDirection = new Vector3(moveDirectionX, MoveDirectionY, moveDirectionZ);

         playerBody.velocity = moveDirection;

         if (Input.GetKeyDown(KeyCode.Space) && isOnGround == true)
         {
             playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
             isOnGround = false;
             print("player has jumped");
         }

     }

     private void OnCollisionEnter(Collision collision)
     {
         isOnGround = true;
         if (collision.gameObject.tag == "Enemy")
         {
             Debug.Log("Player ran into an enemy");
             if (cs.inSky == true)
             {
                 speed = 0;
             }
             else
             {
                 speed = 10;
             }
         }
         else if (collision.gameObject.tag == "Ingredient")
         {

             Debug.Log("Player collided with an ingredient");
             collision.gameObject.SetActive(false);
             ingredient++;
         }
         else if (collision.gameObject.tag == "Ground") {
             isOnGround = true;
             print("player has hit the ground");
         }

     }
 }
</code>```

答:
Do not play with rigidbody in Update method. Use FixedUpdate() instead.
In addition, do not change velocity using rb.velocity = ... but use rigibody.AddForce() method. Try something like this:

```<code> void FixedUpdate() //using rigidbody? => ONLY FIXEDUPDATE
     {
         horizontalInput = Input.GetAxis("Horizontal");
         verticalInput = Input.GetAxis("Vertical");
         playerFacingAngleY += horizontalInput * turnSpeed;
         Vector3 playerFacingDirection = new Vector3(0, playerFacingAngleY, 0);
         playerBody.rotation = Quaternion.Euler(playerFacingDirection);
         float moveDirectionX = (FocalPoint.transform.position.x - gameObject.transform.position.x) *speed * verticalInput * Time.deltaTime;
         float moveDirectionZ = (FocalPoint.transform.position.z - gameObject.transform.position.z) * speed * verticalInput * Time.deltaTime;
         Vector3 moveDirection = new Vector3(moveDirectionX, 0.0f, moveDirectionZ); //0.0f - just turn on gravity in rigidbody component or you can change it if you want some additional Vertical force
         playerBody.AddForce(moveDirection, ForceMode.VelocityChange); //force mode change to whatever you want

         if (Input.GetKeyDown(KeyCode.Space) && isOnGround == true)
         {
             playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
             isOnGround = false;
             print("player has jumped");
         }
     }
</code>```

Body:
I was hoping I could get some help! I've been trying to make a platformer using velocity to move but I can't find a good way to do jumping using the system. Every frame the velocity's y just resets itself and I don't know how to create a jump. I have tried using ForceMode.VelocityChange and I have tried to write out equations. The player falls extremely slowly even with gravity turned on.
 playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);

I have the same issues when I try to set the y velocity to change with gravity

float MoveDirectionY = jumpForce * Physics.gravity.y;

enter image description here

Nothing seems to be working here. When i play the game gravity still pulls the object down slowly but if i turn off gravity it doesnt pull the object down at all.

The game does log the statement letting me know that it does know the space button was pressed.alt text

I want to also provide my code here:

using System.Collections;
 using System.Collections.Generic;
 using System.Transactions;
 using Unity.Collections.LowLevel.Unsafe;
 using UnityEngine;

 public class PlayerMovement : MonoBehaviour
 {
     [SerializeField] private Rigidbody playerBody;
     [SerializeField] private Vector3 inputVector;
     [SerializeField] public float speed = 0.01f;
     [SerializeField] public bool jump;
     [SerializeField] private float turnSpeed = 45;
     [SerializeField] public float jumpForce = 35000f;
     [SerializeField] private bool isOnGround = true;
     [SerializeField] float enemyPushForce = 100;
     public int ingredient;
     public GameManager gameManager;
     public camSwitch cs;
     public float horizontalInput;
     public float verticalInput;
     float playerFacingAngleY;
     private GameObject FocalPoint;

     // Start is called before the first frame update
     void Start()
     {
         //Just making sure we have the rigid body of the game object the script is attached to so we can move it later
         playerBody = gameObject.GetComponent<Rigidbody>();
         FocalPoint = GameObject.Find("Focal Point");
     }

     // Update is called once per frame
     //This is where the player script should be realizing we are using inputs
     void Update()
     {
         horizontalInput = Input.GetAxis("Horizontal");
         verticalInput = Input.GetAxis("Vertical");
         playerFacingAngleY += horizontalInput * turnSpeed;
         Vector3 playerFacingDirection = new Vector3(0, playerFacingAngleY, 0);
         playerBody.rotation = Quaternion.Euler(playerFacingDirection);
         float moveDirectionX = (FocalPoint.transform.position.x - gameObject.transform.position.x) *speed * verticalInput * Time.deltaTime;
         float MoveDirectionY = jumpForce * Physics.gravity.y;
         float moveDirectionZ = (FocalPoint.transform.position.z - gameObject.transform.position.z) * speed * verticalInput * Time.deltaTime;
         Vector3 moveDirection = new Vector3(moveDirectionX, MoveDirectionY, moveDirectionZ);

         playerBody.velocity = moveDirection;

         if (Input.GetKeyDown(KeyCode.Space) && isOnGround == true)
         {
             playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
             isOnGround = false;
             print("player has jumped");
         }

     }

     private void OnCollisionEnter(Collision collision)
     {
         isOnGround = true;
         if (collision.gameObject.tag == "Enemy")
         {
             Debug.Log("Player ran into an enemy");
             if (cs.inSky == true)
             {
                 speed = 0;
             }
             else
             {
                 speed = 10;
             }
         }
         else if (collision.gameObject.tag == "Ingredient")
         {

             Debug.Log("Player collided with an ingredient");
             collision.gameObject.SetActive(false);
             ingredient++;
         }
         else if (collision.gameObject.tag == "Ground") {
             isOnGround = true;
             print("player has hit the ground");
         }

     }
 }

Body:
Do not play with rigidbody in Update method. Use FixedUpdate() instead.
In addition, do not change velocity using rb.velocity = ... but use rigibody.AddForce() method. Try something like this:

 void FixedUpdate() //using rigidbody? => ONLY FIXEDUPDATE
     {
         horizontalInput = Input.GetAxis("Horizontal");
         verticalInput = Input.GetAxis("Vertical");
         playerFacingAngleY += horizontalInput * turnSpeed;
         Vector3 playerFacingDirection = new Vector3(0, playerFacingAngleY, 0);
         playerBody.rotation = Quaternion.Euler(playerFacingDirection);
         float moveDirectionX = (FocalPoint.transform.position.x - gameObject.transform.position.x) *speed * verticalInput * Time.deltaTime;
         float moveDirectionZ = (FocalPoint.transform.position.z - gameObject.transform.position.z) * speed * verticalInput * Time.deltaTime;
         Vector3 moveDirection = new Vector3(moveDirectionX, 0.0f, moveDirectionZ); //0.0f - just turn on gravity in rigidbody component or you can change it if you want some additional Vertical force
         playerBody.AddForce(moveDirection, ForceMode.VelocityChange); //force mode change to whatever you want

         if (Input.GetKeyDown(KeyCode.Space) && isOnGround == true)
         {
             playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
             isOnGround = false;
             print("player has jumped");
         }
     }


问:
How to use round_sum in Python?
In pycharm the outputs are coming back correctly but when I execute in codingbat some test cases provide the wrong answer.

round_sum(16, 17, 18) → 60

round_sum(12, 13, 14) → 30

My code:

```<code>def round_sum(a, b, c):
  return round10(a) + round10(b) + round10(c)

def round10(num):
  n=int(len(str(num))-1)
  if num >=5 and num <=10:
    return 10
  elif num >=1 and num <5:
    return 0
  elif num%10**n >= 5:
    return int(math.ceil(num / (10 ** n)) * 10)
  else:
    return int(math.floor(num / (10 ** n)) * 10)
</code>```

答:
I tried this code and it works perfectly fine it uses round function of python but if you're asking this question specifically as an answer to the coding bat problem then this code will not work there maybe because in that question you are asked to use a different helping function.</p>

```<code>def round_sum(a, b, c):
    sum = 0
    for i in [a,b,c]:
        num = 10*round(i/10)
        sum += num
return int(sum)
</code>```

Title: How to use round_sum in Python?

Body:
In pycharm the outputs are coming back correctly but when I execute in codingbat some test cases provide the wrong answer.

round_sum(16, 17, 18) → 60

round_sum(12, 13, 14) → 30

My code:

def round_sum(a, b, c):
  return round10(a) + round10(b) + round10(c)

def round10(num):
  n=int(len(str(num))-1)
  if num >=5 and num <=10:
    return 10
  elif num >=1 and num <5:
    return 0
  elif num%10**n >= 5:
    return int(math.ceil(num / (10 ** n)) * 10)
  else:
    return int(math.floor(num / (10 ** n)) * 10)

Body:
I tried this code and it works perfectly fine it uses round function of python but if you're asking this question specifically as an answer to the coding bat problem then this code will not work there maybe because in that question you are asked to use a different helping function.

def round_sum(a, b, c):
    sum = 0
    for i in [a,b,c]:
        num = 10*round(i/10)
        sum += num
return int(sum)


问:
Splitwise Create expense not reflected
I have been trying to create and expense entry in splitwise from my application using splitwise API (https://secure.splitwise.com/api/v3.0/create_expense).

Authentication : OAuth1.0

Request:

```<code>API: create_expense
request body:
{
 payment:false,
 cost: 100.00,
 description:”test”,
 users__0__user_id: current user id,
 users__0__paid_share:100.00,
 users__0__owed_share:50.00,
 users__1__user_id:friend user id,
 users__1__paid_share: 0.00,
 users__1__owed_share:50.00
}
</code>```

Response:

Create query called successfully, got response 200. But the expense is not reflecting in Splitwise.

答:
There could be some validation errors at Splitwise API service side. In that case, the reponse is 200 OK but the response body contains the error.

Please refer to Splitwise API documentation errors. https://dev.splitwise.com/#errors

Title: Splitwise Create expense not reflected

Body:
I have been trying to create and expense entry in splitwise from my application using splitwise API (https://secure.splitwise.com/api/v3.0/create_expense).

Authentication : OAuth1.0

Request:

API: create_expense
request body:
{
 payment:false,
 cost: 100.00,
 description:”test”,
 users__0__user_id: current user id,
 users__0__paid_share:100.00,
 users__0__owed_share:50.00,
 users__1__user_id:friend user id,
 users__1__paid_share: 0.00,
 users__1__owed_share:50.00
}

Response:

Create query called successfully, got response 200. But the expense is not reflecting in Splitwise.


问:
how to make a select query with functions pl sql
Function 1:

```<code>create or replace function get_books (l_id in number)
return varchar
is l_return varchar2(100);
begin
select books into l_return from people where id=l_id;
return l_return;
end
/
</code>```

Function 2:

```<code>create or replace function  get_author (l_id in number)
return varchar
is l_return varchar2(100);
begin
select author in l_return from authors where id=l_id;
return l_return;
end
/
</code>```

I want to make a select with 2 functions, I want to display books and authors.
is it possible?

答:
Yes, it is possible. For example:

```<code>select get_books (1) book,
       get_author(1) author
from dual;
</code>```

Presumably, both functions return a single value. If any of those selects (used in functions) returns more than one row, it'll fail.

As of the procedure: code you posted is invalid so I fixed it.

```<code>SQL> create or replace procedure get_categories (l_categories  in     varchar2,
  2                                              l_id          in     number,
  3                                              l_boolean        out boolean,
  4                                              l_error          out varchar2)
  5  is
  6  begin
  7  --   INSERT INTO categories (id, categories)
  8  --        VALUES (l_categories, l_id);
  9
 10     l_boolean := true;
 11     commit;
 12  exception
 13     when others
 14     then
 15        l_boolean := false;
 16        l_error := sqlerrm;
 17  end;
 18  /

Procedure created.
</code>```

As it returns 2 OUT parameters, you have to declare variables to accept those values (v_boolean and v_error). Furthermore, as you can't directly display Boolean value, use CASE and display a string instead.

Procedure can't be called as a function within the SQL SELECT statement so you have to use another PL/SQL piece of code; an anonymous PL/SQL block is OK.

```<code>SQL> set serveroutput on
SQL> declare
  2    v_categories varchar2(10) := 'ABC';
  3    v_id         number := 1;
  4    v_boolean    boolean;
  5    v_error      varchar2(200);
  6  begin
  7    get_categories(l_categories => v_categories,
  8                   l_id         => v_id,
  9                   l_boolean    => v_boolean,
 10                   l_error      => v_error
 11                  );
 12
 13    dbms_output.put_line(case when v_boolean then 'true' else 'false' end ||' - '||
 14                            v_error
 15                           );
 16  end;
 17  /
true -

PL/SQL procedure successfully completed.

SQL>
</code>```

Body:
Function 1:

create or replace function get_books (l_id in number)
return varchar
is l_return varchar2(100);
begin
select books into l_return from people where id=l_id;
return l_return;
end
/

Function 2:

create or replace function  get_author (l_id in number)
return varchar
is l_return varchar2(100);
begin
select author in l_return from authors where id=l_id;
return l_return;
end
/

I want to make a select with 2 functions, I want to display books and authors.
is it possible?

Body:
Yes, it is possible. For example:

select get_books (1) book,
       get_author(1) author
from dual;

Presumably, both functions return a single value. If any of those selects (used in functions) returns more than one row, it'll fail.

As of the procedure: code you posted is invalid so I fixed it.

SQL> create or replace procedure get_categories (l_categories  in     varchar2,
  2                                              l_id          in     number,
  3                                              l_boolean        out boolean,
  4                                              l_error          out varchar2)
  5  is
  6  begin
  7  --   INSERT INTO categories (id, categories)
  8  --        VALUES (l_categories, l_id);
  9
 10     l_boolean := true;
 11     commit;
 12  exception
 13     when others
 14     then
 15        l_boolean := false;
 16        l_error := sqlerrm;
 17  end;
 18  /

Procedure created.

As it returns 2 OUT parameters, you have to declare variables to accept those values (v_boolean and v_error). Furthermore, as you can't directly display Boolean value, use CASE and display a string instead.

Procedure can't be called as a function within the SQL SELECT statement so you have to use another PL/SQL piece of code; an anonymous PL/SQL block is OK.

SQL> set serveroutput on
SQL> declare
  2    v_categories varchar2(10) := 'ABC';
  3    v_id         number := 1;
  4    v_boolean    boolean;
  5    v_error      varchar2(200);
  6  begin
  7    get_categories(l_categories => v_categories,
  8                   l_id         => v_id,
  9                   l_boolean    => v_boolean,
 10                   l_error      => v_error
 11                  );
 12
 13    dbms_output.put_line(case when v_boolean then 'true' else 'false' end ||' - '||
 14                            v_error
 15                           );
 16  end;
 17  /
true -

PL/SQL procedure successfully completed.

SQL>


问:
Unexpected behavior from python tkinter double click bind
I wrote the following program intended to create a 3x3 grid of entry widgets which, when double clicked, toggle between white and black.

```<code>from tkinter import *

root = Tk()

temp = None

def changeColor(event, e):
    print("id(e) =", id(e))
    if e['bg'] == 'white':
        e['bg'] = 'black'
    elif e['bg'] == 'black':
        e['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', bd=0, borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()
</code>```

The grid creation works great but the toggling is misbehaving. Regardless of which of the entries you double click, its always the bottom right entry (the last one added in the loop) which is toggled.

The output in the terminal is

```<code>id(e) = 4376431536
id(e) = 4376431536
id(e) = 4376431536
...
</code>```

I'm very confused. In the bind statements we create a new specialised lambda for each of the entries and pass a reference to the relevant entry. Why is this happening??????

I found a work around, changing the bind function to

```<code>def changeColor(event, e):
    e2 = event.widget
    if e2['bg'] == 'white':
        e2['bg'] = 'black'
    elif e2['bg'] == 'black':
        e2['bg'] = 'white'
</code>```

I'm not asking for a solution to my issue, but asking for an explanation of why it is happening.

答:
I didn't quite know what to search for when I posted this question. It turns out that it has been (indirectly) answered across a number of other posts, which I gather here as a reference. These helped me understand what it going on (even though the why and precise how are still very mysterious):

For the following discussion the following code example is enlightening and easier than my original question:

```<code>funcs = []

for x in range(0, 3):
    funcs.append(lambda: x)

for f in funcs:
    print(f())

x = 5

for f in funcs:
    print(f())

- 2
- 2
- 2
- 5
- 5
- 5
</code>```

To blow my/your brain even more, consider that the above code example still works if you bind everything in a function:

```<code>funcs = []

def foo(i):
    for x in range(i, i+3):
        funcs.append(lambda: x)

foo(0)

for f in funcs:
    print(f())

- 2
- 2
- 2
</code>```

Even though the variable e intuitively should disappear once the function exits (meaning that even if the lambdas were looking up e in the local namespace - well, that namespace no longer exists).

While I know it won't stop future curious individuals like myself, let me state my opinion that trying to understand what's going on here is far more trouble than its worth. My conclusion from several hours of googling and reading is that I will inevitably mess up any attempt I make at storing lambdas (explicitly, or implicitly like above), and that trying to do so will result in unexpected behaviour and (incredibly) difficult behaviour to decipher.

https://www.python.org/dev/peps/pep-0227/

Why aren't python nested functions called closures?

What is a cell in the context of an interpreter or compiler?

Modify bound variables of a closure in Python

https://eev.ee/blog/2011/04/24/gotcha-python-scoping-closures/

How do lexical closures work?

What is the difference between Early and Late Binding?

http://calculist.blogspot.com/2006/05/late-and-early-binding.html

Why results of map() and list comprehension are different?

http://lambda-the-ultimate.org/node/2648

AttributeError: 'function' object has no attribute 'func_name' and python 3

http://zetcode.com/python/python-closures/

My brief (probably wildly wrong) summary of what's going on (hopefully it at least gives you a mental model with which to reason):

In the function foo above, when we create a lambda it doesn't store the value of x (like it would in e.g. SML) but rather, x. When the lambda is later called, x is looked up in the local namespace (like any usual variable lookup).

This is what we see in example 2. x persists in the namespace and can be modified, which modifies future invocations of the lambdas.

Example 2 is even trickier (urgh!). Since the variable x disappears once foo completes, one might think that the lambdas would be 'broken'. To avoid this, what python seems to do is lookahead and realise that persistent functions being created reference local variables in foo that will soon no longer be available. What it does is create a 'lexical closure' which stores the relevant local state so that the lambdas have access to the variable x even after foo terminates.

You can see that all lambdas reference the same closure:

```<code>for f in funcs:
    print(f.__closure__)
    print(f.__code__.co_freevars)

(<cell at 0x10ebaa310: int object at 0x10e92bac0>,)
('x',)
(<cell at 0x10ebaa310: int object at 0x10e92bac0>,)
('x',)
(<cell at 0x10ebaa310: int object at 0x10e92bac0>,)
('x',)
</code>```

which is what leads me to believe that some sort of lookahead is occurring.

Supposedly this is done to allow later modifications of the functions. I have been unable to determine whether that is only in example 1 where you still have access to the variable, or in general through e.g. some dunder attribute. There is a discussion about this in the "Modify bound variables...." link.

If you do insist on using lambdas like above, what you can do is replace

```<code>e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
</code>```

with

```<code>e.bind('<Double-Button-1>', lambda x, e=e: changeColor(x, e))
</code>```

What's happening here is that we are giving the lambda a default value (forcing dereference of the name e) which then leads the expected more intuitive result.

Again, just avoid the headache.

Body:
I wrote the following program intended to create a 3x3 grid of entry widgets which, when double clicked, toggle between white and black.

from tkinter import *

root = Tk()

temp = None

def changeColor(event, e):
    print("id(e) =", id(e))
    if e['bg'] == 'white':
        e['bg'] = 'black'
    elif e['bg'] == 'black':
        e['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', bd=0, borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()

The grid creation works great but the toggling is misbehaving. Regardless of which of the entries you double click, its always the bottom right entry (the last one added in the loop) which is toggled.

The output in the terminal is

id(e) = 4376431536
id(e) = 4376431536
id(e) = 4376431536
...

I'm very confused. In the bind statements we create a new specialised lambda for each of the entries and pass a reference to the relevant entry. Why is this happening??????

I found a work around, changing the bind function to

def changeColor(event, e):
    e2 = event.widget
    if e2['bg'] == 'white':
        e2['bg'] = 'black'
    elif e2['bg'] == 'black':
        e2['bg'] = 'white'

I'm not asking for a solution to my issue, but asking for an explanation of why it is happening.

Body:
I didn't quite know what to search for when I posted this question. It turns out that it has been (indirectly) answered across a number of other posts, which I gather here as a reference. These helped me understand what it going on (even though the why and precise how are still very mysterious):

For the following discussion the following code example is enlightening and easier than my original question:

funcs = []

for x in range(0, 3):
    funcs.append(lambda: x)

for f in funcs:
    print(f())

x = 5

for f in funcs:
    print(f())

- 2
- 2
- 2
- 5
- 5
- 5

To blow my/your brain even more, consider that the above code example still works if you bind everything in a function:

funcs = []

def foo(i):
    for x in range(i, i+3):
        funcs.append(lambda: x)

foo(0)

for f in funcs:
    print(f())

- 2
- 2
- 2

Even though the variable e intuitively should disappear once the function exits (meaning that even if the lambdas were looking up e in the local namespace - well, that namespace no longer exists).

While I know it won't stop future curious individuals like myself, let me state my opinion that trying to understand what's going on here is far more trouble than its worth. My conclusion from several hours of googling and reading is that I will inevitably mess up any attempt I make at storing lambdas (explicitly, or implicitly like above), and that trying to do so will result in unexpected behaviour and (incredibly) difficult behaviour to decipher.

https://www.python.org/dev/peps/pep-0227/

Why aren't python nested functions called closures?

What is a cell in the context of an interpreter or compiler?

Modify bound variables of a closure in Python

https://eev.ee/blog/2011/04/24/gotcha-python-scoping-closures/

How do lexical closures work?

What is the difference between Early and Late Binding?

http://calculist.blogspot.com/2006/05/late-and-early-binding.html

Why results of map() and list comprehension are different?

http://lambda-the-ultimate.org/node/2648

AttributeError: 'function' object has no attribute 'func_name' and python 3

http://zetcode.com/python/python-closures/

My brief (probably wildly wrong) summary of what's going on (hopefully it at least gives you a mental model with which to reason):

In the function foo above, when we create a lambda it doesn't store the value of x (like it would in e.g. SML) but rather, x. When the lambda is later called, x is looked up in the local namespace (like any usual variable lookup).

This is what we see in example 2. x persists in the namespace and can be modified, which modifies future invocations of the lambdas.

Example 2 is even trickier (urgh!). Since the variable x disappears once foo completes, one might think that the lambdas would be 'broken'. To avoid this, what python seems to do is lookahead and realise that persistent functions being created reference local variables in foo that will soon no longer be available. What it does is create a 'lexical closure' which stores the relevant local state so that the lambdas have access to the variable x even after foo terminates.

You can see that all lambdas reference the same closure:

for f in funcs:
    print(f.__closure__)
    print(f.__code__.co_freevars)

(<cell at 0x10ebaa310: int object at 0x10e92bac0>,)
('x',)
(<cell at 0x10ebaa310: int object at 0x10e92bac0>,)
('x',)
(<cell at 0x10ebaa310: int object at 0x10e92bac0>,)
('x',)

which is what leads me to believe that some sort of lookahead is occurring.

Supposedly this is done to allow later modifications of the functions. I have been unable to determine whether that is only in example 1 where you still have access to the variable, or in general through e.g. some dunder attribute. There is a discussion about this in the "Modify bound variables...." link.

If you do insist on using lambdas like above, what you can do is replace

e.bind('<Double-Button-1>', lambda x: changeColor(x, e))

with

e.bind('<Double-Button-1>', lambda x, e=e: changeColor(x, e))

What's happening here is that we are giving the lambda a default value (forcing dereference of the name e) which then leads the expected more intuitive result.

Again, just avoid the headache.


问:
Why I can't connect to mysql docker container through JDBC with another database user than root?
I am using official docker container from mysql.

I've run docker container with this commands]:

```<code>sudo docker run -d --name desarrollo -p 3306:3306 -h localhost -e MYSQL_ROOT_PASSWORD=admin --mount src=mysql-desarrollo,dst=/var/lib/mysql mysq
</code>```

Then I connected:

```<code>sudo docker exec -it desarrollo mysql -u root -p
</code>```

It worked. Althougth I don't know why I have a root user with host '%'

```<code>mysql> select user, host from mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| root             | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)
</code>```

Then I performed these sentences for create a database and its user:

```<code>create database my_database CHARACTER SET utf8 COLLATE utf8_bin;
create user 'my_user'@'localhost' identified by 'my_password';
grant ALL PRIVILEGES ON *.* TO 'my_user'@'localhost';
</code>```

I asignned all privileges because when I only asignned privileges over my created database it didn't work.

Now, When I  try to connect with my_user user through JDB it doesn't work but with root user it works (It was tested with internal client on Intellij IDE). This the JDBC url:

```<code>jdbc:mysql://localhost:3306/my_database
</code>```

Thanks in advance for your help!

答:
This might be because your my_user is allowed to access from localhost. But this is referred to localhost inside the docker container. But you're trying to access from the host PC. So replacing it with your PC IP address or using wild card would work.

```<code>create user 'my_user'@'%' identified by 'my_password';
</code>```

Body:
I am using official docker container from mysql.

I've run docker container with this commands]:

sudo docker run -d --name desarrollo -p 3306:3306 -h localhost -e MYSQL_ROOT_PASSWORD=admin --mount src=mysql-desarrollo,dst=/var/lib/mysql mysq

Then I connected:

sudo docker exec -it desarrollo mysql -u root -p

It worked. Althougth I don't know why I have a root user with host '%'

mysql> select user, host from mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| root             | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)

Then I performed these sentences for create a database and its user:

create database my_database CHARACTER SET utf8 COLLATE utf8_bin;
create user 'my_user'@'localhost' identified by 'my_password';
grant ALL PRIVILEGES ON *.* TO 'my_user'@'localhost';

I asignned all privileges because when I only asignned privileges over my created database it didn't work.

Now, When I  try to connect with my_user user through JDB it doesn't work but with root user it works (It was tested with internal client on Intellij IDE). This the JDBC url:

jdbc:mysql://localhost:3306/my_database

Thanks in advance for your help!

Body:
This might be because your my_user is allowed to access from localhost. But this is referred to localhost inside the docker container. But you're trying to access from the host PC. So replacing it with your PC IP address or using wild card would work.

create user 'my_user'@'%' identified by 'my_password';


问:
Mysql AFTER UPDATE trigger with IF-THEN condition, but no data insertion
I created the following AFTER UPDATE trigger on the table manage_transaction using IF-THEN condition in order to insert the specific data into the table  manage_site_income_details   BUT, neither a single row is inserted into manage_site_income_details nor any error encounters. However, I modified my IF-THEN condition many times, but no success.

```<code>DROP TRIGGER IF EXISTS
        `upon_subscription_payment`;
CREATE DEFINER = `test-db-ru-admin`@`%` TRIGGER `upon_subscription_payment`
AFTER UPDATE
    ON
        `manage_transaction`
FOR EACH ROW
    IF
       OLD.about LIKE 'SUB' AND NEW.status = 'Completed'
    THEN
    INSERT INTO
                manage_site_income_details
    VALUES(
        NULL,
        OLD.t_id,
        OLD.txn_id,
        'SUB_Fee',
        OLD.fee,
        NOW());
    END IF
</code>```

答:
No problem here or https://www.db-fiddle.com/f/8UYVnC2xQsWuSC9VBZz6BN/0</p>

```<code>DROP TRIGGER IF EXISTS T;
drop table if exists `manage_transaction`,manage_site_income_details;
create table manage_transaction(t_id int,txn_id int,fee int,about varchar(3),status varchar(15));
create table manage_site_income_details(id int,t_id int,txn_id int,txt varchar(20),fee int,dt datetime);
insert into manage_transaction values (1,1,10,'sub',null);

CREATE  TRIGGER T
AFTER UPDATE ON `manage_transaction`
FOR EACH ROW
    IF OLD.about LIKE 'SUB' AND NEW.status = 'Completed' THEN
       INSERT INTO manage_site_income_details
       VALUES(
        NULL,
        OLD.t_id,
        OLD.txn_id,
        'SUB_Fee',
        OLD.fee,
        NOW());
    END IF;

update manage_transaction
    set status = 'completed';

select * from manage_site_income_details;

+------+------+--------+---------+------+---------------------+
| id   | t_id | txn_id | txt     | fee  | dt                  |
+------+------+--------+---------+------+---------------------+
| NULL |    1 |      1 | SUB_Fee |   10 | 2020-05-29 09:58:04 |
+------+------+--------+---------+------+---------------------+
1 row in set (0.001 sec)
</code>```

Body:
I created the following AFTER UPDATE trigger on the table manage_transaction using IF-THEN condition in order to insert the specific data into the table  manage_site_income_details   BUT, neither a single row is inserted into manage_site_income_details nor any error encounters. However, I modified my IF-THEN condition many times, but no success.

DROP TRIGGER IF EXISTS
        `upon_subscription_payment`;
CREATE DEFINER = `test-db-ru-admin`@`%` TRIGGER `upon_subscription_payment`
AFTER UPDATE
    ON
        `manage_transaction`
FOR EACH ROW
    IF
       OLD.about LIKE 'SUB' AND NEW.status = 'Completed'
    THEN
    INSERT INTO
                manage_site_income_details
    VALUES(
        NULL,
        OLD.t_id,
        OLD.txn_id,
        'SUB_Fee',
        OLD.fee,
        NOW());
    END IF

Body:
No problem here or https://www.db-fiddle.com/f/8UYVnC2xQsWuSC9VBZz6BN/0

DROP TRIGGER IF EXISTS T;
drop table if exists `manage_transaction`,manage_site_income_details;
create table manage_transaction(t_id int,txn_id int,fee int,about varchar(3),status varchar(15));
create table manage_site_income_details(id int,t_id int,txn_id int,txt varchar(20),fee int,dt datetime);
insert into manage_transaction values (1,1,10,'sub',null);

CREATE  TRIGGER T
AFTER UPDATE ON `manage_transaction`
FOR EACH ROW
    IF OLD.about LIKE 'SUB' AND NEW.status = 'Completed' THEN
       INSERT INTO manage_site_income_details
       VALUES(
        NULL,
        OLD.t_id,
        OLD.txn_id,
        'SUB_Fee',
        OLD.fee,
        NOW());
    END IF;

update manage_transaction
    set status = 'completed';

select * from manage_site_income_details;

+------+------+--------+---------+------+---------------------+
| id   | t_id | txn_id | txt     | fee  | dt                  |
+------+------+--------+---------+------+---------------------+
| NULL |    1 |      1 | SUB_Fee |   10 | 2020-05-29 09:58:04 |
+------+------+--------+---------+------+---------------------+
1 row in set (0.001 sec)


问:
Can you run After Effects on Azure Batch?
I am wondering if it is possible to install Adobe After Effects as an 'application' in Azure batch. If so does anyone know how to do it?</p>

答:
I've not tried it yet. I did do some research around this though and it looks possible.

It appears we need:

A VM image (like these prebuilt images)

Containing aerender.exe

With a blank file called ae_render_only_node.txt

in C:Users/Public/Public Documents/Adobe (to enable non-royalty bearing mode)

It looks like a user did it here, though not specifically in Azure Batch.


问:
What's the best way to segment a data by dates
As the title says

consider dummy data like this (some users in my mongoose database)

```<code>[{ name : "ahmed" , registeredIn : 1590739626724 },
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }]
</code>```

in my admin panel , I'd like to return a chart which display number of registered users per each month

just need numbers , 2 in May , 3 in June and so on..

what's the quickest solutions ?

the only solution in my mind now is a bit bad

to fetch each month separately

fetch users between timestamp X & Y

fetch users between timestamp X & Y

fetch users between timestamp X & Y

fetch users between timestamp X & Y

what if I want to fetch about 20 months , will I call the MongoDB 20 times ?

is there any more better solution ?

答:
try using momentJS

```<code>npm install moment --save   # npm
yarn add moment             # Yarn
</code>```

then when you create new user add a new prop in your mongoose schema for creation date

```<code>var UserSchema = new mongoose.Schema({
   // your fields
   creation_date:{type:String}
})
UserSchema.methods.preSaveMethod = function(){
 this.creation_date = moment().format('MMMM Do YYYY, h:mm:ss a');
}
UserSchema.pre("save", preSaveMethod);
</code>```

although you can discard moment library here but it is much easier to use it than regex for example
if you want to get a month earlier try

```<code>moment().subtract(1, 'months').format('MMM YYYY');
</code>```

hope I made it clear enough for you

Body:
As the title says

consider dummy data like this (some users in my mongoose database)

[{ name : "ahmed" , registeredIn : 1590739626724 },
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }]

in my admin panel , I'd like to return a chart which display number of registered users per each month

just need numbers , 2 in May , 3 in June and so on..

what's the quickest solutions ?

the only solution in my mind now is a bit bad

to fetch each month separately

fetch users between timestamp X & Y

fetch users between timestamp X & Y

fetch users between timestamp X & Y

fetch users between timestamp X & Y

what if I want to fetch about 20 months , will I call the MongoDB 20 times ?

is there any more better solution ?

Body:
try using momentJS

npm install moment --save   # npm
yarn add moment             # Yarn

then when you create new user add a new prop in your mongoose schema for creation date

var UserSchema = new mongoose.Schema({
   // your fields
   creation_date:{type:String}
})
UserSchema.methods.preSaveMethod = function(){
 this.creation_date = moment().format('MMMM Do YYYY, h:mm:ss a');
}
UserSchema.pre("save", preSaveMethod);

although you can discard moment library here but it is much easier to use it than regex for example
if you want to get a month earlier try

moment().subtract(1, 'months').format('MMM YYYY');

hope I made it clear enough for you


问:
Filter out FASTA files by specified sequence length in bash
There's a FASTA file assembly.fasta containing contig names and corresponding sequences:

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
>contig_3
CGTGATCTCGCCATTCGTGCCG
</code>```

I want to get only contigs longer than 30 letters and get a new FASTA file assembly.filtered.fasta containing only those long sequences with contig names, in this format:

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
</code>```

答:
A very quick way to achieve what you are after is:

```<code>awk -v n=30 '/^>/{ if(l>n) print b; b=$0;l=0;next }
            {l+=length;b=b ORS $0}END{if(l>n) print b }' file
</code>```

You might be also interested in BioAwk, it is an adapted version of awk which is tuned to process FASTA files

```<code>bioawk -c fastx -v '(length($seq)>30){print ">" $name ORS $seq}' file.fasta
</code>```

Note: BioAwk is based on Brian Kernighan's awk which is documented in "The AWK Programming Language",
by Al Aho, Brian Kernighan, and Peter Weinberger
(Addison-Wesley, 1988, ISBN 0-201-07981-X)
. I'm not sure if this version is compatible with POSIX.

Body:
There's a FASTA file assembly.fasta containing contig names and corresponding sequences:

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
>contig_3
CGTGATCTCGCCATTCGTGCCG

I want to get only contigs longer than 30 letters and get a new FASTA file assembly.filtered.fasta containing only those long sequences with contig names, in this format:

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA

Body:
A very quick way to achieve what you are after is:

awk -v n=30 '/^>/{ if(l>n) print b; b=$0;l=0;next }
            {l+=length;b=b ORS $0}END{if(l>n) print b }' file

You might be also interested in BioAwk, it is an adapted version of awk which is tuned to process FASTA files

bioawk -c fastx -v '(length($seq)>30){print ">" $name ORS $seq}' file.fasta

Note: BioAwk is based on Brian Kernighan's awk which is documented in "The AWK Programming Language",
by Al Aho, Brian Kernighan, and Peter Weinberger
(Addison-Wesley, 1988, ISBN 0-201-07981-X)
. I'm not sure if this version is compatible with POSIX.


问:
Avoiding undefined behaviour: temporary objects
I've written a class for using it as a convenient view e.g. in range-based fors. Overall, it is just a pair of iterators with bound checking:

```<code>template<typename I> class Range {
private:
  I begin;
  I end;

public:
  Range(I const begin, I const end)
    : begin(begin), end(end)
  {}

  Range<I>& skip(int const amount) {
    begin = std::min(begin + amount, end);
    return *this;
  }
};

template<typename C> auto whole(C const& container) {
  using Iterator = decltype(std::begin(container));
  return Range<Iterator>(std::begin(container), std::end(container));
}
</code>```

Here's the intended usage of it (which led to UB):

```<code>std::vector<int> const vector{1, 2, 3};
for (int const value : whole(vector).skip(1)) {
  std::cout << value << ' ';
}
</code>```

Removing the skip(1) part helps, same about the following refactoring of Range::skip:

```<code>Range<I> skip(int const amount) const {
  I const new_begin = std::min(begin + amount, end);
  return Range<I>(new_begin, end);
}
</code>```

It seems like a temporary mustn't return a reference to itself. Here's what cppreference says:

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

Though I'm not sure it's the case and I don't now how to interpret it practically. What's the actual problem and how can I reliably avoid such UB? Are alike expressions e.g. auto string = std::string("abc").append("def") also unsafe?

答:
A range-for holds a reference to the range. Your example

```<code>for (int const value : whole(vector).skip(1)) {
  std::cout << value << ' ';
}
</code>```

is defined to be equivalent to

```<code>{
    auto && __range = whole(vector).skip(1);
    auto __begin = __range.begin();
    auto __end = __range.end();
    for ( ; __begin != __end; ++__begin) {
        int const value = *__begin;
        std::cout << value << ' ';
    }
}
</code>```

The reference returned by skip becomes invalid at the first ;.

Where you are initialising an object, like

```<code>std::string s = std::string("abc").append("def");
</code>```

it is safe, because the temporary only needs to outlive the constructor.

As an aside, I prefer Range skip(int) const over the mutating one.

Body:
I've written a class for using it as a convenient view e.g. in range-based fors. Overall, it is just a pair of iterators with bound checking:

template<typename I> class Range {
private:
  I begin;
  I end;

public:
  Range(I const begin, I const end)
    : begin(begin), end(end)
  {}

  Range& skip(int const amount) {
    begin = std::min(begin + amount, end);
    return *this;
  }
};

template<typename C> auto whole(C const& container) {
  using Iterator = decltype(std::begin(container));
  return Range<Iterator>(std::begin(container), std::end(container));
}

Here's the intended usage of it (which led to UB):

std::vector<int> const vector{1, 2, 3};
for (int const value : whole(vector).skip(1)) {
  std::cout << value << ' ';
}

Removing the skip(1) part helps, same about the following refactoring of Range::skip:

Range skip(int const amount) const {
  I const new_begin = std::min(begin + amount, end);
  return Range(new_begin, end);
}

It seems like a temporary mustn't return a reference to itself. Here's what cppreference says:

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

Though I'm not sure it's the case and I don't now how to interpret it practically. What's the actual problem and how can I reliably avoid such UB? Are alike expressions e.g. auto string = std::string("abc").append("def") also unsafe?

Body:
A range-for holds a reference to the range. Your example

for (int const value : whole(vector).skip(1)) {
  std::cout << value << ' ';
}

is defined to be equivalent to

{
    auto && __range = whole(vector).skip(1);
    auto __begin = __range.begin();
    auto __end = __range.end();
    for ( ; __begin != __end; ++__begin) {
        int const value = *__begin;
        std::cout << value << ' ';
    }
}

The reference returned by skip becomes invalid at the first ;.

Where you are initialising an object, like

std::string s = std::string("abc").append("def");

it is safe, because the temporary only needs to outlive the constructor.

As an aside, I prefer Range<I> skip(int) const over the mutating one.


问:
Python grep and cut
In Linux, it's easy to get certain string by using tools such as grep, cut, or awk.

This show version sample is taken from https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst9300/software/release/16-6/configuration_guide/sys_mgmt/b_166_sys_mgmt_9300_cg/b_166_sys_mgmt_9300_cg_chapter_01.html

```<code>wolf@linux:~$ cat shver
cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S

wolf@linux:~$
</code>```

grep and cut

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2
 C9300-48P
 C9300-48P
wolf@linux:~$
</code>```

Remove extra space (If there's better solution, let me know)

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2
C9300-48P
C9300-48P
wolf@linux:~$
</code>```

Select the 1st output

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2 | head -1
C9300-48P
wolf@linux:~$
</code>```

That was in Linux. I was planning to write similar code in Python.

My attempt which still didn't work at the moment.

Define shver string

```<code>>>> shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
... Processor board ID FCW2049G03S
... 2048K bytes of non-volatile configuration memory.
... 8388608K bytes of physical memory.
... 1638400K bytes of Crash Files at crashinfo:.
... 11264000K bytes of Flash at flash:.
... 0K bytes of WebUI ODM Files at webui:.
... Model Number                       : C9300-48P
...
... Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
... Motherboard Assembly Number        : 73-17956-04
... Motherboard Serial Number          : FOC20465ABU
... Model Revision Number              : P4B
... Motherboard Revision Number        : 04
... Model Number                       : C9300-48P
... System Serial Number               : FCW2049G03S
... '''
>>>
</code>```

verify it

```<code>>>> shver
'cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.\nProcessor board ID FCW2049G03S\n2048K bytes of non-volatile configuration memory.\n8388608K bytes of physical memory.\n1638400K bytes of Crash Files at crashinfo:.\n11264000K bytes of Flash at flash:.\n0K bytes of WebUI ODM Files at webui:.\nModel Number                       : C9300-48P\n\nBase Ethernet MAC Address          : 04:6c:9d:01:3b:80\nMotherboard Assembly Number        : 73-17956-04\nMotherboard Serial Number          : FOC20465ABU\nModel Revision Number              : P4B\nMotherboard Revision Number        : 04\nModel Number                       : C9300-48P\nSystem Serial Number               : FCW2049G03S\n'
>>>
</code>```

create a list

```<code>>>> shver_list = shver.splitlines()
>>> shver_list
['cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.', 'Processor board ID FCW2049G03S', '2048K bytes of non-volatile configuration memory.', '8388608K bytes of physical memory.', '1638400K bytes of Crash Files at crashinfo:.', '11264000K bytes of Flash at flash:.', '0K bytes of WebUI ODM Files at webui:.', 'Model Number                       : C9300-48P', '', 'Base Ethernet MAC Address          : 04:6c:9d:01:3b:80', 'Motherboard Assembly Number        : 73-17956-04', 'Motherboard Serial Number          : FOC20465ABU', 'Model Revision Number              : P4B', 'Motherboard Revision Number        : 04', 'Model Number                       : C9300-48P', 'System Serial Number               : FCW2049G03S']
>>>
</code>```

Next step is to find out if string 'Model Number' is there or not and print out that line

```<code>>>> if 'Model Number' in shver_list:
...     'yes'
... else:
...     'no'
...
'no'
>>>
</code>```

How do I print out the line contains 'Model Number'?

```<code>>>> for i in shver_list:
...     if 'Model Number' in shver_list:
...             i
...
>>>
</code>```

Desired Output

```<code>C9300-48P
</code>```

答:
You could parse the data into a dictionary, that makes it quite easy to access the relevant informations:

```<code>shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S
'''

attributes = {}

for line in shver.splitlines():
    if ':' in line:  # we just take lines that contain a colon
        item, value = line.strip().split(':', 1)  # Split at the first colon!
        attributes[item.strip()] = value.strip()  # remove all whitespaces

print(attributes['Model Number'])
print(attributes['System Serial Number'])
</code>```

Output:

```<code>C9300-48P
FCW2049G03S
</code>```

Title: Python grep and cut

Body:
In Linux, it's easy to get certain string by using tools such as grep, cut, or awk.

This show version sample is taken from https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst9300/software/release/16-6/configuration_guide/sys_mgmt/b_166_sys_mgmt_9300_cg/b_166_sys_mgmt_9300_cg_chapter_01.html

wolf@linux:~$ cat shver
cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S

wolf@linux:~$

grep and cut

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2
 C9300-48P
 C9300-48P
wolf@linux:~$

Remove extra space (If there's better solution, let me know)

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2
C9300-48P
C9300-48P
wolf@linux:~$

Select the 1st output

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2 | head -1
C9300-48P
wolf@linux:~$

That was in Linux. I was planning to write similar code in Python.

My attempt which still didn't work at the moment.

Define shver string

>>> shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
... Processor board ID FCW2049G03S
... 2048K bytes of non-volatile configuration memory.
... 8388608K bytes of physical memory.
... 1638400K bytes of Crash Files at crashinfo:.
... 11264000K bytes of Flash at flash:.
... 0K bytes of WebUI ODM Files at webui:.
... Model Number                       : C9300-48P
...
... Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
... Motherboard Assembly Number        : 73-17956-04
... Motherboard Serial Number          : FOC20465ABU
... Model Revision Number              : P4B
... Motherboard Revision Number        : 04
... Model Number                       : C9300-48P
... System Serial Number               : FCW2049G03S
... '''
>>>

verify it

>>> shver
'cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.\nProcessor board ID FCW2049G03S\n2048K bytes of non-volatile configuration memory.\n8388608K bytes of physical memory.\n1638400K bytes of Crash Files at crashinfo:.\n11264000K bytes of Flash at flash:.\n0K bytes of WebUI ODM Files at webui:.\nModel Number                       : C9300-48P\n\nBase Ethernet MAC Address          : 04:6c:9d:01:3b:80\nMotherboard Assembly Number        : 73-17956-04\nMotherboard Serial Number          : FOC20465ABU\nModel Revision Number              : P4B\nMotherboard Revision Number        : 04\nModel Number                       : C9300-48P\nSystem Serial Number               : FCW2049G03S\n'
>>>

create a list

>>> shver_list = shver.splitlines()
>>> shver_list
['cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.', 'Processor board ID FCW2049G03S', '2048K bytes of non-volatile configuration memory.', '8388608K bytes of physical memory.', '1638400K bytes of Crash Files at crashinfo:.', '11264000K bytes of Flash at flash:.', '0K bytes of WebUI ODM Files at webui:.', 'Model Number                       : C9300-48P', '', 'Base Ethernet MAC Address          : 04:6c:9d:01:3b:80', 'Motherboard Assembly Number        : 73-17956-04', 'Motherboard Serial Number          : FOC20465ABU', 'Model Revision Number              : P4B', 'Motherboard Revision Number        : 04', 'Model Number                       : C9300-48P', 'System Serial Number               : FCW2049G03S']
>>>

Next step is to find out if string 'Model Number' is there or not and print out that line

>>> if 'Model Number' in shver_list:
...     'yes'
... else:
...     'no'
...
'no'
>>>

How do I print out the line contains 'Model Number'?

>>> for i in shver_list:
...     if 'Model Number' in shver_list:
...             i
...
>>>

Desired Output

C9300-48P

Body:
You could parse the data into a dictionary, that makes it quite easy to access the relevant informations:

shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S
'''

attributes = {}

for line in shver.splitlines():
    if ':' in line:  # we just take lines that contain a colon
        item, value = line.strip().split(':', 1)  # Split at the first colon!
        attributes[item.strip()] = value.strip()  # remove all whitespaces

print(attributes['Model Number'])
print(attributes['System Serial Number'])

Output:

C9300-48P
FCW2049G03S


问:
.htaccess - "Too many redirects" when trying to force https
I am trying to force a subfolder (/bbb/) of my root domain to show always as https. Also my .htaccess file take care of the extensions of the pages.

I have put the .htaccess file inside my /bbb/ folder but I get "Too many redirects" when I try to force to connect to https, without it everything works fine.

Whats wrong in my code?

```<code>Options +FollowSymLinks -MultiViews
Options +Indexes
AcceptPathInfo Off
RewriteEngine on
RewriteBase   /

ErrorDocument 404 https://example.co.uk/404page/404.html

#Force from http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} !^bbb.example.co.uk/$
RewriteRule ^(.*)$ https://bbb.example.co.uk/$1 [R=301]

#take off index.html
 RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . http://www.%{HTTP_HOST}%1 [R=301,NE,L]

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]
</code>```

答:
Add X-Forwarded-Proto condition instead

```<code>RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Body:
I am trying to force a subfolder (/bbb/) of my root domain to show always as https. Also my .htaccess file take care of the extensions of the pages.

I have put the .htaccess file inside my /bbb/ folder but I get "Too many redirects" when I try to force to connect to https, without it everything works fine.

Whats wrong in my code?

Options +FollowSymLinks -MultiViews
Options +Indexes
AcceptPathInfo Off
RewriteEngine on
RewriteBase   /

ErrorDocument 404 https://example.co.uk/404page/404.html

#Force from http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} !^bbb.example.co.uk/$
RewriteRule ^(.*)$ https://bbb.example.co.uk/$1 [R=301]

#take off index.html
 RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . http://www.%{HTTP_HOST}%1 [R=301,NE,L]

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]

Body:
Add X-Forwarded-Proto condition instead

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


问:
How can I use the tm_map, removeWords, function with regex values?
I am working with a list of previously clustered re-tweet usernames, which I would like to upload in a Document-Term-Matrix for further comparison per cluster. Each cluster is hereby stored as a seperate document.

Some of the usernames as taken from the original re-tweet data have not been clearly extracted, so that they still contain the phrases @userxxx @user123, etc.

I would now like to clean these remnants using the (tm_map, removeStopwords) function and specify that all words starting with an @ should be removed from my corpus.

The way I imagined that is as follows ("docs" is my previously established VCorpus):

```<code>#clean docs from remaining @retweets
docs <- VCorpus(DirSource(c))

docs <- tm_map(docs, removeWords, regex("@*"))

dtm <- DocumentTermMatrix(docs)
</code>```

However, I am not fully aware if it is possible to establish a regex-value within the removeWords function, and if so, how I would need to do it.

I would be very happy for suggestions on how to deal with this. If I run the code, it does not produce any errors but it also does not produce the expected results.

Thanks in advance!

答:
The solution I have found was now was

```<code>docs <- tm_map(docs, content_transformer(function(x) gsub(x, pattern = "@.*", replacement = "")))
</code>```

It does what I needed.

Body:
I am working with a list of previously clustered re-tweet usernames, which I would like to upload in a Document-Term-Matrix for further comparison per cluster. Each cluster is hereby stored as a seperate document.

Some of the usernames as taken from the original re-tweet data have not been clearly extracted, so that they still contain the phrases @userxxx @user123, etc.

I would now like to clean these remnants using the (tm_map, removeStopwords) function and specify that all words starting with an @ should be removed from my corpus.

The way I imagined that is as follows ("docs" is my previously established VCorpus):

#clean docs from remaining @retweets
docs <- VCorpus(DirSource(c))

docs <- tm_map(docs, removeWords, regex("@*"))

dtm <- DocumentTermMatrix(docs)

However, I am not fully aware if it is possible to establish a regex-value within the removeWords function, and if so, how I would need to do it.

I would be very happy for suggestions on how to deal with this. If I run the code, it does not produce any errors but it also does not produce the expected results.

Thanks in advance!

Body:
The solution I have found was now was

docs <- tm_map(docs, content_transformer(function(x) gsub(x, pattern = "@.*", replacement = "")))

It does what I needed.