问:
Want to create a multi dimension array in codeigniter like below array given
I want the array format like this

```<code>  Array
    (
        [id] => 34
        [restaurant_name] => Chow Pow
        [state] => Odisha
        [city] => Cuttack
        [address] => Daraghabazar, Kumbhar Sahi
        [logo] => c4ca4238a0b923820dcc509a6f75849b.jpg
        [open_time] => 11:00
        [close_time] => 22:00
        [rating] => 3.5
        [count_rating] => 4
        [restaurant_email] => soumya@oricubetechnology.com
        [service_type] => both
        [status] => approved
        [gst] => 5.6
        [telephone_no] => 0674-23823456
        [postcode] => 2000
        [suburb] => SYDNEY
        [abn] => 12345678901
        [restaurant_id] => 1
        [servicearea_postcode] => 753010
        [servicearea_suburb] => 753010 - Cuttack
        [delivery_time] => 00:45
        [delivery_fee] => 100
        [min_order] => 1000
        [min_order_free] => 500
        [cuisines] => Array
            (
                [0] => Array
                    (
                        [id] => 60
                        [restaurant_id] => 1
                        [dealsin] => Chinese
                    )

            )

        [coupons] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [restaurant_id] => 1
                        [coupon_code] => PURBA100
                        [coupon_discount] => 20
                        [no_of_usage] => 5
                    )

            )

        [categories] => Array
            (
                [menus] => Array
                    (
                        [0] => Array
                            (
                                [id] => 11
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Elaichi Bread Roll
                                [food] => nonveg
                                [food_type] =>
                                [price] => 320.00
                                [restaurant_price] => 20.00
                                [stock_qty] => 20
                                [stock_out_qty] => 19
                                [commission] => 300.00
                                [item_img] => 6512bd43d9caa6e02c990b0a82652dca.jpg
                                [created_date] => 0000-00-00
                            )

                        [1] => Array
                            (
                                [id] => 15
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Bread Crumbsggggg
                                [food] => nonveg
                                [food_type] =>
                                [price] => 0.00
                                [restaurant_price] => 65.00
                                [stock_qty] => 0
                                [stock_out_qty] => 0
                                [commission] => 0.00
                                [item_img] => 9bf31c7ff062936a96d3c8bd1f8f2ff3.jpg
                                [created_date] => 0000-00-00
                            )

                        [2] => Array
                            (
                                [id] => 23
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Chiken Biriyani
                                [food] => egg
                                [food_type] =>
                                [price] => 0.00
                                [restaurant_price] => 300.00
                                [stock_qty] => 0
                                [stock_out_qty] => 0
                                [commission] => 0.00
                                [item_img] => 37693cfc748049e45d87b8c7d8b9aacd.jpg
                                [created_date] => 0000-00-00
                            )

                        [3] => Array
                            (
                                [id] => 24
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Chiken Biriyani1
                                [food] => veg
                                [food_type] =>
                                [price] => 0.00
                                [restaurant_price] => 89.00
                                [stock_qty] => 0
                                [stock_out_qty] => 0
                                [commission] => 0.00
                                [item_img] => 1ff1de774005f8da13f42943881c655f.jpg
                                [created_date] => 0000-00-00
                            )

                        [4] => Array
                            (
                                [id] => 32
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Vege Pie
                                [food] => veg
                                [food_type] =>
                                [price] => 45.00
                                [restaurant_price] => 45.00
                                [stock_qty] => 5
                                [stock_out_qty] => 5
                                [commission] => 0.00
                                [item_img] =>
                                [created_date] => 0000-00-00
                            )

                        [5] => Array
                            (
                                [id] => 34
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Finger bun
                                [food] => veg
                                [food_type] =>
                                [price] => 2.00
                                [restaurant_price] => 2.00
                                [stock_qty] => 1
                                [stock_out_qty] => 1
                                [commission] => 0.00
                                [item_img] =>
                                [created_date] => 0000-00-00
                            )

                    )

            )

    )
</code>```

I have written the code for that but it will show only the last category menu only. I think if I will make concatenate the the array inside the category loop then it will resolve my issue. But I am unable to do that. Below is the controller code

```<code>//To show the result of clicked restaurant from searched restaurant
    public function restaurant_details($restaurant_id)
    {
        $search_suburb = $this->session->userdata('search_suburb');
        $get_restaurant_details = $this->searchRestaurantModel->get_restaurant_details($restaurant_id, $search_suburb);

        $restaurant_details = array();
        foreach($get_restaurant_details as $res_details)
        {
            $get_cus = $this->searchRestaurantModel->get_restaurant_cuisines($res_details['restaurant_id']);
            $get_cup = $this->searchRestaurantModel->get_restaurant_coupons($res_details['restaurant_id']);
            $get_category = $this->searchRestaurantModel->get_restaurant_categories($res_details['restaurant_id']);
            $restaurant_id = $res_details['restaurant_id'];

            $res_details['cuisines'] = $get_cus;
            $res_details['coupons'] = $get_cup;
            $res_details['all_categories'] = $get_category;
            //Category Items name
            $restaurant_menus = array();
            foreach($get_category as $res_category)
            {
                //echo $res_category['cat_name'];
                $get_menu = $this->searchRestaurantModel->get_restaurant_menus($res_category['cat_name'], $res_details['restaurant_id']);

                $res_details['categories']['menus'] = $get_menu;
                //echo "```";
                //print_r($res_details);
                //die();
            }
            array_push($restaurant_details, $res_details);

        }
        echo "```";
        print_r($restaurant_details);
        die();

        //Breadcrumb
        $this->breadcrumbs->push('Home', '/');
        $this->breadcrumbs->push('Search Results', 'restaurants/restaurant_search');
        $this->breadcrumbs->push($res_details['restaurant_name'], '#');

        $data['title'] = $res_details['restaurant_name']. 'Home Delivery in '.$res_details['servicearea_suburb'];
        $data['restaurant_details'] = $restaurant_details;
        $this->load->view('header', $data);
        $this->load->view('restaurants_details');
        $this->load->view('footer');
    }
</code>```

答:
replace code

```<code>$res_details['categories']['menus'] = $get_menu; //---> you miss to add array
</code>```

with following

```<code>$res_details['categories']['menus'][] = $get_menu; //---> now it will store value in array
</code>```

Hope this will work for you. If is there anything else let us know...

ContentLicense: CC BY-SA 4.0

Body:
I want the array format like this

  Array
    (
        [id] => 34
        [restaurant_name] => Chow Pow
        [state] => Odisha
        [city] => Cuttack
        [address] => Daraghabazar, Kumbhar Sahi
        [logo] => c4ca4238a0b923820dcc509a6f75849b.jpg
        [open_time] => 11:00
        [close_time] => 22:00
        [rating] => 3.5
        [count_rating] => 4
        [restaurant_email] => soumya@oricubetechnology.com
        [service_type] => both
        [status] => approved
        [gst] => 5.6
        [telephone_no] => 0674-23823456
        [postcode] => 2000
        [suburb] => SYDNEY
        [abn] => 12345678901
        [restaurant_id] => 1
        [servicearea_postcode] => 753010
        [servicearea_suburb] => 753010 - Cuttack
        [delivery_time] => 00:45
        [delivery_fee] => 100
        [min_order] => 1000
        [min_order_free] => 500
        [cuisines] => Array
            (
                [0] => Array
                    (
                        [id] => 60
                        [restaurant_id] => 1
                        [dealsin] => Chinese
                    )

            )

        [coupons] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [restaurant_id] => 1
                        [coupon_code] => PURBA100
                        [coupon_discount] => 20
                        [no_of_usage] => 5
                    )

            )

        [categories] => Array
            (
                [menus] => Array
                    (
                        [0] => Array
                            (
                                [id] => 11
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Elaichi Bread Roll
                                [food] => nonveg
                                [food_type] =>
                                [price] => 320.00
                                [restaurant_price] => 20.00
                                [stock_qty] => 20
                                [stock_out_qty] => 19
                                [commission] => 300.00
                                [item_img] => 6512bd43d9caa6e02c990b0a82652dca.jpg
                                [created_date] => 0000-00-00
                            )

                        [1] => Array
                            (
                                [id] => 15
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Bread Crumbsggggg
                                [food] => nonveg
                                [food_type] =>
                                [price] => 0.00
                                [restaurant_price] => 65.00
                                [stock_qty] => 0
                                [stock_out_qty] => 0
                                [commission] => 0.00
                                [item_img] => 9bf31c7ff062936a96d3c8bd1f8f2ff3.jpg
                                [created_date] => 0000-00-00
                            )

                        [2] => Array
                            (
                                [id] => 23
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Chiken Biriyani
                                [food] => egg
                                [food_type] =>
                                [price] => 0.00
                                [restaurant_price] => 300.00
                                [stock_qty] => 0
                                [stock_out_qty] => 0
                                [commission] => 0.00
                                [item_img] => 37693cfc748049e45d87b8c7d8b9aacd.jpg
                                [created_date] => 0000-00-00
                            )

                        [3] => Array
                            (
                                [id] => 24
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Chiken Biriyani1
                                [food] => veg
                                [food_type] =>
                                [price] => 0.00
                                [restaurant_price] => 89.00
                                [stock_qty] => 0
                                [stock_out_qty] => 0
                                [commission] => 0.00
                                [item_img] => 1ff1de774005f8da13f42943881c655f.jpg
                                [created_date] => 0000-00-00
                            )

                        [4] => Array
                            (
                                [id] => 32
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Vege Pie
                                [food] => veg
                                [food_type] =>
                                [price] => 45.00
                                [restaurant_price] => 45.00
                                [stock_qty] => 5
                                [stock_out_qty] => 5
                                [commission] => 0.00
                                [item_img] =>
                                [created_date] => 0000-00-00
                            )

                        [5] => Array
                            (
                                [id] => 34
                                [restaurant_id] => 1
                                [cat_name] => Baker's Treat - Breaddd
                                [itemname] => Finger bun
                                [food] => veg
                                [food_type] =>
                                [price] => 2.00
                                [restaurant_price] => 2.00
                                [stock_qty] => 1
                                [stock_out_qty] => 1
                                [commission] => 0.00
                                [item_img] =>
                                [created_date] => 0000-00-00
                            )

                    )

            )

    )

I have written the code for that but it will show only the last category menu only. I think if I will make concatenate the the array inside the category loop then it will resolve my issue. But I am unable to do that. Below is the controller code

//To show the result of clicked restaurant from searched restaurant
    public function restaurant_details($restaurant_id)
    {
        $search_suburb = $this->session->userdata('search_suburb');
        $get_restaurant_details = $this->searchRestaurantModel->get_restaurant_details($restaurant_id, $search_suburb);

        $restaurant_details = array();
        foreach($get_restaurant_details as $res_details)
        {
            $get_cus = $this->searchRestaurantModel->get_restaurant_cuisines($res_details['restaurant_id']);
            $get_cup = $this->searchRestaurantModel->get_restaurant_coupons($res_details['restaurant_id']);
            $get_category = $this->searchRestaurantModel->get_restaurant_categories($res_details['restaurant_id']);
            $restaurant_id = $res_details['restaurant_id'];

            $res_details['cuisines'] = $get_cus;
            $res_details['coupons'] = $get_cup;
            $res_details['all_categories'] = $get_category;
            //Category Items name
            $restaurant_menus = array();
            foreach($get_category as $res_category)
            {
                //echo $res_category['cat_name'];
                $get_menu = $this->searchRestaurantModel->get_restaurant_menus($res_category['cat_name'], $res_details['restaurant_id']);

                $res_details['categories']['menus'] = $get_menu;
                //echo "
";
                //print_r($res_details);
                //die();
            }
            array_push($restaurant_details, $res_details);

        }
        echo "
";
        print_r($restaurant_details);
        die();

        //Breadcrumb
        $this->breadcrumbs->push('Home', '/');
        $this->breadcrumbs->push('Search Results', 'restaurants/restaurant_search');
        $this->breadcrumbs->push($res_details['restaurant_name'], '#');

        $data['title'] = $res_details['restaurant_name']. 'Home Delivery in '.$res_details['servicearea_suburb'];
        $data['restaurant_details'] = $restaurant_details;
        $this->load->view('header', $data);
        $this->load->view('restaurants_details');
        $this->load->view('footer');
    }

Body:
replace code

$res_details['categories']['menus'] = $get_menu; //---> you miss to add array

with following

$res_details['categories']['menus'][] = $get_menu; //---> now it will store value in array

Hope this will work for you. If is there anything else let us know...


来源: stackexchange

问:
How can use mysql DATE_SUB in laravel?
How can use mysql date_sub method in laravel?
In laravel I want to get the value of time property using date_sub.
and I tried the code below but and I can not get anything.</p>

```<code>$notAllowedTime = DB::table('consultant_timings')
     ->where('id',78,DB::raw('DATE_SUB(time2,INTERVAL 30 MINUTE'));
</code>```

答:
You have to use whereRaw to do this

Try like this

```<code>$notAllowedTime = DB::table('consultant_timings')
     ->whereRaw('id =78 AND DATE_SUB(time2,INTERVAL 30 MINUTE'));
</code>```

Modified:-
According to you description (on comment) you want to retrieve value with sub 30 min
Then you can do like this

```<code>$notAllowedTime = DB::table('consultant_timings')
    ->select(['*',DB::raw("DATE_SUB($time2,INTERVAL 30 MINUTE) as time2")])
    ->where('id','=',82)
    ->get();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can use mysql DATE_SUB in laravel?

Body:
How can use mysql date_sub method in laravel?
In laravel I want to get the value of time property using date_sub.
and I tried the code below but and I can not get anything.

$notAllowedTime = DB::table('consultant_timings')
     ->where('id',78,DB::raw('DATE_SUB(time2,INTERVAL 30 MINUTE'));

Body:
You have to use whereRaw to do this

Try like this

$notAllowedTime = DB::table('consultant_timings')
     ->whereRaw('id =78 AND DATE_SUB(time2,INTERVAL 30 MINUTE'));

Modified:-
According to you description (on comment) you want to retrieve value with sub 30 min
Then you can do like this

$notAllowedTime = DB::table('consultant_timings')
    ->select(['*',DB::raw("DATE_SUB($time2,INTERVAL 30 MINUTE) as time2")])
    ->where('id','=',82)
    ->get();


问:
count the number of points at the end of a string
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

```<code>string sample = "This.is.a.sample.string.....";
</code>```

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

```<code>\.*$
</code>```

should be used in such a case.

答:
Start from the end of the string and go back char by char until its not a dot:</p>

```<code>string sample = "This.is.a.sample.string....."
int count = 0;
for (int i = sample.Length - 1; i >= 0; i--)
{
    if (sample[i] != '.') break;
    count++;
}
</code>```

Body:
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

string sample = "This.is.a.sample.string.....";

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

\.*$

should be used in such a case.

Body:
Start from the end of the string and go back char by char until its not a dot:

string sample = "This.is.a.sample.string....."
int count = 0;
for (int i = sample.Length - 1; i >= 0; i--)
{
    if (sample[i] != '.') break;
    count++;
}


问:
C# AppSettingsReader: "reread" values into the AppSettingsReader (runtime)?
In my application, I need to change some value ("Environment") in appSetting of app.config at runtime.

I use AppSettingsReader

```<code>    private static AppSettingsReader _settingReader;

    public static AppSettingsReader SettingReader
    {
        get
        {
            if (_settingReader == null)
            {
                _settingReader = new AppSettingsReader();
            }
            return _settingReader;
        }
    }
</code>```

Then at some stage I do this

```<code>        config.AppSettings.Settings[AppSettingString.Environment.ToString()].Value = newEnvironment.ToString();
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
</code>```

However, next time I try to read "Environment" like this

```<code>       string environment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));
</code>```

I end up with the old value of Environment.

I noticed that I can fix this by doing

```<code>_settingReader = new AppSettingsReader();
</code>```

before I read "Environment".

But I think creating a new instance is not the proper approach.

Maybe there is a way to let my SettingReader know, that the values have changed to use the same instance of it, but with refreshed values?

(Not a project-breaking question obviously, more of an educational one)

OwnerDisplayName: Evgeny

ContentLicense: CC BY-SA 2.5

Body:
In my application, I need to change some value ("Environment") in appSetting of app.config at runtime.

I use AppSettingsReader

    private static AppSettingsReader _settingReader;

    public static AppSettingsReader SettingReader
    {
        get
        {
            if (_settingReader == null)
            {
                _settingReader = new AppSettingsReader();
            }
            return _settingReader;
        }
    }

Then at some stage I do this

        config.AppSettings.Settings[AppSettingString.Environment.ToString()].Value = newEnvironment.ToString();
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

However, next time I try to read "Environment" like this

       string environment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));

I end up with the old value of Environment.

I noticed that I can fix this by doing

_settingReader = new AppSettingsReader();

before I read "Environment".

But I think creating a new instance is not the proper approach.

Maybe there is a way to let my SettingReader know, that the values have changed to use the same instance of it, but with refreshed values?

(Not a project-breaking question obviously, more of an educational one)

Body: System.Configuration.ApplicationSettingsBase.Reload

OwnerDisplayName: Grauenwolf


问:
How to echo all rows (related to DISTINCT)
This is my SQL Fiddle

As you can see here, If I use DISTINCT then, there are 2 problems

1.)Only 1st recommendations_vote_average coloum's number is correct. All other numbers are in wrong order

2.) Only 2 Number get's printed.

If i do not use DISTINCT, all numbers are 7.5 (i.e first vote_average)

How to show all the (10) numbers in correct order?

Expected output

```<code>movie_title       recommendations_vote_average                    recommendations_title
                                                                  The Dark Knight Rises,Batman Begins,Iron Man,The Lord of the Rings: The Return of the King,The Lord of the Rings: The The Fellowship of the Ring,The Lord of the Rings: The Two Towers,The Matrix,Inception,Iron Man 2,Captain America: The First Avenger
The Dark Knight   7.5,7.5,7.3,8.1,8,7.9,7.9,8,6.6,6.6
</code>```

SQL Fiddle Code:

```<code>CREATE TABLE tmdb_movies (
  tmdb_id INTEGER NOT NULL PRIMARY KEY,
  movie_title TEXT NOT NULL
);

INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');

CREATE TABLE recommendations (
  recommendations_tmdb_id INTEGER NOT NULL,
  recommendations_title TEXT NOT NULL,
  recommendations_vote_average TEXT NOT NULL
);

INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average
,GROUP_CONCAT(DISTINCT recommendations.recommendations_title) as recommendations_title
FROM tmdb_movies

LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id=1

GROUP BY tmdb_movies.movie_title
</code>```

答:
It's hard to guess what you want from your question. You mentioned "correct order" without defining it.

You can use GROUP_CONCAT() in these ways.

```<code>GROUP_CONCAT(a.b)  -- gets all the items in column b -- cardinality preserved

GROUP_CONCAT(DISTINCT a.b) -- distinct values in column b -- cardinality reduced

GROUP_CONCAT(a.b ORDER BY a.b) -- all items in b in order

GROUP_CONCAT(DISTINCT a.b ORDER BY a.b) -- distinct items in b in order

GROUP_CONCAT(a.b ORDER BY a.c) -- all items in b in the same order as c
</code>```

I'm not completely sure what it means to an application to add DISTINCT to the last one.

If you're trying to get two concatenated columns in corresponding order, you can't use DISTINCT in either one; DISTINCT has the potential to remove duplicate values.

Your result set column mentions _average. You get an actual average (arithmetic mean) with AVG(value). and that gives a single aggregate number.

If you want a list of scores in one column and a corresponding list of titles in another, try this.

```<code>GROUP_CONCAT(
            recommendations.recommendations_vote_average
   ORDER BY recommendations.recommendations_title
 ) AS recommendations_vote_average,
GROUP_CONCAT(
            recommendations.recommendations_title
   ORDER BY recommendations.recommendations_title
 ) AS recommendations_title
</code>```

That presents the two concatenated lists in order by the title.

You may not be aware of this: rows in DBMS tables have no inherent order. If you say SELECT * FROM table (without an ORDER BY clause) more than once, and the rows come out in the same order each time, it is an accident.   There's nothing in your recommendations table -- no unique id values for example -- to give the order of those items except the scores and the titles. So you may not be able to get the exact order you want.

Many tables contain an autoincrementing id column (but yours does not). Using such an id column in ORDER BY clauses is a way to get repeatable ordering.

Pro tip: Denormalized data (comma separated data in columns, for example) is often considered harmful.  GROUP_CONCAT() turns normalized data, like your input, into denormalized data. So use it sparingly and only when you need it.

Body:
This is my SQL Fiddle

As you can see here, If I use DISTINCT then, there are 2 problems

1.)Only 1st recommendations_vote_average coloum's number is correct. All other numbers are in wrong order

2.) Only 2 Number get's printed.

If i do not use DISTINCT, all numbers are 7.5 (i.e first vote_average)

How to show all the (10) numbers in correct order?

Expected output

movie_title       recommendations_vote_average                    recommendations_title
                                                                  The Dark Knight Rises,Batman Begins,Iron Man,The Lord of the Rings: The Return of the King,The Lord of the Rings: The The Fellowship of the Ring,The Lord of the Rings: The Two Towers,The Matrix,Inception,Iron Man 2,Captain America: The First Avenger
The Dark Knight   7.5,7.5,7.3,8.1,8,7.9,7.9,8,6.6,6.6

SQL Fiddle Code:

CREATE TABLE tmdb_movies (
  tmdb_id INTEGER NOT NULL PRIMARY KEY,
  movie_title TEXT NOT NULL
);

INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');

CREATE TABLE recommendations (
  recommendations_tmdb_id INTEGER NOT NULL,
  recommendations_title TEXT NOT NULL,
  recommendations_vote_average TEXT NOT NULL
);

INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average
,GROUP_CONCAT(DISTINCT recommendations.recommendations_title) as recommendations_title
FROM tmdb_movies

LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id=1

GROUP BY tmdb_movies.movie_title

Body:
It's hard to guess what you want from your question. You mentioned "correct order" without defining it.

You can use GROUP_CONCAT() in these ways.

GROUP_CONCAT(a.b)  -- gets all the items in column b -- cardinality preserved

GROUP_CONCAT(DISTINCT a.b) -- distinct values in column b -- cardinality reduced

GROUP_CONCAT(a.b ORDER BY a.b) -- all items in b in order

GROUP_CONCAT(DISTINCT a.b ORDER BY a.b) -- distinct items in b in order

GROUP_CONCAT(a.b ORDER BY a.c) -- all items in b in the same order as c

I'm not completely sure what it means to an application to add DISTINCT to the last one.

If you're trying to get two concatenated columns in corresponding order, you can't use DISTINCT in either one; DISTINCT has the potential to remove duplicate values.

Your result set column mentions _average. You get an actual average (arithmetic mean) with AVG(value). and that gives a single aggregate number.

If you want a list of scores in one column and a corresponding list of titles in another, try this.

GROUP_CONCAT(
            recommendations.recommendations_vote_average
   ORDER BY recommendations.recommendations_title
 ) AS recommendations_vote_average,
GROUP_CONCAT(
            recommendations.recommendations_title
   ORDER BY recommendations.recommendations_title
 ) AS recommendations_title

That presents the two concatenated lists in order by the title.

You may not be aware of this: rows in DBMS tables have no inherent order. If you say SELECT * FROM table (without an ORDER BY clause) more than once, and the rows come out in the same order each time, it is an accident.   There's nothing in your recommendations table -- no unique id values for example -- to give the order of those items except the scores and the titles. So you may not be able to get the exact order you want.

Many tables contain an autoincrementing id column (but yours does not). Using such an id column in ORDER BY clauses is a way to get repeatable ordering.

Pro tip: Denormalized data (comma separated data in columns, for example) is often considered harmful.  GROUP_CONCAT() turns normalized data, like your input, into denormalized data. So use it sparingly and only when you need it.


问:
AngularJS hiding input field
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?

HTML:

```<code><h2>Welcome to Mail Service</h2>

<form action="/action_page.php">
  <div class="imgcontainer">
    <img src="images/img_avatar2.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
    <label><b>Username</b></label><br>
    <input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
    <label><b>Password</b></label><br>
    <input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>

    <!-- NAME INPUT FIELD -->
    <div class="textField-hidden">
        <label><b>Name</b></label><br>
        <input type="text" placeholder="Enter Name" ng-model="user.name">
    </div><br>

    <button type="submit" ng-click="login()">Login</button><br>
    <button type="submit" ng-click="register()">Register</button>
  </div>

</form>
</code>```

AngularJS Controller:

```<code>app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);
</code>```

答:
You can use a variable for input fields type and hide it

HTML:

```<code><input type="{{type}}" placeholder="Enter Name" ng-model="user.name">
</code>```

JS:

```<code>app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            $scope.type="hidden";
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
           $scope.type="text";
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);
</code>```

An alternative will be to use ng-if or ng-hide/ng-show defined on a $scope variable and trigger a boolean value for this variable according to your needs.

Title: AngularJS hiding input field

Body:
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?

HTML:

Welcome to Mail Service

<form action="/action_page.php">

    Username

    <input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username">

    Password

    <input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password">

        Name

        <input type="text" placeholder="Enter Name" ng-model="user.name">

    <button type="submit" ng-click="login()">Login</button>

    <button type="submit" ng-click="register()">Register</button>

</form>

AngularJS Controller:

app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);

Body:
You can use a variable for input fields type and hide it

HTML:

<input type="{{type}}" placeholder="Enter Name" ng-model="user.name">

JS:

app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            $scope.type="hidden";
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
           $scope.type="text";
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);

An alternative will be to use ng-if or ng-hide/ng-show defined on a $scope variable and trigger a boolean value for this variable according to your needs.


问:
Save kafka broker ids (zookeeper-shell.sh result) to variable in bash script
I want to check if broker id is already in use, but I want to do this within a script.

```<code>./bin/zookeeper-shell.sh localhost:2181 <<< "ls /brokers/ids"
</code>```

Gives the result I want, but how would I save this to a variable for later use? What I'm interested in is the actual result of the "ls ..". The whole output includes some fodder:

```<code>Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is disabled

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
Node does not exist: /brokers/ids
</code>```

If I save the result to a variable I actually only get this fodder and the last line is only printed to the screen.

```<code>var=$(./opt/kafka/bin/zookeeper-shell.sh localhost:2181 <<< "ls /brokers/ids")
</code>```

And then echo $var gives

```<code>Connecting to localhost:2181 Welcome to ZooKeeper! JLine support is disabled WATCHER:: WatchedEvent state:SyncConnected type:None path:null
</code>```

How would I get the actual result of the request to a variable for later use?

答:
You can get the last line of the output using: </p>

```<code>./zookeeper-shell.sh localhost:2181 <<< "ls /brokers/ids" | tail -n 1
</code>```

Body:
I want to check if broker id is already in use, but I want to do this within a script.

./bin/zookeeper-shell.sh localhost:2181 <<< "ls /brokers/ids"

Gives the result I want, but how would I save this to a variable for later use? What I'm interested in is the actual result of the "ls ..". The whole output includes some fodder:

Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is disabled

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
Node does not exist: /brokers/ids

If I save the result to a variable I actually only get this fodder and the last line is only printed to the screen.

var=$(./opt/kafka/bin/zookeeper-shell.sh localhost:2181 <<< "ls /brokers/ids")

And then echo $var gives

Connecting to localhost:2181 Welcome to ZooKeeper! JLine support is disabled WATCHER:: WatchedEvent state:SyncConnected type:None path:null

How would I get the actual result of the request to a variable for later use?

Body:
You can get the last line of the output using:

./zookeeper-shell.sh localhost:2181 <<< "ls /brokers/ids" | tail -n 1


问:
Proper Mutex usage / Good coding style?
Within the following code, the producer periodically_fill_page_queue might add a page to the queue that is currently being consumed (read: in the consumer before the status being_processed is set).

```<code>class Example

  def initialize
    @threads      = ThreadGroup.new
    @page_queue   = Queue.new
    Thread.abort_on_exception = true
  end

  def start
    periodically_fill_page_queue
    periodically_process_page_queue
  end

  def periodically_fill_page_queue
    @threads.add(Thread.new do
      loop do
        if @page_queue.empty?
          Page.with_state(:waiting).each do |p|
            p.queued!
            @page_queue << f
          end
        end
        sleep 2
      end
    end)
  end

  def periodically_process_page_queue
    loop do
      until file = @page_queue.pop
        sleep 2
      end
      page.being_processed
      process(page)
    end
  end

  def process(page)
    sleep 120
    page.processed
  end

end

class Page < ActiveRecord::Base

  state_machine :state, :initial => :waiting do

    event :queued do
      transition :waiting => :queued
    end

    event :being_processed do
      transition :queued => :being_processed
    end

    event :processed do
      transition :being_processed => :processed
    end

  end

end
</code>```

To avoid this, i'd use a Mutex object:

```<code>def initialize
  ...
  @mutex = Mutex.new
end

def periodically_process_page_queue
  loop do
    until file = @page_queue.pop
      sleep 2
    end
    @mutex.synchronize { page.being_processed }
    process(page)
  end
end
</code>```

Is this "good" coding style, or are there any more elegant approaches?

Thanks!

答:
Not with this design. Some alternative designs might do one of the below, but naturally have their own can of worms.

"Fork"

For each job you start a new thread or process, giving it the job

Delegation

Delegate the task to a queue in each thread. Each thread pulls from its own unique queue.

Stride

You have a circular buffer and each thread checks at a different interval. E.G. Num_threads + thread.id
This probably isn't for your situation.

Range

A thread is responsible for a range of jobs. num_threads * thread.id
This probably isn't for your situation.

Title: Proper Mutex usage / Good coding style?

Body:
Within the following code, the producer periodically_fill_page_queue might add a page to the queue that is currently being consumed (read: in the consumer before the status being_processed is set).

class Example

  def initialize
    @threads      = ThreadGroup.new
    @page_queue   = Queue.new
    Thread.abort_on_exception = true
  end

  def start
    periodically_fill_page_queue
    periodically_process_page_queue
  end

  def periodically_fill_page_queue
    @threads.add(Thread.new do
      loop do
        if @page_queue.empty?
          Page.with_state(:waiting).each do |p|
            p.queued!
            @page_queue << f
          end
        end
        sleep 2
      end
    end)
  end

  def periodically_process_page_queue
    loop do
      until file = @page_queue.pop
        sleep 2
      end
      page.being_processed
      process(page)
    end
  end

  def process(page)
    sleep 120
    page.processed
  end

end

class Page < ActiveRecord::Base

  state_machine :state, :initial => :waiting do

    event :queued do
      transition :waiting => :queued
    end

    event :being_processed do
      transition :queued => :being_processed
    end

    event :processed do
      transition :being_processed => :processed
    end

  end

end

To avoid this, i'd use a Mutex object:

def initialize
  ...
  @mutex = Mutex.new
end

def periodically_process_page_queue
  loop do
    until file = @page_queue.pop
      sleep 2
    end
    @mutex.synchronize { page.being_processed }
    process(page)
  end
end

Is this "good" coding style, or are there any more elegant approaches?

Thanks!


问:
CPU usage of diferrent state of wpf application
I have tried to improve the performance of a WPF application. I found when the window is minimized, the CPU usage will reduce to 0 or very little usage, but when the application display in the front end, the CPU usage will increase to 10% or more. Anyone know why?</p>

答:
This happens on all WPF apps. When an app is minimised and the UI is hidden the WPF app is not having to do much unless you have tasks running on a background thread.

WPF can be quite resource intensive and there is a cost to drawing windows and controls. If there is nothing happening in the background of the app and it no longer has to draw any windows/controls then the CPU usage will likely be zero.


问:
whitenoise with zappa, push static files to s3?
I am using WhiteNoise with Zappa.

Zappa suggests to keep project sizes down as size will:

...eat into the memory space of your application function (source)

Indeed with projects over 50MB you need to set slim_handler=true, which has a slight performance loss.

WhiteNoise advises having your static files on your server, and for eg Amazon Cloudfront to access and cache these.

The cache-22 here is that the many versions of the compresed WhiteNoise static files that are created can lead to static packages > 100MB (in my case).

I dont know how to proceed here. The options are:

manually push WhiteNoise's static content to an S3 bucket and have Cloudfront have this as an origin, and dont upload the 100MB to Amazon Lambda.

see if I can get Zappa to bundle out static content to S3 (and remove the static content from the app itself). As Zappa uploads a Zip, perhaps this is a speedier option.

Any thoughts? Thanks.

答:
As per Zappa-django-guide, I moved over to using django-storages (tutorial setting up with zappa).

Whilst I did manage to get WhiteNoise to work with Zappa, our app was very slow. The django-storages solution is zippy!


问:
Put json data pipeline definition using Boto3
I have a data pipeline definition in json format, and I would like to 'put' that using Boto3 in Python.

I know you can do this via the AWS CLI using put-pipeline-definition, but Boto3 (and the AWS API) use a different format, splitting the definition into pipelineObjects, parameterObjects and parameterValues.

Do I need to write code to translate from a json definition to that expected by the API/Boto? If so, is there a library that does this?

答:
You could convert from the Data Pipeline exported JSON format to the pipelineObjects format expected by boto3 using a python function of the following form.</p>

```<code>def convert_to_pipeline_objects(pipeline_definition_dict):
    objects_list = []
    for def_object in pipeline_definition_dict['objects']:
        new_object = {
            'id': def_object['id'],
            'name': def_object['name'],
            'fields': []
        }
        for key in def_object.keys():
            if key in ('id', 'name'):
                continue
            if type(def_object[key]) == dict:
                new_object['fields'].append(
                    {
                        'key': key,
                        'refValue': def_object[key]['ref']
                    }
                )
            else:
                new_object['fields'].append(
                    {
                        'key': key,
                        'stringValue': def_object[key]
                    }
                )
        objects_list.append(new_object)
</code>```

Body:
You could convert from the Data Pipeline exported JSON format to the pipelineObjects format expected by boto3 using a python function of the following form.

def convert_to_pipeline_objects(pipeline_definition_dict):
    objects_list = []
    for def_object in pipeline_definition_dict['objects']:
        new_object = {
            'id': def_object['id'],
            'name': def_object['name'],
            'fields': []
        }
        for key in def_object.keys():
            if key in ('id', 'name'):
                continue
            if type(def_object[key]) == dict:
                new_object['fields'].append(
                    {
                        'key': key,
                        'refValue': def_object[key]['ref']
                    }
                )
            else:
                new_object['fields'].append(
                    {
                        'key': key,
                        'stringValue': def_object[key]
                    }
                )
        objects_list.append(new_object)


问:
Detect a real world object using ARKit and SceneKit
I am new with ARKit and SceneKit frameworks and I want to know if it's possible to detect real world object like a door a wall or something.

For example is it possible to detect an object's collision with a door or any other real world objects?

答:
ARKit can detect planes, but right now only horizontal ones, see this answer here.
Other detections are not part of ARKit.


问:
Logging Framework for the ASP.NET application
My application needs to log informations about user actions (inserts, updates, deletes, etc) and exceptions and i want to store de log on Oracle10, so i'am searching some log framework to use.
I read a little bit about:

1 -Log4Net

2 - Logging Application Block

3 - Elmah

Whats your opinion about these log tools?
Whats a good framework (or way to implement) log on my application?

*After a discussion with the project manager, Logging Application Block
 will be our choice, but, lets comment about this =)

答: Log4net is quiet good, it is basically a version of log4j. Elmah is nice also, especially if you find (like me) that you are unable to write to files on the production environment, since it writes to the DB instead. Also, Elmah is more suited for exception logging, and is cool because it allows you to log based on events. In my projects I normaly deploy both log4net and Elmah</p>


答:
To get the requested result I think all you need to do is to remove DISTINCT, but I would also recommend introducing an ORDER BY

```<code>SELECT
      tmdb_movies.movie_title
    , GROUP_CONCAT(r.recommendations_vote_average
                   ORDER BY r.recommendations_vote_average DESC
                   SEPARATOR ', '
                  ) as recommendations
    , GROUP_CONCAT(r.recommendations_title
                   ORDER BY r.recommendations_vote_average DESC
                   SEPARATOR ', '
                  ) as recommendations
FROM tmdb_movies
LEFT JOIN recommendations r ON r.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=1
GROUP BY tmdb_movies.movie_title
;

              recommendations                |                                 recommendations                                 |
+----+-----------------+----------------------------------------------+---------------------------------------------------------------------------------+
|  1 | The Dark Knight | 8.1, 8, 8, 7.9, 7.9, 7.5, 7.5, 7.3, 6.6, 6.6 | The Lord of the Rings: The Return of the King, Inception,                       |
|    |                 |                                              | The Lord of the Rings: The The Fellowship of the Ring, The Matrix,              |
|    |                 |                                              | The Lord of the Rings: The Two Towers, Batman Begins,                           |
|    |                 |                                              | The Dark Knight Rises, Iron Man, Captain America: The First Avenger, Iron Man 2 |
+----+-----------------+----------------------------------------------+---------------------------------------------------------------------------------+
</code>```

If it were up to me I would be combining the recommendation score with title (manual line breaks added for presentation):

```<code>+----+-----------------+-------------------------------------------------------------------------
|    |   movie_title   |  recommendations                                                                                |
+----+-----------------+-------------------------------------------------------------------------
|  1 | The Dark Knight | 8.1(The Lord of the Rings: The Return of the King);
                       | 8(Inception); 8(The Lord of the Rings: The The Fellowship of the Ring);
                       | 7.9(The Matrix); 7.9(The Lord of the Rings: The Two Towers);
                       | 7.5(Batman Begins); 7.5(The Dark Knight Rises);
                       | 7.3(Iron Man);  6.6(Captain America: The First Avenger);  6.6(Iron Man 2)
</code>```

which was produced by this query:

```<code>SELECT
      tmdb_movies.movie_title
    , GROUP_CONCAT(DISTINCT concat(r.recommendations_vote_average,'(',r.recommendations_title,')')
                   ORDER BY r.recommendations_vote_average DESC
                   SEPARATOR '; '
                  ) as recommendations
FROM tmdb_movies
LEFT JOIN recommendations r ON r.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=1
GROUP BY tmdb_movies.movie_title
</code>```

more info.
The following query reverses the table precedence and doesn't use group_concat

```<code>select
    m.movie_title, r.*
from recommendations r
left join tmdb_movies m  ON r.recommendations_tmdb_id=m.tmdb_id
;
</code>```

Result:

```<code>+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
|    |   movie_title   | recommendations_tmdb_id |                 recommendations_title                 | recommendations_vote_average |
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
|  1 | The Dark Knight |                       1 | The Dark Knight Rises                                 |                          7.5 |
|  2 | The Dark Knight |                       1 | Batman Begins                                         |                          7.5 |
|  3 | The Dark Knight |                       1 | Iron Man                                              |                          7.3 |
|  4 | The Dark Knight |                       1 | The Lord of the Rings: The Return of the King         |                          8.1 |
|  5 | The Dark Knight |                       1 | The Lord of the Rings: The The Fellowship of the Ring |                            8 |
|  6 | The Dark Knight |                       1 | The Lord of the Rings: The Two Towers                 |                          7.9 |
|  7 | The Dark Knight |                       1 | The Matrix                                            |                          7.9 |
|  8 | The Dark Knight |                       1 | Inception                                             |                            8 |
|  9 | The Dark Knight |                       1 | Iron Man 2                                            |                          6.6 |
| 10 | The Dark Knight |                       1 | Captain America: The First Avenger                    |                          6.6 |
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
</code>```

sample data (should have been in question):

```<code>CREATE TABLE tmdb_movies (
  tmdb_id INTEGER NOT NULL PRIMARY KEY,
  movie_title TEXT NOT NULL
);

INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');

CREATE TABLE recommendations (
  recommendations_tmdb_id INTEGER NOT NULL,
  recommendations_title TEXT NOT NULL,
  recommendations_vote_average TEXT NOT NULL
);

INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');
</code>```

Title: How to echo all rows (related to DISTINCT)

Body:
To get the requested result I think all you need to do is to remove DISTINCT, but I would also recommend introducing an ORDER BY

SELECT
      tmdb_movies.movie_title
    , GROUP_CONCAT(r.recommendations_vote_average
                   ORDER BY r.recommendations_vote_average DESC
                   SEPARATOR ', '
                  ) as recommendations
    , GROUP_CONCAT(r.recommendations_title
                   ORDER BY r.recommendations_vote_average DESC
                   SEPARATOR ', '
                  ) as recommendations
FROM tmdb_movies
LEFT JOIN recommendations r ON r.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=1
GROUP BY tmdb_movies.movie_title
;

              recommendations                |                                 recommendations                                 |
+----+-----------------+----------------------------------------------+---------------------------------------------------------------------------------+
|  1 | The Dark Knight | 8.1, 8, 8, 7.9, 7.9, 7.5, 7.5, 7.3, 6.6, 6.6 | The Lord of the Rings: The Return of the King, Inception,                       |
|    |                 |                                              | The Lord of the Rings: The The Fellowship of the Ring, The Matrix,              |
|    |                 |                                              | The Lord of the Rings: The Two Towers, Batman Begins,                           |
|    |                 |                                              | The Dark Knight Rises, Iron Man, Captain America: The First Avenger, Iron Man 2 |
+----+-----------------+----------------------------------------------+---------------------------------------------------------------------------------+

If it were up to me I would be combining the recommendation score with title (manual line breaks added for presentation):

+----+-----------------+-------------------------------------------------------------------------
|    |   movie_title   |  recommendations                                                                                |
+----+-----------------+-------------------------------------------------------------------------
|  1 | The Dark Knight | 8.1(The Lord of the Rings: The Return of the King);
                       | 8(Inception); 8(The Lord of the Rings: The The Fellowship of the Ring);
                       | 7.9(The Matrix); 7.9(The Lord of the Rings: The Two Towers);
                       | 7.5(Batman Begins); 7.5(The Dark Knight Rises);
                       | 7.3(Iron Man);  6.6(Captain America: The First Avenger);  6.6(Iron Man 2)

which was produced by this query:

SELECT
      tmdb_movies.movie_title
    , GROUP_CONCAT(DISTINCT concat(r.recommendations_vote_average,'(',r.recommendations_title,')')
                   ORDER BY r.recommendations_vote_average DESC
                   SEPARATOR '; '
                  ) as recommendations
FROM tmdb_movies
LEFT JOIN recommendations r ON r.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=1
GROUP BY tmdb_movies.movie_title

more info.
The following query reverses the table precedence and doesn't use group_concat

select
    m.movie_title, r.*
from recommendations r
left join tmdb_movies m  ON r.recommendations_tmdb_id=m.tmdb_id
;

Result:

+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
|    |   movie_title   | recommendations_tmdb_id |                 recommendations_title                 | recommendations_vote_average |
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
|  1 | The Dark Knight |                       1 | The Dark Knight Rises                                 |                          7.5 |
|  2 | The Dark Knight |                       1 | Batman Begins                                         |                          7.5 |
|  3 | The Dark Knight |                       1 | Iron Man                                              |                          7.3 |
|  4 | The Dark Knight |                       1 | The Lord of the Rings: The Return of the King         |                          8.1 |
|  5 | The Dark Knight |                       1 | The Lord of the Rings: The The Fellowship of the Ring |                            8 |
|  6 | The Dark Knight |                       1 | The Lord of the Rings: The Two Towers                 |                          7.9 |
|  7 | The Dark Knight |                       1 | The Matrix                                            |                          7.9 |
|  8 | The Dark Knight |                       1 | Inception                                             |                            8 |
|  9 | The Dark Knight |                       1 | Iron Man 2                                            |                          6.6 |
| 10 | The Dark Knight |                       1 | Captain America: The First Avenger                    |                          6.6 |
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+

sample data (should have been in question):

CREATE TABLE tmdb_movies (
  tmdb_id INTEGER NOT NULL PRIMARY KEY,
  movie_title TEXT NOT NULL
);

INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');

CREATE TABLE recommendations (
  recommendations_tmdb_id INTEGER NOT NULL,
  recommendations_title TEXT NOT NULL,
  recommendations_vote_average TEXT NOT NULL
);

INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');


问:
Show/remove classes while scrolling down
I just need to show div while scrolling down and remove another div at same time.
I try with this code and this is working as I expected. The problem is, If I scroll to top I need to show the removed class and hide current class. (opposite side of this)

This is my code.

```<code>    $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll >= 0) {
     $(".left-nav").removeClass("white-nav");
    }
  });
</code>```

What is the best solution?

答:
$(window).scroll(function() {
   $(".left-nav").toggleClass("white-nav", $(window).scrollTop() <= 0);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.white-nav{
  color:red
}</code>```

Hey

nothing here
```

Body:
I just need to show div while scrolling down and remove another div at same time.
I try with this code and this is working as I expected. The problem is, If I scroll to top I need to show the removed class and hide current class. (opposite side of this)

This is my code.

    $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll >= 0) {
     $(".left-nav").removeClass("white-nav");
    }
  });

What is the best solution?

Body:
$(window).scroll(function() {
   $(".left-nav").toggleClass("white-nav", $(window).scrollTop() <= 0);
});

.white-nav{
  color:red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='left-nav white-nav'>Hey</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div>nothing here</div>


答:
If you are auditing data changes in a db then you can use triggers on the relevant table.

For logging in a dotNet app use TraceSource to write logging info and a custom TraceListener to write to a db.  Don't need a framework beyond the base class library really.

Title: Logging Framework for the ASP.NET application

Body:
My application needs to log informations about user actions (inserts, updates, deletes, etc) and exceptions and i want to store de log on Oracle10, so i'am searching some log framework to use.
I read a little bit about:

1 -Log4Net

2 - Logging Application Block

3 - Elmah

Whats your opinion about these log tools?
Whats a good framework (or way to implement) log on my application?

*After a discussion with the project manager, Logging Application Block
 will be our choice, but, lets comment about this =)


问:
Keep element fixed while Safari navigation bar collapes on iOS
I'm developing a web site based on the Hyde theme for Jekyll.

This layout uses a fixed navigation bar on the left with 100% width. This is working fine in most situations.

In Safari on iOS, however, the height of the viewport changes while the user is scrolling as the browsers top navigation bar collapses. If this happens, the navigation bar's size is not updated until the scroll stops, leaving an area in the lower left corner that is not covered by the navigation bar:

(Notice the text extends below the navigation bar. This screenshot was taken while the page was in motion.)

This video shows the problem in action.

Is there any way to force Safari to update the navigation bar's height while the scroll is in progress?

答:
its an ongoing discussion. There is no real solution for this problem. https://nicolas-hoizey.com/2015/02/viewport-height-is-taller-than-the-visible-part-of-the-document-in-some-mobile-browsers.html

What you can try for your website is the following:

```<code>.sidebar {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 18rem;
    text-align: left;
    height: 100vh;
}
</code>```

This will align the sidebar to the bottom and the text wont cut. The white bar will appear on top but it wont be too intrusive as the bottom being cut out.

Body:
its an ongoing discussion. There is no real solution for this problem. https://nicolas-hoizey.com/2015/02/viewport-height-is-taller-than-the-visible-part-of-the-document-in-some-mobile-browsers.html

What you can try for your website is the following:

.sidebar {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 18rem;
    text-align: left;
    height: 100vh;
}

This will align the sidebar to the bottom and the text wont cut. The white bar will appear on top but it wont be too intrusive as the bottom being cut out.


问:
How to check if FFmpeg process is complete
How can I check if ffmpeg process is complete.
Like if I want to perform overlaying of image to video, I want to determine when the process is completed or if the output file is already complete.

So from this command

```<code>  ffmpeg -i original.mp4 -i watermark.png -filter_complex "overlay=(W-w)/2:(H-h)/2" output.mp4
</code>```

How can I determine if output.mp4 is already complete.
Because if I have another function to transfer the output file somewhere, the transferred file is still incomplete by the time transfer is executed.

答:
You did not specify how you're running ffmpeg: from bash or maybe from your code?

I will assume bash

In bash, when you run a process the way you run ffmpeg in your example, it will run in a sequential manner, so all you have to do is put your function right after the ffmpeg command line like so:

```<code>ffmpeg -i original.mp4 -i watermark.png -filter_complex "overlay=(W-w)/2:(H-h)/2" output.mp4

echo "done!"
</code>```

Body:
How can I check if ffmpeg process is complete.
Like if I want to perform overlaying of image to video, I want to determine when the process is completed or if the output file is already complete.

So from this command

  ffmpeg -i original.mp4 -i watermark.png -filter_complex "overlay=(W-w)/2:(H-h)/2" output.mp4

How can I determine if output.mp4 is already complete.
Because if I have another function to transfer the output file somewhere, the transferred file is still incomplete by the time transfer is executed.

Body:
You did not specify how you're running ffmpeg: from bash or maybe from your code?

I will assume bash

In bash, when you run a process the way you run ffmpeg in your example, it will run in a sequential manner, so all you have to do is put your function right after the ffmpeg command line like so:

ffmpeg -i original.mp4 -i watermark.png -filter_complex "overlay=(W-w)/2:(H-h)/2" output.mp4

echo "done!"


问:
Error trying to send email through Gmail using SwiftMailer
I'm following Symfony 3 Documentation to send an email from my controller, but I'm getting an error. I made sure to follow each step from the above page correctly, but no use.

This is how my controller looks like:

```<code><?php

namespace MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction(\Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('my.address@gmail.com')
            ->setBody(
                $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                    'MyBundle::Emails/registration.html.twig',
                    array('name' => 'John Doe')
                ),
                'text/html'
            );

        $mailer->send($message);

        return new Response('<html<body>Sent</body></html>');
    }
}
</code>```

This is the error I'm getting:

Controller "MyBundle\Controller\DefaultController::indexAction()" requires that you provide a value for the "$mailer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

Comparing to the documentation page, I'm pretty sure everything is as it should be, so can anyone please help me find the source of this error?

答:
I think, you not enable autowiring in projects settings. So, Swift_Mailer is not injected automatically. Enable it or inject mailer service manually.

See more about autowiring in Symfony here.

Body:
I'm following Symfony 3 Documentation to send an email from my controller, but I'm getting an error. I made sure to follow each step from the above page correctly, but no use.

This is how my controller looks like:

<?php

namespace MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction(\Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('my.address@gmail.com')
            ->setBody(
                $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                    'MyBundle::Emails/registration.html.twig',
                    array('name' => 'John Doe')
                ),
                'text/html'
            );

        $mailer->send($message);

        return new Response('<htmlSent');
    }
}

This is the error I'm getting:

Controller "MyBundle\Controller\DefaultController::indexAction()" requires that you provide a value for the "$mailer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

Comparing to the documentation page, I'm pretty sure everything is as it should be, so can anyone please help me find the source of this error?


问:
How to correctly call a controller function with in a directive?
I am using a directive in my html page under the impression of a controller. I need to call a controller function from that directive but I am  unable to correctly do that. Every time there are some errors. Can Any body help me ? Please :(
Below is the code.

app.directive('myGoogleAutocomplete', function () {
    return {
        replace: true,
        require: 'ngModel',
        scope: {
            ngModel: '=',
            googleModel: '=',
            onSelect: '&?', // optional callback on selected successfully: 'onPostedBid(googleModel)'
        },
        template: '<input class="form-control" type="text" style="z-index: 100000;" autocomplete="on">',
        link: function ($scope, element, attrs, model) {
            var googleOptions = {
                types: ['address'] // change or empty it, if you want no restrictions
            };

            var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

            google.maps.event.addListener(autocomplete, 'place_changed', function () {

                /**
                 * Search gor the passed 'type' of info into the google place component
                 * @param {type} components
                 * @param {type} type
                 * @returns {type}
                 */
                $scope.extract = function (components, type) {
                    for (var i = 0; i < components.length; i++)
                        for (var j = 0; j < components[i].types.length; j++)
                            if (components[i].types[j] == type) return components[i].short_name;
                    return '';
                };

                $scope.$apply(function () {
                    var place = autocomplete.getPlace();
                    if (!place.geometry)
                     {
                        // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
                        model.$setValidity('place', false);
                        //console.log("No details available for input: '" + place.name + "'");
                        return;
                    }

                    console.log($scope.googleModel.longitude);

                    console.log($scope.googleModel.latitude);
      $scope.thisFunct(); //want to call controller func here

                    if (place.address_components) {
                        $scope.googleModel.address = [
                            $scope.extract(place.address_components, 'route'),
                            $scope.extract(place.address_components, 'street_number')
                        ].join(' ');

                    }

                    model.$setViewValue(element.val());
                    model.$setValidity('place', true);
                    if (attrs.onSelect) $scope.onSelect({ $item: $scope.googleModel });
                });
            });
        }
    }
});

//
app.controller("featureController", function($scope,$http,$rootScope,close,ModalService,NgMap) {
        $scope.thisFunct=function()
        {
            console.log("Reached Here finally! Success ");
        }
```

<pre class="lang-html prettyprint-override"><code>  <my-google-autocomplete id="address"   name="address"
      ng-model="task.house_no" google-model="model.googleAddress"
      on-select="vm.onSelectGoogleAddress($item)" autocomplete="off"
      required>
  </my-google-autocomplete>
</code>```

答:
In scope of directive, to call the function:</p>

```<code><div my-directive callback-fn="ctrlFn(arg1)"></div>

 app.directive('myDirective', function() {
    return {
        scope: { someCtrlFn: '&callbackFn' },
        link: function(scope, element, attrs) {
            scope.someCtrlFn({arg1: 22});
        },
    }
});

 function MyCtrl($scope) {
    $scope.ctrlFn = function(test) {
        console.log(test);
    }
}
</code>```

Body:
I am using a directive in my html page under the impression of a controller. I need to call a controller function from that directive but I am  unable to correctly do that. Every time there are some errors. Can Any body help me ? Please :(
Below is the code.

app.directive('myGoogleAutocomplete', function () {
    return {
        replace: true,
        require: 'ngModel',
        scope: {
            ngModel: '=',
            googleModel: '=',
            onSelect: '&?', // optional callback on selected successfully: 'onPostedBid(googleModel)'
        },
        template: '<input class="form-control" type="text" style="z-index: 100000;" autocomplete="on">',
        link: function ($scope, element, attrs, model) {
            var googleOptions = {
                types: ['address'] // change or empty it, if you want no restrictions
            };

            var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

            google.maps.event.addListener(autocomplete, 'place_changed', function () {

                /**
                 * Search gor the passed 'type' of info into the google place component
                 * @param {type} components
                 * @param {type} type
                 * @returns {type}
                 */
                $scope.extract = function (components, type) {
                    for (var i = 0; i < components.length; i++)
                        for (var j = 0; j < components[i].types.length; j++)
                            if (components[i].types[j] == type) return components[i].short_name;
                    return '';
                };

                $scope.$apply(function () {
                    var place = autocomplete.getPlace();
                    if (!place.geometry)
                     {
                        // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
                        model.$setValidity('place', false);
                        //console.log("No details available for input: '" + place.name + "'");
                        return;
                    }

                    console.log($scope.googleModel.longitude);

                    console.log($scope.googleModel.latitude);
      $scope.thisFunct(); //want to call controller func here

                    if (place.address_components) {
                        $scope.googleModel.address = [
                            $scope.extract(place.address_components, 'route'),
                            $scope.extract(place.address_components, 'street_number')
                        ].join(' ');

                    }

                    model.$setViewValue(element.val());
                    model.$setValidity('place', true);
                    if (attrs.onSelect) $scope.onSelect({ $item: $scope.googleModel });
                });
            });
        }
    }
});

//
app.controller("featureController", function($scope,$http,$rootScope,close,ModalService,NgMap) {
        $scope.thisFunct=function()
        {
            console.log("Reached Here finally! Success ");
        }

  <my-google-autocomplete id="address"   name="address"
      ng-model="task.house_no" google-model="model.googleAddress"
      on-select="vm.onSelectGoogleAddress($item)" autocomplete="off"
      required>
  </my-google-autocomplete>

Body:
In scope of directive, to call the function:

<div my-directive callback-fn="ctrlFn(arg1)"></div>

 app.directive('myDirective', function() {
    return {
        scope: { someCtrlFn: '&callbackFn' },
        link: function(scope, element, attrs) {
            scope.someCtrlFn({arg1: 22});
        },
    }
});

 function MyCtrl($scope) {
    $scope.ctrlFn = function(test) {
        console.log(test);
    }
}


问:
Why AppCompat does not support the current theme features windowActionBar: false
Why AppCompat does not support the current theme features  { windowActionBar: false, windowActionBarOverlay: false, android:windowIsFloating: false, windowActionModeOverlay: false, windowNoTitle: false

```<code>    IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2473)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
    at android.app.ActivityThread.access$1100(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5582)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
    at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.github.paolorotolo.appintro.AppIntroBase.onCreate(AppIntroBase.java:79)
    at com.infos.activities.Activity_Splash.onCreate(Activity_Splash.kt:27)
    at android.app.Activity.performCreate(Activity.java:6321)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread
</code>```

my Theme style

```<code> <!-- Base application theme. -->
    <style name="MyTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>

        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@color/windowBackground</item>
        <item name="colorButtonNormal">@color/colorPrimary</item>
        <item name="colorControlActivated">@color/colorPrimary</item>
    </style>
</code>```

答:
Try this,</p>

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="windowActionBar">false</item>
    <item name="windowActionBarOverlay">false</item>
    <item name="windowIsFloating">false</item>
    <item name="windowActionModeOverlay">false</item>
    <item name="windowNoTitle">false</item>
</style>
</code>```

Body:
Why AppCompat does not support the current theme features  { windowActionBar: false, windowActionBarOverlay: false, android:windowIsFloating: false, windowActionModeOverlay: false, windowNoTitle: false

    IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2473)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
    at android.app.ActivityThread.access$1100(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5582)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
    at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.github.paolorotolo.appintro.AppIntroBase.onCreate(AppIntroBase.java:79)
    at com.infos.activities.Activity_Splash.onCreate(Activity_Splash.kt:27)
    at android.app.Activity.performCreate(Activity.java:6321)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread

my Theme style

Body:
Try this,

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="windowActionBar">false</item>
    <item name="windowActionBarOverlay">false</item>
    <item name="windowIsFloating">false</item>
    <item name="windowActionModeOverlay">false</item>
    <item name="windowNoTitle">false</item>
</style>


问:
Tkinter askopenfilename open at script start
I encounter small issue with askopenfilename module in python.
I create a small GUI for catch file, select and add option before running another script.

Presently i have define my GUI and i want to add button for call the askopenfilename.

But my problem is when i run my script askopenfilename start directly and not on click on my specific button.

I share with you my problematic code.

thanks for your help.

```<code>##Import##
import os
import sys
import math
import pickle
import shutil
import paramiko
import Tkinter, tkFileDialog
import Tix

from Tkinter import *
def open():
    tkFileDialog.askopenfilename(initialdir="U:/calcul/projects/", title="job file selector",parent=fen1)
###Graphical interface##
#principal window
fen1=Tk()
fen1.title("utilitaire de lancement serveur")
v=IntVar()
tex=StringVar()
tex.set('abc \n timmy')
#slave widget
txt1=Label(fen1, text='Fichier Dat').grid(row=0, sticky=W)
entr1=Text(fen1, width=50,height=2).grid(row=1, sticky=W)
b1=Button(fen1, text='select file', command=open()).grid(row=2,sticky=E)
text2=Label(fen1, text='number of core').grid(row=3, sticky=W)
check1=Radiobutton(fen1, text="1 core", variable=v, value=1).grid(row=4, column=0)
check2=Radiobutton(fen1, text="8 core", variable=v, value=8).grid(row=5, column=0)
check3=Radiobutton(fen1, text="12 core", variable=v, value=12).grid(row=6, column=0)
text3=Label(fen1, text='Dependencies').grid(row=7, sticky=W)
entr2=Entry(fen1).grid(row=8, column=0)
text4=Label(fen1, text='log').grid(row=9, sticky=W)
mes1=Message(fen1,textvariable=tex,bg='white',relief='sunken',bd=3).grid(row=10, column=0)
b2=Button(fen1, text='quitter',command= fen1.quit).grid(row=11,column=1)
fen1.mainloop()
print v.get()
</code>```

答:
this line:

```<code>b1=Button(fen1, text='select file', command=open()).grid(row=2,sticky=E)
</code>```

is the problem. to call a function with a button when pressed you need to skip the brackets:

```<code>b1=Button(fen1, text='select file', command=open).grid(row=2,sticky=E)
</code>```

what you were actually doing is calling your function once at the start of the script, then it uses what the function returns (None) as the command to be called, obviously it cannot be called when you subsequently press the button so it does nothing. a complete (and working) version of what you have above:

```<code>##Import##
import os
import sys
import math
import pickle
import shutil
import paramiko
import Tkinter, tkFileDialog
import Tix

from Tkinter import *
def open():
    tkFileDialog.askopenfilename(initialdir="U:/calcul/projects/", title="job file selector",parent=fen1)
###Graphical interface##
#principal window
fen1=Tk()
fen1.title("utilitaire de lancement serveur")
v=IntVar()
tex=StringVar()
tex.set('abc \n timmy')
#slave widget
txt1=Label(fen1, text='Fichier Dat').grid(row=0, sticky=W)
entr1=Text(fen1, width=50,height=2).grid(row=1, sticky=W)
b1=Button(fen1, text='select file', command=open).grid(row=2,sticky=E) # note that i removed the brackets after "command=open"
text2=Label(fen1, text='number of core').grid(row=3, sticky=W)
check1=Radiobutton(fen1, text="1 core", variable=v, value=1).grid(row=4, column=0)
check2=Radiobutton(fen1, text="8 core", variable=v, value=8).grid(row=5, column=0)
check3=Radiobutton(fen1, text="12 core", variable=v, value=12).grid(row=6, column=0)
text3=Label(fen1, text='Dependencies').grid(row=7, sticky=W)
entr2=Entry(fen1).grid(row=8, column=0)
text4=Label(fen1, text='log').grid(row=9, sticky=W)
mes1=Message(fen1,textvariable=tex,bg='white',relief='sunken',bd=3).grid(row=10, column=0)
b2=Button(fen1, text='quitter',command= fen1.quit).grid(row=11,column=1)
fen1.mainloop()
print v.get()
</code>```

also worth noting that there is a built in function called open by calling your function the same thing any calls to the original (to open a file) will not work. calling functions the same as built in functions should be avoided.

Body:
I encounter small issue with askopenfilename module in python.
I create a small GUI for catch file, select and add option before running another script.

Presently i have define my GUI and i want to add button for call the askopenfilename.

But my problem is when i run my script askopenfilename start directly and not on click on my specific button.

I share with you my problematic code.

thanks for your help.

##Import##
import os
import sys
import math
import pickle
import shutil
import paramiko
import Tkinter, tkFileDialog
import Tix

from Tkinter import *
def open():
    tkFileDialog.askopenfilename(initialdir="U:/calcul/projects/", title="job file selector",parent=fen1)
###Graphical interface##
#principal window
fen1=Tk()
fen1.title("utilitaire de lancement serveur")
v=IntVar()
tex=StringVar()
tex.set('abc \n timmy')
#slave widget
txt1=Label(fen1, text='Fichier Dat').grid(row=0, sticky=W)
entr1=Text(fen1, width=50,height=2).grid(row=1, sticky=W)
b1=Button(fen1, text='select file', command=open()).grid(row=2,sticky=E)
text2=Label(fen1, text='number of core').grid(row=3, sticky=W)
check1=Radiobutton(fen1, text="1 core", variable=v, value=1).grid(row=4, column=0)
check2=Radiobutton(fen1, text="8 core", variable=v, value=8).grid(row=5, column=0)
check3=Radiobutton(fen1, text="12 core", variable=v, value=12).grid(row=6, column=0)
text3=Label(fen1, text='Dependencies').grid(row=7, sticky=W)
entr2=Entry(fen1).grid(row=8, column=0)
text4=Label(fen1, text='log').grid(row=9, sticky=W)
mes1=Message(fen1,textvariable=tex,bg='white',relief='sunken',bd=3).grid(row=10, column=0)
b2=Button(fen1, text='quitter',command= fen1.quit).grid(row=11,column=1)
fen1.mainloop()
print v.get()

Body:
this line:

b1=Button(fen1, text='select file', command=open()).grid(row=2,sticky=E)

is the problem. to call a function with a button when pressed you need to skip the brackets:

b1=Button(fen1, text='select file', command=open).grid(row=2,sticky=E)

what you were actually doing is calling your function once at the start of the script, then it uses what the function returns (None) as the command to be called, obviously it cannot be called when you subsequently press the button so it does nothing. a complete (and working) version of what you have above:

##Import##
import os
import sys
import math
import pickle
import shutil
import paramiko
import Tkinter, tkFileDialog
import Tix

from Tkinter import *
def open():
    tkFileDialog.askopenfilename(initialdir="U:/calcul/projects/", title="job file selector",parent=fen1)
###Graphical interface##
#principal window
fen1=Tk()
fen1.title("utilitaire de lancement serveur")
v=IntVar()
tex=StringVar()
tex.set('abc \n timmy')
#slave widget
txt1=Label(fen1, text='Fichier Dat').grid(row=0, sticky=W)
entr1=Text(fen1, width=50,height=2).grid(row=1, sticky=W)
b1=Button(fen1, text='select file', command=open).grid(row=2,sticky=E) # note that i removed the brackets after "command=open"
text2=Label(fen1, text='number of core').grid(row=3, sticky=W)
check1=Radiobutton(fen1, text="1 core", variable=v, value=1).grid(row=4, column=0)
check2=Radiobutton(fen1, text="8 core", variable=v, value=8).grid(row=5, column=0)
check3=Radiobutton(fen1, text="12 core", variable=v, value=12).grid(row=6, column=0)
text3=Label(fen1, text='Dependencies').grid(row=7, sticky=W)
entr2=Entry(fen1).grid(row=8, column=0)
text4=Label(fen1, text='log').grid(row=9, sticky=W)
mes1=Message(fen1,textvariable=tex,bg='white',relief='sunken',bd=3).grid(row=10, column=0)
b2=Button(fen1, text='quitter',command= fen1.quit).grid(row=11,column=1)
fen1.mainloop()
print v.get()

also worth noting that there is a built in function called open by calling your function the same thing any calls to the original (to open a file) will not work. calling functions the same as built in functions should be avoided.


问:
How to change default values of td in table HTML/CSS
How can i resize only 1 or 2 cells from my table. I created a new class with new width , but when i try to use it nothing changes. Where is mistake in my code ?
So the problem is that i want City and State to be on the same line with shorter width of the cells, because now the input box of State is upper the Last name and it's not in the table

CSS

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <tr>
        <th>Last Name</th>
        <td class="cbCell">
            <input type = "text" name "Last Name" value = "Enter Last Name" />
        </td>
    </tr>
    <tr>
        <th>First Name</th>
        <td>
            <input type = "text" name "First Name" value = "Enter First Name" />
        </td>
    </tr>
    <tr>
        <th>Address</th>
        <td> <input type = "text" name "Address" /></td>
    </tr>
    <tr>
        <th class = "thnewclass">City</th>
        <td class = "thnewclass">
            <input type = "text" name "City" />
        </td>
        <th>State</th>
        <input type = "text" name "State">
    </tr></code>```

答:
Loose the !important from td style

```<code>td {
    width: 300px ;
}
th {
    width: 120px;
    text-align: right;
}
.thnewclass {
    width: 50px;
}
</code>```

Demo

Body:
How can i resize only 1 or 2 cells from my table. I created a new class with new width , but when i try to use it nothing changes. Where is mistake in my code ?
So the problem is that i want City and State to be on the same line with shorter width of the cells, because now the input box of State is upper the Last name and it's not in the table

CSS

        Last Name

            <input type = "text" name "Last Name" value = "Enter Last Name" />

        First Name

            <input type = "text" name "First Name" value = "Enter First Name" />

        Address
         <input type = "text" name "Address" />

        City

            <input type = "text" name "City" />

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

Body:
Loose the !important from td style

td {
    width: 300px ;
}
th {
    width: 120px;
    text-align: right;
}
.thnewclass {
    width: 50px;
}

Demo