问:
Error Code: 1248. Every derived table must have its own alias
```<code>SELECT dept_name,avg_salary
FROM (SELECT dept_name,AVG(salary) AS avg_salary
        FROM instructor
        group by dept_name)
WHERE avg_salary>42000;
</code>```

答:
The Impaler's answer is correct and actually solves the error that you are getting.

Let me pinpoint, however, that you do not need a subquery to achieve your purpose. To filter on an aggregate expression, you can use the having clause, which is part of the standard SQL:

```<code>select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name
having avg(salary) > 42000;
</code>```

On top of that, MySQL extends the standard and lets you use column aliases in the having clause, which furthermore simplifies the query:

```<code>select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name
having avg_salary > 42000;
</code>```

I would expect that this solution should be more efficient than using a subquery (unless the database is smart enough to spot that optimization, in which case it would be equivalent, performance-wise); and it sure is neater and easier to understand.

Body:
The Impaler's answer is correct and actually solves the error that you are getting.

Let me pinpoint, however, that you do not need a subquery to achieve your purpose. To filter on an aggregate expression, you can use the having clause, which is part of the standard SQL:

select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name
having avg(salary) > 42000;

On top of that, MySQL extends the standard and lets you use column aliases in the having clause, which furthermore simplifies the query:

select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name
having avg_salary > 42000;

I would expect that this solution should be more efficient than using a subquery (unless the database is smart enough to spot that optimization, in which case it would be equivalent, performance-wise); and it sure is neater and easier to understand.


来源: stackexchange

问:
Keyboard disappearing shows white color- Xamarin forms
I am developing a chat application.For adjusting the chat entry with keyboard, I used

```<code> App.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().
    UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
</code>```

It works fine. But the problem I am facing is whenever we hide the keyboard, it is not that smooth.ie; It shows some white color and closes.Please refer the attached GIF.

When I changed to

```<code>UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Pan);
</code>```

It will solve the issue but, keyboard will overlap the entry. How to solve this? How to make the keyboard disappearing smooth like in whatsApp? Any help is appreciated.

For more clarity please find the video URL:https://drive.google.com/file/d/16g8oVzOkQ0fxd66zOfc97D4TI80B1VKe/view?usp=drivesdk

答:
https://forums.xamarin.com/discussion/87176/windowsoftinputmode-doesnt-work-in-xamarin-forms-android

Maybe second post in this discussion will help

ContentLicense: CC BY-SA 4.0

Body:
I am developing a chat application.For adjusting the chat entry with keyboard, I used

 App.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().
    UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);

It works fine. But the problem I am facing is whenever we hide the keyboard, it is not that smooth.ie; It shows some white color and closes.Please refer the attached GIF.

When I changed to

UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Pan);

It will solve the issue but, keyboard will overlap the entry. How to solve this? How to make the keyboard disappearing smooth like in whatsApp? Any help is appreciated.

For more clarity please find the video URL:https://drive.google.com/file/d/16g8oVzOkQ0fxd66zOfc97D4TI80B1VKe/view?usp=drivesdk


问:
How to make a carousel where the center is bigger? (flutter)
I want to have a slideshow where you see three container and the middle container should be bigger than the other two.

This is how it should look:

I tried the to put enlargeCenterPage: true,but it only works with a viewportFraction: 0.8.

This is how it looks now:

This is my code with the ,,carousel_slider: ^1.4.1'' plugin:

mport 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../classes/konto.dart';
import '../providers/account_type.dart';

class Carousel extends StatefulWidget {
  @override
  _CarouselState createState() => _CarouselState();
}

class _CarouselState extends State<Carousel> {
  @override
  Widget build(BuildContext context) {
    return Consumer<GeldKonto>(
      builder: (ctx, konto, child) => CarouselSlider.builder(
          height: MediaQuery.of(context).size.height * 0.5,
          //realPage: 1,
         aspectRatio: 16/4,
          viewportFraction: 0.4,
          initialPage: 0,
          enableInfiniteScroll: true,
          reverse: false,
          autoPlay: true,
          autoPlayInterval: Duration(seconds: 4),
          autoPlayAnimationDuration: Duration(milliseconds: 800),
          autoPlayCurve: Curves.fastOutSlowIn,
          pauseAutoPlayOnTouch: Duration(seconds: 10),
          enlargeCenterPage: true,
          scrollDirection: Axis.horizontal,
          itemCount: konto.kontos.length,
          itemBuilder: (BuildContext context, int i) {
            Map<String, Konto> kontoHier = konto.kontos;
            String key = kontoHier.keys.elementAt(i);
            return
               Container(
                 height: 200,
                 child: Column(mainAxisAlignment: MainAxisAlignment.center ,
              children: <Widget>[
                  Text(
                    kontoHier[key].title,
                    style: Theme.of(context).textTheme.title,
                  ),
                  Container(
                    height: 150,
                    width: 150,
                    margin: EdgeInsets.all(10.0),
                    decoration: BoxDecoration(
                        color: Colors.transparent,
                        border: Border.all(
                          color: Colors.white54,
                          width: 2,
                        ),
                        shape: BoxShape.circle),
                        child: kontoHier[key].icon,

                  ),
                   Text(
                    '${kontoHier[key].kontostand}',
                    style: Theme.of(context).textTheme.title,
                  ),
              ]
            ),
               );
          }),
    );
  }
}```

How to make the center bigger (the two others smaller)?

I am new to flutter and would love to hear some advice :)

答:
Use a scale widget like shown here     </p>

```<code>import 'package:carousel_slider/carousel_slider.dart';
    import 'package:flutter/material.dart';

    class CArousel extends StatefulWidget {
      @override
      _CArouselState createState() => _CArouselState();
    }

    class _CArouselState extends State<CArousel> {
      int _current = 0;

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
              padding: EdgeInsets.only(top: 200),
              child: CarouselSlider.builder(
                  viewportFraction: 0.7,
                  initialPage: _current,
                  onPageChanged: (index) {
                    setState(() {
                      _current = index;
                    });
                  },
                  itemCount: 6,
                  itemBuilder: (ctx, int index) {
                    return Transform.scale(
                      scale: index == _current ? 1 : 0.8,
                      child: Container(
                        height: 400,
                        width: 300,
                        color: Colors.red,
                        child: Center(
                          child: Text(
                            "$index",
                            style: TextStyle(fontSize: 30),
                          ),
                        ),
                      ),
                    );
                  })),
        );
      }
    }
</code>```

Body:
I want to have a slideshow where you see three container and the middle container should be bigger than the other two.

This is how it should look:

I tried the to put enlargeCenterPage: true,but it only works with a viewportFraction: 0.8.

This is how it looks now:

This is my code with the ,,carousel_slider: ^1.4.1'' plugin:

mport 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../classes/konto.dart';
import '../providers/account_type.dart';

class Carousel extends StatefulWidget {
  @override
  _CarouselState createState() => _CarouselState();
}

class _CarouselState extends State<Carousel> {
  @override
  Widget build(BuildContext context) {
    return Consumer<GeldKonto>(
      builder: (ctx, konto, child) => CarouselSlider.builder(
          height: MediaQuery.of(context).size.height * 0.5,
          //realPage: 1,
         aspectRatio: 16/4,
          viewportFraction: 0.4,
          initialPage: 0,
          enableInfiniteScroll: true,
          reverse: false,
          autoPlay: true,
          autoPlayInterval: Duration(seconds: 4),
          autoPlayAnimationDuration: Duration(milliseconds: 800),
          autoPlayCurve: Curves.fastOutSlowIn,
          pauseAutoPlayOnTouch: Duration(seconds: 10),
          enlargeCenterPage: true,
          scrollDirection: Axis.horizontal,
          itemCount: konto.kontos.length,
          itemBuilder: (BuildContext context, int i) {
            Map<String, Konto> kontoHier = konto.kontos;
            String key = kontoHier.keys.elementAt(i);
            return
               Container(
                 height: 200,
                 child: Column(mainAxisAlignment: MainAxisAlignment.center ,
              children: <Widget>[
                  Text(
                    kontoHier[key].title,
                    style: Theme.of(context).textTheme.title,
                  ),
                  Container(
                    height: 150,
                    width: 150,
                    margin: EdgeInsets.all(10.0),
                    decoration: BoxDecoration(
                        color: Colors.transparent,
                        border: Border.all(
                          color: Colors.white54,
                          width: 2,
                        ),
                        shape: BoxShape.circle),
                        child: kontoHier[key].icon,

                  ),
                   Text(
                    '${kontoHier[key].kontostand}',
                    style: Theme.of(context).textTheme.title,
                  ),
              ]
            ),
               );
          }),
    );
  }
}

How to make the center bigger (the two others smaller)?

I am new to flutter and would love to hear some advice :)

Body:
Use a scale widget like shown here

import 'package:carousel_slider/carousel_slider.dart';
    import 'package:flutter/material.dart';

    class CArousel extends StatefulWidget {
      @override
      _CArouselState createState() => _CArouselState();
    }

    class _CArouselState extends State<CArousel> {
      int _current = 0;

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
              padding: EdgeInsets.only(top: 200),
              child: CarouselSlider.builder(
                  viewportFraction: 0.7,
                  initialPage: _current,
                  onPageChanged: (index) {
                    setState(() {
                      _current = index;
                    });
                  },
                  itemCount: 6,
                  itemBuilder: (ctx, int index) {
                    return Transform.scale(
                      scale: index == _current ? 1 : 0.8,
                      child: Container(
                        height: 400,
                        width: 300,
                        color: Colors.red,
                        child: Center(
                          child: Text(
                            "$index",
                            style: TextStyle(fontSize: 30),
                          ),
                        ),
                      ),
                    );
                  })),
        );
      }
    }


问:
Deleting a row in datagrid view
I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.

A sample code is appreciated.

Thanks

答:
```<code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
        String productId = row.Cells[0].Text; // I suposed your product Id in very first column in gridview
        //Delete Code goes here..........
        ...........................
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Deleting a row in datagrid view


问:
Pass value to string imported from another module using f-string
This will be easier to explain with an example. Let's say I have a settings.py file that looks like this:

settings.py

```<code>a_string='This string should contain {value} <<< here.'
</code>```

I then import settings into my .py file, where I have a function mystring that looks something like this (note the function does not work as I would like it to):

```<code>import settings

def mystring(value='100'):
    b_string=f'{settings.a_string}'
    return b_string

print(mystring())
# I would like this to return:
# "This string should contain 100 <<< here."
</code>```

I have tried placing the f-string formatting inside settings.py, such as:

```<code>a_string="f'This string should contain {value} <<< here.'"
</code>```

to no avail. No luck if I place it in the function or function call either.

I feel like I am missing something obvious, but I just can't see it, so any pointers would be much appreciated.

答:
Method 1: use str.format():

```<code>b_string=settings.a_string.format(value=value)
</code>```

Method 2: use eval :

```<code>fstr = "the value is {value}"
def func(value=100):
    b_str = eval('f"' + fstr + '"')
    return b_str
</code>```

WARNING: Only use this method if you know what fstr contains. If fstr is something like "open('virus.txt', 'w').write('evil')", your code gets vulnerable.

Body:
This will be easier to explain with an example. Let's say I have a settings.py file that looks like this:

settings.py

a_string='This string should contain {value} <<< here.'

I then import settings into my .py file, where I have a function mystring that looks something like this (note the function does not work as I would like it to):

import settings

def mystring(value='100'):
    b_string=f'{settings.a_string}'
    return b_string

print(mystring())
# I would like this to return:
# "This string should contain 100 <<< here."

I have tried placing the f-string formatting inside settings.py, such as:

a_string="f'This string should contain {value} <<< here.'"

to no avail. No luck if I place it in the function or function call either.

I feel like I am missing something obvious, but I just can't see it, so any pointers would be much appreciated.

Body:
Method 1: use str.format():

b_string=settings.a_string.format(value=value)

Method 2: use eval :

fstr = "the value is {value}"
def func(value=100):
    b_str = eval('f"' + fstr + '"')
    return b_str

WARNING: Only use this method if you know what fstr contains. If fstr is something like "open('virus.txt', 'w').write('evil')", your code gets vulnerable.


问:
how to use the same container which was exited in docker
I had created a lot of containers. I am new to this docker container system.
I do a docker ps -a then I get following result

```<code>debian@osboxes:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                       PORTS               NAMES
a6a62181dcf0        python              "/bin/bash"              About a minute ago   Exited (127) 8 seconds ago                       try1
ed5ef0b8155d        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          pedantic_ellis
19a4eff3b5e5        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          assignment4
30933891f08c        eeadc22d21a9        "python3"                22 hours ago         Exited (0) 22 hours ago                          python
ccdab94fd32f        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (0) 24 hours ago                          confident_wu
ce462ecfc5f2        1d1a162a72a6        "/bin/bash -v /home/…"   28 hours ago         Exited (127) 28 hours ago                        stupefied_grothendieck
6123f134934c        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (1) 28 hours ago                          stupefied_taussig
0ed23a8112a4        1d1a162a72a6        "/bin/bash"              29 hours ago         Exited (0) 29 hours ago                          vigilant_bartik
c343731b7cde        1d1a162a72a6        "/bin/bash"              30 hours ago         Exited (0) 29 hours ago                          gallant_ardinghelli
2f95d3b4c1b8        1d1a162a72a6        "/bin/bash"              30 hours ago         Created                                          nice_hermann
5ebe9f18c744        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          pensive_easley
c1b43edfafb9        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 22 hours ago                          adoring_williams
42dea69d1d4e        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          funny_austin
6f736902e650        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 46 hours ago                          strange_ride
09306e5ec5d1        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          pensive_shtern
699fb2a23e1c        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          sharp_feistel
9f7b29ab512e        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          elastic_payne2
25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            festive_einstein
e658dd320297        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (255) 2 minutes ago                       objective_napier
ebae378d9152        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            brave_ritchie
23c7f4293b30        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            suspicious_lumiere
5090081f6809        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quizzical_keller
425d59be9cbf        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            distracted_lederberg
11c55ce7f011        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_noyce
1ccaf0477995        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          mystifying_tu
62528115f4b7        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          determined_meninsky
fca64af2f595        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_goldwasser
eecb3153bded        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          cool_cray
30b6d61fcac9        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quirky_kapitsa
cf992a8b8286        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          hungry_goldstine
0f9a951f7593        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          crazy_wright
e25dcf8a8be8        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          bold_pasteur
73d068e0d756        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            condescending_goodall
adda325294cd        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            serene_wilson
75a9a3262505        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            hardcore_khorana
e38726a74e9b        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (255) 2 days ago                          beautiful_clarke
4060dbc85d2d        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (0) 3 days ago                            strange_yonath
174509213b30        hadoop-build-1001   "/bin/bash"              8 days ago           Exited (255) 7 days ago                          hadoop-c
fa82c595e214        1d1a162a72a6        "/bin/bash"              8 days ago           Exited (0) 8 days ago                            agitated_edison
4b07fcc45271        python              "python3"                2 weeks ago          Exited (255) 8 days ago                          pyC
1cc06f213eb7        abee520343a4        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        compassionate_kowalevski
8c1eb67f7325        1b1c7b120b48        "/bin/sh -c 'cd /opt…"   3 months ago         Exited (255) 3 months ago                        dreamy_jepsen
1406d7476a28        1180f37ef8b1        "/bin/sh -c 'mkdir -…"   3 months ago         Exited (35) 3 months ago                         upbeat_taussig
e88bcf7743e2        f0f5acc11f91        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        tender_cohen
</code>```

I had made some changes in a container which was created using one of hadoop image as below

```<code>debian@osboxes:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
python              latest              eeadc22d21a9        2 weeks ago         933MB
hadoop-build-1001   latest              1d1a162a72a6        3 months ago        2.02GB
hadoop-build        latest              5c1480006f78        3 months ago        1.96GB
ubuntu              xenial              5f2bf26e3524        3 months ago        123MB
</code>```

I powered off the machine and rebooted etc.
I want to know that I made changes to one of the containers say in above output of docker ps -a the container was

```<code>25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1)
</code>```

how can after a reboot etc I connect or start the same container again.
What I am currently doing is

```<code>docker run -it 1d1a162a72a6 /bin/bash
</code>```

I make some changes and run a few python programms. But after a reboot all the changes are gone that means those python files which I had edited I have to copy paste them again in the container and do every thing from scratch.I have to install vim each time and then each time I do apt-get update install softwares and then check edit the programe.
I am not able to understand how to go back to same container which was created moments ago before exiting. What mistake I am doing here?

答:
docker run always starts a new container.  You can re-attach to the existing container provided it wasn't started with --rm using docker start:

```<code>docker start -ai <CONTAINER_ID>
</code>```

Notice that you should use container ID, not image ID as a parameter to docker start. See more in Docker help:

```<code>$ docker start --help

Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]

Start one or more stopped containers

Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals
      --detach-keys string   Override the key sequence for detaching a container
  -i, --interactive          Attach container's STDIN
</code>```

Body:
I had created a lot of containers. I am new to this docker container system.
I do a docker ps -a then I get following result

debian@osboxes:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                       PORTS               NAMES
a6a62181dcf0        python              "/bin/bash"              About a minute ago   Exited (127) 8 seconds ago                       try1
ed5ef0b8155d        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          pedantic_ellis
19a4eff3b5e5        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          assignment4
30933891f08c        eeadc22d21a9        "python3"                22 hours ago         Exited (0) 22 hours ago                          python
ccdab94fd32f        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (0) 24 hours ago                          confident_wu
ce462ecfc5f2        1d1a162a72a6        "/bin/bash -v /home/…"   28 hours ago         Exited (127) 28 hours ago                        stupefied_grothendieck
6123f134934c        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (1) 28 hours ago                          stupefied_taussig
0ed23a8112a4        1d1a162a72a6        "/bin/bash"              29 hours ago         Exited (0) 29 hours ago                          vigilant_bartik
c343731b7cde        1d1a162a72a6        "/bin/bash"              30 hours ago         Exited (0) 29 hours ago                          gallant_ardinghelli
2f95d3b4c1b8        1d1a162a72a6        "/bin/bash"              30 hours ago         Created                                          nice_hermann
5ebe9f18c744        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          pensive_easley
c1b43edfafb9        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 22 hours ago                          adoring_williams
42dea69d1d4e        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          funny_austin
6f736902e650        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 46 hours ago                          strange_ride
09306e5ec5d1        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          pensive_shtern
699fb2a23e1c        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          sharp_feistel
9f7b29ab512e        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          elastic_payne2
25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            festive_einstein
e658dd320297        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (255) 2 minutes ago                       objective_napier
ebae378d9152        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            brave_ritchie
23c7f4293b30        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            suspicious_lumiere
5090081f6809        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quizzical_keller
425d59be9cbf        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            distracted_lederberg
11c55ce7f011        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_noyce
1ccaf0477995        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          mystifying_tu
62528115f4b7        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          determined_meninsky
fca64af2f595        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_goldwasser
eecb3153bded        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          cool_cray
30b6d61fcac9        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quirky_kapitsa
cf992a8b8286        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          hungry_goldstine
0f9a951f7593        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          crazy_wright
e25dcf8a8be8        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          bold_pasteur
73d068e0d756        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            condescending_goodall
adda325294cd        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            serene_wilson
75a9a3262505        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            hardcore_khorana
e38726a74e9b        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (255) 2 days ago                          beautiful_clarke
4060dbc85d2d        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (0) 3 days ago                            strange_yonath
174509213b30        hadoop-build-1001   "/bin/bash"              8 days ago           Exited (255) 7 days ago                          hadoop-c
fa82c595e214        1d1a162a72a6        "/bin/bash"              8 days ago           Exited (0) 8 days ago                            agitated_edison
4b07fcc45271        python              "python3"                2 weeks ago          Exited (255) 8 days ago                          pyC
1cc06f213eb7        abee520343a4        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        compassionate_kowalevski
8c1eb67f7325        1b1c7b120b48        "/bin/sh -c 'cd /opt…"   3 months ago         Exited (255) 3 months ago                        dreamy_jepsen
1406d7476a28        1180f37ef8b1        "/bin/sh -c 'mkdir -…"   3 months ago         Exited (35) 3 months ago                         upbeat_taussig
e88bcf7743e2        f0f5acc11f91        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        tender_cohen

I had made some changes in a container which was created using one of hadoop image as below

debian@osboxes:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
python              latest              eeadc22d21a9        2 weeks ago         933MB
hadoop-build-1001   latest              1d1a162a72a6        3 months ago        2.02GB
hadoop-build        latest              5c1480006f78        3 months ago        1.96GB
ubuntu              xenial              5f2bf26e3524        3 months ago        123MB

I powered off the machine and rebooted etc.
I want to know that I made changes to one of the containers say in above output of docker ps -a the container was

25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1)

how can after a reboot etc I connect or start the same container again.
What I am currently doing is

docker run -it 1d1a162a72a6 /bin/bash

I make some changes and run a few python programms. But after a reboot all the changes are gone that means those python files which I had edited I have to copy paste them again in the container and do every thing from scratch.I have to install vim each time and then each time I do apt-get update install softwares and then check edit the programe.
I am not able to understand how to go back to same container which was created moments ago before exiting. What mistake I am doing here?

Body:
docker run always starts a new container.  You can re-attach to the existing container provided it wasn't started with --rm using docker start:

docker start -ai <CONTAINER_ID>

Notice that you should use container ID, not image ID as a parameter to docker start. See more in Docker help:

$ docker start --help

Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]

Start one or more stopped containers

Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals
      --detach-keys string   Override the key sequence for detaching a container
  -i, --interactive          Attach container's STDIN


问:
How to validate access tokens from different identity providers
I have 2 different ways of login into the application

End Customer or External user

Developer or Internal user

End customer or external user will login into the application at enterprise gateway.
  This login is common for multiple applications and will use reverse
  proxy to load the requested app.

Developers will login into the application using application gateway.

The End user has already authenticated, he would have the access token embedded in the request. How can we validate this access token? The token was generated by the identity server at Enterprise level.

The internal user will be redirected to login page. He would login via Identity server at application level.

Is there a way, I can proxy the Identity server at application level to validate the token generated by the enterprise identity server.

答: For enterprise user, you could have reverse proxy server to set special header to indicate request is from end user. If reverse proxy sends JWT, your application can introspect it locally. If reverse proxy sends opaque access_token, your application will have to remotely introspect the token.</p>


问:
How to check if a character is a letter or a number in javascript?
I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance

```<code>function CHECKCHARATCTER(Letter) {
    if (Letter.length <= 1) {
      if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
        return "Alphabhate";
      }
      else if (47 < Letter.charCodeAt(0) < 58) {
        return "NUMBER";
      }
      else { return "Its NOt a NUMBER or Alphabets"; }
    }
    else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);
</code>```

答:
Here:

```<code>if (64 < Letter.charCodeAt(0) < 91) //...
</code>```

JS isn't Python. You can't simply do a < b < c, you need to explicitly use the logical && operator: (a < b) && (b < c).

Body:
I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance

function CHECKCHARATCTER(Letter) {
    if (Letter.length <= 1) {
      if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
        return "Alphabhate";
      }
      else if (47 < Letter.charCodeAt(0) < 58) {
        return "NUMBER";
      }
      else { return "Its NOt a NUMBER or Alphabets"; }
    }
    else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);

Body:
Here:

if (64 < Letter.charCodeAt(0) < 91) //...

JS isn't Python. You can't simply do a < b < c, you need to explicitly use the logical && operator: (a < b) && (b < c).


问:
Rails 3 Handling Javascript for Mobile Users
I have a mobile version of my site that I'm developing. I'm using the technique described in Ryan Bates' Railscast episode to do the mobile detection. In a nut, you have to write a controller action that detects whether this is a mobile browser, and if so, set the request format to "mobile". So you can have views with the name format "file.mobile.erb" alongside "file.html.erb".

This works great. But I have a remote script execution to support, and I'd consequently like to have it serve up a mobile version of the Javascript as well.

Here's the form declaration in the view:

```<code><%= form_for :humanity, :url=>{:action=>"human"}, :remote=>true do |h| %>
</code>```

On the desktop version, it calls the controller action properly. In the log:

```<code>Processing by CardsController#human as JS
</code>```

But when I call it from the mobile version, the log doesn't pick it out as JS:

```<code>Processing by CardsController#human as */*
</code>```

So I first have to figure out how to get the form to tell the controller that it wants Javascript. Assuming I can do that, then I think this modification to @rbates' code should lock me in (as suggested by a commenter on that Railscast post). This is in application_controller.rb, in the prepare_for_mobile method:

```<code>if mobile_device?
    if request.format == :js
        request.format = :mobilejs
    else
        request.format = :mobile
    end
end
</code>```

So I have a "human.mobilejs.erb" file ready to fire, except it can't until the controller rightfully acknowledges that it's getting a JS request!

Looking forward to your generous assistance!

Aaron

答:
Add !request.xhr? in the following function in your application_controller.rb

```<code>def prepare_for_mobile
  session[:mobile_param] = params[:mobile] if params[:mobile]
  request.format = :mobile if mobile_device? && !request.xhr?
end
</code>```

It will respond to .js request with format.js

Also, as genkilabs suggested, use mobile_fu. It is awesome.

Body:
I have a mobile version of my site that I'm developing. I'm using the technique described in Ryan Bates' Railscast episode to do the mobile detection. In a nut, you have to write a controller action that detects whether this is a mobile browser, and if so, set the request format to "mobile". So you can have views with the name format "file.mobile.erb" alongside "file.html.erb".

This works great. But I have a remote script execution to support, and I'd consequently like to have it serve up a mobile version of the Javascript as well.

Here's the form declaration in the view:

<%= form_for :humanity, :url=>{:action=>"human"}, :remote=>true do |h| %>

On the desktop version, it calls the controller action properly. In the log:

Processing by CardsController#human as JS

But when I call it from the mobile version, the log doesn't pick it out as JS:

Processing by CardsController#human as */*

So I first have to figure out how to get the form to tell the controller that it wants Javascript. Assuming I can do that, then I think this modification to @rbates' code should lock me in (as suggested by a commenter on that Railscast post). This is in application_controller.rb, in the prepare_for_mobile method:

if mobile_device?
    if request.format == :js
        request.format = :mobilejs
    else
        request.format = :mobile
    end
end

So I have a "human.mobilejs.erb" file ready to fire, except it can't until the controller rightfully acknowledges that it's getting a JS request!

Looking forward to your generous assistance!

Aaron

Body:
Add !request.xhr? in the following function in your application_controller.rb

def prepare_for_mobile
  session[:mobile_param] = params[:mobile] if params[:mobile]
  request.format = :mobile if mobile_device? && !request.xhr?
end

It will respond to .js request with format.js

Also, as genkilabs suggested, use mobile_fu. It is awesome.


问:
How function match in scala?
```<code>case class Person(name:String,age:Int)

val p1 = Person("Maria",18)

def h(x:Person) = x match{
 case y if y.age >17 => "Adult"
 case z if z.age <=17 => "Younger"
}
</code>```

Why in the cases it refers to the age with y or z if the parameter containing the values is x?

答:
It is because case y means pattern everything and name the variable y, so it is basically creating a new variable that refers to the same object.

However, this is a poor use of pattern matching.

A better alternative would be:

```<code>def h(person: Person): String = person match {
  case Person(_, age) if (age > 17) => "Adult"
  case _ => "Younger" // Checking the age here is redudant.
}
</code>```

Or just use if / else:

```<code>def h(person: Person): String =
  if (person.age > 17) "Adult"
  else "Younger"
</code>```

Title: How function match in scala?

Body:
case class Person(name:String,age:Int)

val p1 = Person("Maria",18)

def h(x:Person) = x match{
 case y if y.age >17 => "Adult"
 case z if z.age <=17 => "Younger"
}

Why in the cases it refers to the age with y or z if the parameter containing the values is x?

Body:
It is because case y means pattern everything and name the variable y, so it is basically creating a new variable that refers to the same object.

However, this is a poor use of pattern matching.

A better alternative would be:

def h(person: Person): String = person match {
  case Person(_, age) if (age > 17) => "Adult"
  case _ => "Younger" // Checking the age here is redudant.
}

Or just use if / else:

def h(person: Person): String =
  if (person.age > 17) "Adult"
  else "Younger"


问:
Greatest of 3 numbers code not working for specific numbers
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:

```<code>a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

if (a > b) and (a > c):
    lnum = a

elif (b > a) and (b > c):
    lnum = b

else:
    lnum = c

print("The largest number is", lnum)
</code>```

Can anyone help me to understand why the output is showing 20 as greatest instead of 100?

答:
a = input("Enter 1st value") stores string into a you should convert it into integer by using int() method.
a = int(input("Enter 1st value")) or try a= input("Enter 1st value") then a=int(a).

Body:
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:

a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

if (a > b) and (a > c):
    lnum = a

elif (b > a) and (b > c):
    lnum = b

else:
    lnum = c

print("The largest number is", lnum)

Can anyone help me to understand why the output is showing 20 as greatest instead of 100?


问:
Is there PHP mysql_real_escape_string for postgresql?
Is there PHP mysql_real_escape_string for postgresql?
if yes then how ? please Give the Examples? & also the work of this string</p>

答: See pg_escape_string at http://www.php.net/manual/en/function.pg-escape-string.php.


问:
drawRoundRect in Android not working
I want to draw a rounded rectangle with drawRoundRect method in Android.

```<code>void drawRoundRect (RectF rect, float rx,  float ry, Paint paint)
</code>```

I'm using Android Studio, and my testing device use Android 6.0.1, API 23

This is part of my code. It works find when I put zeros in rx and ry.

```<code>public void draw(Canvas canvas){
        canvas.drawColor(Color.WHITE);
        canvas.drawRoundRect(rect, 0, 0, pnt);
}
</code>```

This draws a black rectangle in my screen.

But when I try to make it rounded,

```<code>public void draw(Canvas canvas){
        canvas.drawColor(Color.WHITE);
        canvas.drawRoundRect(rect, 10, 10, pnt);
}
</code>```

It draws nothing. This only draws white background....

I tried different numbers like 100, 3, 5, 0.03f etc in rx and ry,

but any numbers bigger than 0 make drawRoundRect() not working.

Is there anything wrong with my code...?

答:
You could do this,

RectF rect = new RectF(0f, 0f, width, height);

canvas.drawRoundRect(rect , 0, 0, mPaint);

Title: drawRoundRect in Android not working

Body:
I want to draw a rounded rectangle with drawRoundRect method in Android.

void drawRoundRect (RectF rect, float rx,  float ry, Paint paint)

I'm using Android Studio, and my testing device use Android 6.0.1, API 23

This is part of my code. It works find when I put zeros in rx and ry.

public void draw(Canvas canvas){
        canvas.drawColor(Color.WHITE);
        canvas.drawRoundRect(rect, 0, 0, pnt);
}

This draws a black rectangle in my screen.

But when I try to make it rounded,

public void draw(Canvas canvas){
        canvas.drawColor(Color.WHITE);
        canvas.drawRoundRect(rect, 10, 10, pnt);
}

It draws nothing. This only draws white background....

I tried different numbers like 100, 3, 5, 0.03f etc in rx and ry,

but any numbers bigger than 0 make drawRoundRect() not working.

Is there anything wrong with my code...?


问:
Javascript: Get instance getter and fields names or names and values
I usually use the next sentence to obtain all object fields but I just realized that is skips object getters

```<code>Object.entries(myInstance)
</code>```

I also tried without results:

```<code>Object.keys(myInstance)
Object.values(myInstance)
</code>```

There is any way to traverse the object attributes AND getters? I am interested in the name and value of the getter not the function itself.

答:
If a class declaration defines a method or a getter, they will defined on the prototype, and are not enumerable.

That is, they will appear neither of Object.keys, Object.getOwnPropertyNames, Reflect.ownKeys (they won't look up prototypes), nor in a for..in loop (it skips non-enumerable properties).

You have three ways:

Make the getter enumerable:

class Foo{
  /* contents of class */
}
Object.defineProperty(Foo.prototype, 'bar', {
  get: () => 'baz',
  enumerable: true,
  configurable: false //Or true
})
for(const prop in new Foo){
  console.log(prop)
}```
</div>
</div>
</p>

<ul>
<li>Define the getter on instances:</li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Foo{
  constructor() {
     Object.defineProperty(this, 'bar', {
      get: () => 'baz',
      enumerable: false,
      configurable: false //Or true
    })
  }
  /* contents of class */
}
console.log(Object.getOwnPropertyNames(new Foo))</code>```

Implement a custom lookup algorithm:

class Foo{
  get bar(){return 'baz'}
  /* class contents here */
}

Object.getAllPropertyNames = obj => new Set(obj != null //not null or undefined
  ? [
    ...Reflect.ownKeys(obj),
    ...Object.getAllPropertyNames(Object.getPrototypeOf(obj))
  ]
  : undefined
)

console.log(Array.from(Object.getAllPropertyNames(new Foo)))```

Body:
I usually use the next sentence to obtain all object fields but I just realized that is skips object getters

Object.entries(myInstance)

I also tried without results:

Object.keys(myInstance)
Object.values(myInstance)

There is any way to traverse the object attributes AND getters? I am interested in the name and value of the getter not the function itself.

Body:
If a class declaration defines a method or a getter, they will defined on the prototype, and are not enumerable.

That is, they will appear neither of Object.keys, Object.getOwnPropertyNames, Reflect.ownKeys (they won't look up prototypes), nor in a for..in loop (it skips non-enumerable properties).

You have three ways:

Make the getter enumerable:

class Foo{
  /* contents of class */
}
Object.defineProperty(Foo.prototype, 'bar', {
  get: () => 'baz',
  enumerable: true,
  configurable: false //Or true
})
for(const prop in new Foo){
  console.log(prop)
}

Define the getter on instances:

class Foo{
  constructor() {
     Object.defineProperty(this, 'bar', {
      get: () => 'baz',
      enumerable: false,
      configurable: false //Or true
    })
  }
  /* contents of class */
}
console.log(Object.getOwnPropertyNames(new Foo))

Implement a custom lookup algorithm:

class Foo{
  get bar(){return 'baz'}
  /* class contents here */
}

Object.getAllPropertyNames = obj => new Set(obj != null //not null or undefined
  ? [
    ...Reflect.ownKeys(obj),
    ...Object.getAllPropertyNames(Object.getPrototypeOf(obj))
  ]
  : undefined
)

console.log(Array.from(Object.getAllPropertyNames(new Foo)))


问:
Selecting updated rows between two tables
Good day,

I have to identical table structures. One is base table and second has incremental changes. I wish to have resulting table so that I pick he rows from the update, if present. Otherwise from old table.

Like so

```<code>table a: | Table b: | Result table:
key val  |  key val | key val
1   a    |  2   bb  |  1   a
2   b    |  4   dd  |  2   bb
3   c    |  5   ee  |  3   c
4   d    |          |  4   dd
                       5   ee
</code>```

I tried selecting B table values on inner join and full outer join where a.key is NULL or b.key is NULL and union. (Code not tested to functionality yet.)

```<code>select * from
(
  (select table_B.* from
    TABLE_A
      inner join
    TABLE_B
    on TABLE_A.key = TABLE_B.key
  )
  UNION
  (select * from
    TABLE_A
     full outer join
    TABLE_B
  on TABLE_A.key = TABLE_B.key
  where TABLE_A.key is NULL or TABLE_A.key is NULL
  )
)
</code>```

Is there an easier way to do this? I got the feeling that there has to be a more robust way to do this.

EDIT: I'm currently implementing this in the SPARK SQL context, but have had similar issues in the SQL server environment. Yet, I'm looking for a general idea.

答:
You don't mention which database you are using, so I'll assume it implements FULL OUTER JOIN. You can do:

```<code>select
  coalesce(a.key, b.key),
  case when b.key is not null then b.val else a.val end
from a
full outer join b on a.key = b.key
order by coalesce(a.key, b.key)
</code>```

Body:
Good day,

I have to identical table structures. One is base table and second has incremental changes. I wish to have resulting table so that I pick he rows from the update, if present. Otherwise from old table.

Like so

table a: | Table b: | Result table:
key val  |  key val | key val
1   a    |  2   bb  |  1   a
2   b    |  4   dd  |  2   bb
3   c    |  5   ee  |  3   c
4   d    |          |  4   dd
                       5   ee

I tried selecting B table values on inner join and full outer join where a.key is NULL or b.key is NULL and union. (Code not tested to functionality yet.)

select * from
(
  (select table_B.* from
    TABLE_A
      inner join
    TABLE_B
    on TABLE_A.key = TABLE_B.key
  )
  UNION
  (select * from
    TABLE_A
     full outer join
    TABLE_B
  on TABLE_A.key = TABLE_B.key
  where TABLE_A.key is NULL or TABLE_A.key is NULL
  )
)

Is there an easier way to do this? I got the feeling that there has to be a more robust way to do this.

EDIT: I'm currently implementing this in the SPARK SQL context, but have had similar issues in the SQL server environment. Yet, I'm looking for a general idea.

Body:
You don't mention which database you are using, so I'll assume it implements FULL OUTER JOIN. You can do:

select
  coalesce(a.key, b.key),
  case when b.key is not null then b.val else a.val end
from a
full outer join b on a.key = b.key
order by coalesce(a.key, b.key)


答:
you have to convert your inputs to int:

```<code>a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

print("The largest number is", max(map(int, (a, b, c))))
</code>```

Title: Greatest of 3 numbers code not working for specific numbers

Body:
you have to convert your inputs to int:

a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

print("The largest number is", max(map(int, (a, b, c))))


问:
Laravel, relationship problems
this is my first Laravel project and I have to do a LMS(learning management system).
I have a course table and an user table.

Here is my controller code:

```<code>public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = DB::table('Course')->join('Course_formation', 'course_id', '=', 'Course.id')

            ->select('Course.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }
</code>```

here is my view code:

```<code><tr>
 <td class="align-middle">{{ $cours->name }}</td>
 <td class="align-middle">{{ $cours->level}}</td>
 <td class="align-middle">{{ $cours->user() }}</td>
</tr>
@endforeach
@endif
</code>```

Course have a foreign key professor_id and I want to display the name of the user which created the course but have some errors

This is my Course model:

```<code>class Course extends Model
{

    protected $table = 'cours';
    public $timestamps = true;

    protected $fillable = [
        'name', 'lien', 'type', 'level', 'theme_id', 'prof_id'
    ];

    public function user()
    {
        return $this->hasOne('App\Models\User');
    }
}
</code>```

and this is my user model:

```<code>class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';
    public $timestamps = true;

    protected $fillable = [
        'pseudo', 'email', 'password', 'name', 'prenom', 'image'
    ];

    public function roles()
    {
          //return $this->belongsToMany('App\Models\Role', 'user_role', 'user_id', 'role_id');
          return $this->belongsToMany(Role::class);
    }

    public function cours()
    {
        return $this->belongsToMany('App\Models\Course', 'professor_id', 'id');
    }
}
</code>```

thanks for helping.

答:
Try this in your controller

```<code>$cours = Course::with('cours')
                 ->where('id' , $id)
                 ->get();

</code>```

And In Course Model

```<code>public function user()
    {
        return $this->hasMany('App\Models\User' , 'prof_id');
    }
</code>```

in User Model

```<code>public function cours() {
          return $this->belongsToMany('App\model\Course', 'prof_id', 'id');
    }
</code>```

Relation Depends on You But it look like this..Hope it will help lil bit

Title: Laravel, relationship problems

Body:
this is my first Laravel project and I have to do a LMS(learning management system).
I have a course table and an user table.

Here is my controller code:

public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = DB::table('Course')->join('Course_formation', 'course_id', '=', 'Course.id')

            ->select('Course.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }

here is my view code:

 {{ $cours->name }}
 {{ $cours->level}}
 {{ $cours->user() }}

@endforeach
@endif

Course have a foreign key professor_id and I want to display the name of the user which created the course but have some errors

This is my Course model:

class Course extends Model
{

    protected $table = 'cours';
    public $timestamps = true;

    protected $fillable = [
        'name', 'lien', 'type', 'level', 'theme_id', 'prof_id'
    ];

    public function user()
    {
        return $this->hasOne('App\Models\User');
    }
}

and this is my user model:

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';
    public $timestamps = true;

    protected $fillable = [
        'pseudo', 'email', 'password', 'name', 'prenom', 'image'
    ];

    public function roles()
    {
          //return $this->belongsToMany('App\Models\Role', 'user_role', 'user_id', 'role_id');
          return $this->belongsToMany(Role::class);
    }

    public function cours()
    {
        return $this->belongsToMany('App\Models\Course', 'professor_id', 'id');
    }
}

thanks for helping.

Body:
Try this in your controller

$cours = Course::with('cours')
                 ->where('id' , $id)
                 ->get();

And In Course Model

public function user()
    {
        return $this->hasMany('App\Models\User' , 'prof_id');
    }

in User Model

public function cours() {
          return $this->belongsToMany('App\model\Course', 'prof_id', 'id');
    }

Relation Depends on You But it look like this..Hope it will help lil bit


问:
How to recursively append to file name in powershell?
I have multiple .txt files in folders/their sub-folders.

I want to append _old to their file names.

I tried:

```<code>Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace '.txt','_old.txt' }
</code>```

This results in:

Some files get updated correctly

Some files get updated incorrectly - they get _old twice - example: .._old_old.txt

There are few errors: Rename-Item : Source and destination path must be different.

答:
To prevent already renamed files from accidentally reentering the file enumeration and therefore getting renamed multiple times, enclose your Get-ChildItem call in (), the grouping operator, which ensures that all output is collected first[1], before sending the results through the pipeline:

```<code>(Get-ChildItem -Recurse) |
  Rename-Item -NewName { $_.name -replace '\.txt$', '_old.txt' }
</code>```

Note that I've used \.txt$ as the regex[2], so as to ensure that only a literal . (\.) followed by string txt at the end ($) of the file name is matched, so as to prevent false positives (e.g., a file named Atxt.csv or even a directory named AtxtB would accidentally match your original regex).

Note: The need to collect all Get-ChildItem output first arises from how the PowerShell pipeline fundamentally works: objects are (by default) sent to the pipeline one by one, and processed by a receiving command as they're being received. This means that, without (...) around Get-ChildItem,  Rename-Item starts renaming files before Get-ChildItem has finished enumerating files, which causes problems. See this answer for more information about how the PowerShell pipeline works.

Tip of the hat to Matthew for suggesting inclusion of this information.

However, I suggest optimizing your command as follows:

```<code>(Get-ChildItem -Recurse -File -Filter *.txt) |
  Rename-Item -NewName { $_.BaseName + '_old' + $_.Extension }
</code>```

-File limits the the output to files (doesn't also return directories).

-Filter is the fastest way to limit results to a given wildcard pattern.

$_.BaseName + '_old' + $_.Extension uses simple string concatenation via the sub-components of a file name.

An alternative is to stick with -replace:

$_.Name -replace '\.[^.]+$', '_old$&'

Note that if you wanted to run this repeatedly and needed to exclude files renamed in a previous run, add -Exclude *_old.txt to the Get-ChildItem call.

[1] Due to a change in how Get-ChildItem is implemented in PowerShell [Core] 6+ (it now internally sorts the results, which invariably requires collecting them all first), the (...) enclosure is no longer strictly necessary, but this could be considered an implementation detail, so for conceptual clarity it's better to continue to use (...).

[2] PowerShell's -replace operator operates on regexes (regular expressions); it doesn't perform literal substring searches the way that the [string] type's .Replace() method does.

Body:
I have multiple .txt files in folders/their sub-folders.

I want to append _old to their file names.

I tried:

Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace '.txt','_old.txt' }

This results in:

Some files get updated correctly

Some files get updated incorrectly - they get _old twice - example: .._old_old.txt

There are few errors: Rename-Item : Source and destination path must be different.

Body:
To prevent already renamed files from accidentally reentering the file enumeration and therefore getting renamed multiple times, enclose your Get-ChildItem call in (), the grouping operator, which ensures that all output is collected first[1], before sending the results through the pipeline:

(Get-ChildItem -Recurse) |
  Rename-Item -NewName { $_.name -replace '\.txt$', '_old.txt' }

Note that I've used \.txt$ as the regex[2], so as to ensure that only a literal . (\.) followed by string txt at the end ($) of the file name is matched, so as to prevent false positives (e.g., a file named Atxt.csv or even a directory named AtxtB would accidentally match your original regex).

Note: The need to collect all Get-ChildItem output first arises from how the PowerShell pipeline fundamentally works: objects are (by default) sent to the pipeline one by one, and processed by a receiving command as they're being received. This means that, without (...) around Get-ChildItem,  Rename-Item starts renaming files before Get-ChildItem has finished enumerating files, which causes problems. See this answer for more information about how the PowerShell pipeline works.

Tip of the hat to Matthew for suggesting inclusion of this information.

However, I suggest optimizing your command as follows:

(Get-ChildItem -Recurse -File -Filter *.txt) |
  Rename-Item -NewName { $_.BaseName + '_old' + $_.Extension }

-File limits the the output to files (doesn't also return directories).

-Filter is the fastest way to limit results to a given wildcard pattern.

$_.BaseName + '_old' + $_.Extension uses simple string concatenation via the sub-components of a file name.

An alternative is to stick with -replace:

$_.Name -replace '\.[^.]+$', '_old$&'

Note that if you wanted to run this repeatedly and needed to exclude files renamed in a previous run, add -Exclude *_old.txt to the Get-ChildItem call.

[1] Due to a change in how Get-ChildItem is implemented in PowerShell [Core] 6+ (it now internally sorts the results, which invariably requires collecting them all first), the (...) enclosure is no longer strictly necessary, but this could be considered an implementation detail, so for conceptual clarity it's better to continue to use (...).

[2] PowerShell's -replace operator operates on regexes (regular expressions); it doesn't perform literal substring searches the way that the [string] type's .Replace() method does.


答:
You could do this easier with max(list) when you store your values in a list. Example:

```<code>values = []
values.append(int(input('Enter 1st value ')))
values.append(int(input('Enter 2st value ')))
values.append(int(input('Enter 3st value ')))

lnum = max(values)

print("The largest number is", lnum)
</code>```

Body:
You could do this easier with max(list) when you store your values in a list. Example:

values = []
values.append(int(input('Enter 1st value ')))
values.append(int(input('Enter 2st value ')))
values.append(int(input('Enter 3st value ')))

lnum = max(values)

print("The largest number is", lnum)


问:
open a text area on click of a button - Jquery
Solution here: http://jsfiddle.net/kralco626/E9XVr/53/

Note: I think this is a duplicate of this question: how to show text area on button click? However, the OP of that question never followed up and I don't think any of the answers actually answer the question. I think Tomalak's comment on that question

Seems to me that, if anything, he wanted to pop up a textarea, wait for input into it, have the user press some 'OK' button then store the result in a variable.

Pretty much sums it up.

When the user clicks a button, I would like a text area to open in which the user can enter some text click an OK button and then the text area will close.

I don't want a dialog box, it's too intrusive, I want just a plain simple textarea or similar to open so that the top left of the text area is positioned at the bottom left of the button.

Thanks!

```<code><span style="width:20px;height:20px" class="remarkButton"></span>

$(".remarkButton").button({ icons: { primary: "ui-icon-pencil" }, text: false }).click(function () {
       $(...something to show text area...).data("$clickedButton",$(this));
});

//called when the OK button on the text area is clicked
function saveRemark($referenceToTextArea)
{
$referenceToTextArea.data("$clickedButton").data("remark",$referenceToTextArea.text());
}
</code>```

答:
OK, I've knocked something up very quickly -- it doesn't exactly match your specifications, but it's something similar.  See jsFiddle.

The Javascript:

```<code>$('#foo').click(function() { // the button - could be a class selector instead
    var button = $(this),
        commentField = $('<textarea/>'); // create a textarea element

    commentField
        .css({
            position: 'absolute',
            width: 200,          // textbox 200px by 100px
            height: 100,
            // position the textarea directly over the button
            left: button.offset().left + (button.outerWidth() / 2) - 100,
            top: button.offset().top + (button.outerHeight() / 2) - 50
        })
        // set the textarea's value to be the saved content, or a default if there is no saved content
        .val(button.data('textContent') || 'This is my comment field\'s text')
        // set up a keypress handler on the textarea
        .keypress(function(e) {
            if (e.which === 13) { // if it's the enter button
                e.preventDefault(); // ignore the line break
                button.data('textContent', this.value); // save the content to the button
                $(this).remove(); // remove the textarea
            }
        })
        .appendTo(document.body); // add the textarea to the document
});
</code>```

The main difference to the specification is that the textarea closes when you press "enter", not on clicking a button. It wouldn't be hard to modify if that's what you want.

Body:
Solution here: http://jsfiddle.net/kralco626/E9XVr/53/

Note: I think this is a duplicate of this question: how to show text area on button click? However, the OP of that question never followed up and I don't think any of the answers actually answer the question. I think Tomalak's comment on that question

Seems to me that, if anything, he wanted to pop up a textarea, wait for input into it, have the user press some 'OK' button then store the result in a variable.

Pretty much sums it up.

When the user clicks a button, I would like a text area to open in which the user can enter some text click an OK button and then the text area will close.

I don't want a dialog box, it's too intrusive, I want just a plain simple textarea or similar to open so that the top left of the text area is positioned at the bottom left of the button.

Thanks!

$(".remarkButton").button({ icons: { primary: "ui-icon-pencil" }, text: false }).click(function () {
       $(...something to show text area...).data("$clickedButton",$(this));
});

//called when the OK button on the text area is clicked
function saveRemark($referenceToTextArea)
{
$referenceToTextArea.data("$clickedButton").data("remark",$referenceToTextArea.text());
}

Body:
OK, I've knocked something up very quickly -- it doesn't exactly match your specifications, but it's something similar.  See jsFiddle.

The Javascript:

$('#foo').click(function() { // the button - could be a class selector instead
    var button = $(this),
        commentField = $('<textarea/>'); // create a textarea element

    commentField
        .css({
            position: 'absolute',
            width: 200,          // textbox 200px by 100px
            height: 100,
            // position the textarea directly over the button
            left: button.offset().left + (button.outerWidth() / 2) - 100,
            top: button.offset().top + (button.outerHeight() / 2) - 50
        })
        // set the textarea's value to be the saved content, or a default if there is no saved content
        .val(button.data('textContent') || 'This is my comment field\'s text')
        // set up a keypress handler on the textarea
        .keypress(function(e) {
            if (e.which === 13) { // if it's the enter button
                e.preventDefault(); // ignore the line break
                button.data('textContent', this.value); // save the content to the button
                $(this).remove(); // remove the textarea
            }
        })
        .appendTo(document.body); // add the textarea to the document
});

The main difference to the specification is that the textarea closes when you press "enter", not on clicking a button. It wouldn't be hard to modify if that's what you want.


问:
ISNA: Return "YES", "NO" in nested formula
I'm trying to get it to return YES/NO instead of the the lookup value/#N/A by using ISNA, but I'm not sure where to place it.

Here is my formula:

```<code>=IF(AND([@Center]="London",[@Reportable]="YES"),VLOOKUP([@ID],Client!C:C,1,FALSE),"IGNORE")
</code>```

答:
Try using MATCH as you only want to know if it's in the list.  This will return its location in the list or #N/A (VLOOKUP may return something that's not a number).

You can then check if it's numeric and return Yes / No as required:

```<code>=IF(AND([@Center]="London",[@Reportable]="YES"),IF(ISNUMBER(MATCH([@ID],Client!C:C,0)),"Yes","No"),"IGNORE")
</code>```

Body:
I'm trying to get it to return YES/NO instead of the the lookup value/#N/A by using ISNA, but I'm not sure where to place it.

Here is my formula:

=IF(AND([@Center]="London",[@Reportable]="YES"),VLOOKUP([@ID],Client!C:C,1,FALSE),"IGNORE")

Body:
Try using MATCH as you only want to know if it's in the list.  This will return its location in the list or #N/A (VLOOKUP may return something that's not a number).

You can then check if it's numeric and return Yes / No as required:

=IF(AND([@Center]="London",[@Reportable]="YES"),IF(ISNUMBER(MATCH([@ID],Client!C:C,0)),"Yes","No"),"IGNORE")


问:
How to to display images according to id (Filters)
I want to display images in a div according to select option (onclick = "DispImg())
I get 2 problem's

I store the images in array and I display all of theme and when you select an option it will automatically display the images that have the correct id .

and this is my script : I want to add to every image an id but the (setAttribute) method dosn't work and when you chose what id the script will display only the images that have the same id .

var imgArray = new Array();

var corp = document.getElementById('range_imgs');

imgArray[0] = new Image();
imgArray[0].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fdefinitions%2Funivers-etoile-3730%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAD";
imgArray[0].setAttribute("id" , "2");

imgArray[1] = new Image();
imgArray[1].src = "https://www.google.com/url?sa=i&url=http%3A%2F%2Fvivre-marrakech.com%2Fblog%2Ffaire%2Fobserver-les-etoiles-a-marrakech%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAI";
imgArray[1].setAttribute("id" , "1");

imgArray[2] = new Image();
imgArray[2].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.numerama.com%2Fsciences%2F537548-au-lieu-detre-avalee-par-un-trou-noir-cette-etoile-sest-echappee-a-toute-vitesse.html&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAN";
imgArray[2].setAttribute("id" , "3");

imgArray[3] = new Image();
imgArray[3].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geowiki.fr%2Findex.php%3Ftitle%3D%25C3%2589toile&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAS";
imgArray[3].setAttribute("id" , "2");

imgArray[4] = new Image();
imgArray[4].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fquestions-reponses%2Fespace-quest-ce-quune-etoile-157%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAX";
imgArray[4].setAttribute("id" , "1");

  for(var i=0;i<imgArray.length;i++){
    var imges = document.createElement("img");
      imges.src = imgArray[i].src;
      imges.style.marginRight = "15px";
      corp.appendChild(imges);
  }

  function appFilter(ele){

      var pics = document.querySelectorAll("img");

          if(pics.id == "1"){

          }

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <select id="allimgs" name="allimmages" >
      <option value="1et" onclick="appfilter(1)">img with id=1</option>
      <option value="2et" onclick="appfilter(2)">img with id=2</option>
      <option value="3et" onclick="appfilter(3)">img with id=3</option>
  </select>
</form>
<div id="range_imgs">
</div></code>```

Thank you !!

答:
Instead of setAttribute you can replace with just .id but both should work fine

```<code>imgArray[x].id = x
</code>```

your filter also won't work. replace with something like this

the pics variable is an array so pic.id won't work

```<code>var pics = document.querySelectorAll("img");
pics.forEach(function(pic) {
  if (pic.attr('id') == 2) {
    // do something
  }
})

</code>```

Body:
I want to display images in a div according to select option (onclick = "DispImg())
I get 2 problem's

I store the images in array and I display all of theme and when you select an option it will automatically display the images that have the correct id .

and this is my script : I want to add to every image an id but the (setAttribute) method dosn't work and when you chose what id the script will display only the images that have the same id .

var imgArray = new Array();

var corp = document.getElementById('range_imgs');

imgArray[0] = new Image();
imgArray[0].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fdefinitions%2Funivers-etoile-3730%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAD";
imgArray[0].setAttribute("id" , "2");

imgArray[1] = new Image();
imgArray[1].src = "https://www.google.com/url?sa=i&url=http%3A%2F%2Fvivre-marrakech.com%2Fblog%2Ffaire%2Fobserver-les-etoiles-a-marrakech%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAI";
imgArray[1].setAttribute("id" , "1");

imgArray[2] = new Image();
imgArray[2].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.numerama.com%2Fsciences%2F537548-au-lieu-detre-avalee-par-un-trou-noir-cette-etoile-sest-echappee-a-toute-vitesse.html&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAN";
imgArray[2].setAttribute("id" , "3");

imgArray[3] = new Image();
imgArray[3].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geowiki.fr%2Findex.php%3Ftitle%3D%25C3%2589toile&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAS";
imgArray[3].setAttribute("id" , "2");

imgArray[4] = new Image();
imgArray[4].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fquestions-reponses%2Fespace-quest-ce-quune-etoile-157%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAX";
imgArray[4].setAttribute("id" , "1");

  for(var i=0;i<imgArray.length;i++){
    var imges = document.createElement("img");
      imges.src = imgArray[i].src;
      imges.style.marginRight = "15px";
      corp.appendChild(imges);
  }

  function appFilter(ele){

      var pics = document.querySelectorAll("img");

          if(pics.id == "1"){

          }

  }

<form>
  <select id="allimgs" name="allimmages" >
      <option value="1et" onclick="appfilter(1)">img with id=1</option>
      <option value="2et" onclick="appfilter(2)">img with id=2</option>
      <option value="3et" onclick="appfilter(3)">img with id=3</option>
  </select>
</form>

Thank you !!

Body:
Instead of setAttribute you can replace with just .id but both should work fine

imgArray[x].id = x

your filter also won't work. replace with something like this

the pics variable is an array so pic.id won't work

var pics = document.querySelectorAll("img");
pics.forEach(function(pic) {
  if (pic.attr('id') == 2) {
    // do something
  }
})


问:
Azure blob sasToken “Signature did not match” (java)
Hello I try to create a SAS to a blob on azure storage in java.
I write the following code:

```<code>  public static String GSAS(String url, String signedstart, String signedexpiry) throws
     Exception {

    String accountName = "taelearninguat2";
    String accountKey = "xxxx"; // Here I hide the passsword

    String signedpermissions = "r";

    signedstart = "2020-02-18T08:49Z";
    signedexpiry = "2020-02-28T08:49Z";

    String canonicalizedResource = "/blob/" + accountName + "/resource/8a5dcc036edbba6a016ede49fec30000.jpg";

    String signedIP = "";
    String signedProtocol = "";
    String signedidentifier = "";
    String signedversion = "2015-04-05";
    String rscc = "";
    String responsecontent = "file; attachment";
    String rsce = "";
    String rscl = "";
    String rsct = "binary";

    String stringToSign =
            signedpermissions + "\n" +
                    signedstart + "\n" +
                    signedexpiry + "\n" +
                    canonicalizedResource + "\n" +
                    signedidentifier + "\n" +
                    signedIP + "\n" +
                    signedProtocol + "\n" +
                    signedversion + "\n" +
                    rscc + "\n" +
                    responsecontent + "\n" +
                    rsce + "\n" +
                    rscl + "\n" +
                    rsct;

   String sig = computeHmac256(stringToSign,Base64.getDecoder().decode(accountKey));

    StringBuffer param = new StringBuffer();
    param.append("?")
            .append("sv=").append(URLEncoder.encode(signedversion, "UTF-8")).append("&")
            .append("sr=").append(URLEncoder.encode("b", "UTF-8")).append("&")
            .append("sig=").append(URLEncoder.encode(sig, "UTF-8")).append("&")
            .append("st=").append(URLEncoder.encode(signedstart, "UTF-8")).append("&")
            .append("se=").append(URLEncoder.encode(signedexpiry, "UTF-8")).append("&")
            .append("sp=").append(URLEncoder.encode(signedpermissions, "UTF-8")).append("&")
            .append("rscd=").append(URLEncoder.encode(responsecontent, "UTF-8")).append("&")
            .append("rsct=").append(URLEncoder.encode(rsct, "UTF-8"));
    String sasURL = url + param.toString();
    return sasURL;
}

static String computeHmac256(String stringToSign, byte[] accountKey) throws Exception {
    try {
        /*
        We must get a new instance of the Mac calculator for each signature calculated because the instances are
        not threadsafe and there is some suggestion online that they may not even be safe for reuse, so we use a
        new one each time to be sure.
         */
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        hmacSha256.init(new SecretKeySpec(accountKey, "HmacSHA256"));
        byte[] utf8Bytes = stringToSign.getBytes("UTF-8");
        return Base64.getEncoder().encodeToString(hmacSha256.doFinal(utf8Bytes));
    } catch (Exception e) {
        throw new Error(e);
    }
}
</code>```

Suppose I have a picture which url is : https://taelearninguat2.blob.core.chinacloudapi.cn/resource/8a5dcc036edbba6a016ede49fec30000.jpg

so the stringToSign is :

```<code>r
2020-02-18T08:49Z
2020-02-28T08:49Z
/blob/taelearninguat2/resource/8a5dcc036edbba6a016ede49fec30000.jpg

2015-04-05

file; attachment

binary
</code>```

SAS url : https://taelearninguat2.blob.core.chinacloudapi.cn/resource/8a5dcc036edbba6a016ede49fec30000.jpg?sv=2015-04-05&sr=b&sig=IbBspyUvIyOoxq7XRs7nQ3zHK%2BrlZzoen9jwSN%2B1Yfw%3D&st=2020-02-18T08%3A49Z&se=2020-02-28T08%3A49Z&sp=r&rscd=file%3B+attachment&rsct=binary

```<code><AuthenticationErrorDetail>Signature did not match. String to sign used was r 2020-02-18T08:49Z 2020-02-28T08:49Z /blob/taelearninguat2/resource/8a5dcc036edbba6a016ede49fec30000.jpg 2015-04-05 file; attachment</AuthenticationErrorDetail>
</code>```

new update:
alter the time params:
signedstart = 2019-11-27
signedexpiry = 2019-12-04
then result to be :
Signature not valid in the specified time frame: Start [Wed, 27 Nov 2019 00:00:00 GMT] - Expiry [Wed, 04 Dec 2019 00:00:00 GMT] - Current [Thu, 20 Feb 2020 14:45:57 GMT]

but
signedstart = 2020-02-19
signedexpiry = 2020-02-25
still signature not match

答:
Please try changing the following line of code:

```<code>byte[] shaSig = HMACSHA256(stringToSign, accountKey);
</code>```

to

```<code>byte[] shaSig = HMACSHA256(stringToSign, Base64.getDecoder().decode(accountKey));
</code>```

Basically your account key is a base64 encoded string you would need to decode it first.

You can also take a look at the code here as to how Azure SDK is doing the signing: https://github.com/Azure/azure-sdk-for-java/blob/1e2982e008aead0453e2295d41df5352c603fd34/storage/data-plane/src/main/java/com/microsoft/azure/storage/blob/SharedKeyCredentials.java#L213

Body:
Hello I try to create a SAS to a blob on azure storage in java.
I write the following code:

  public static String GSAS(String url, String signedstart, String signedexpiry) throws
     Exception {

    String accountName = "taelearninguat2";
    String accountKey = "xxxx"; // Here I hide the passsword

    String signedpermissions = "r";

    signedstart = "2020-02-18T08:49Z";
    signedexpiry = "2020-02-28T08:49Z";

    String canonicalizedResource = "/blob/" + accountName + "/resource/8a5dcc036edbba6a016ede49fec30000.jpg";

    String signedIP = "";
    String signedProtocol = "";
    String signedidentifier = "";
    String signedversion = "2015-04-05";
    String rscc = "";
    String responsecontent = "file; attachment";
    String rsce = "";
    String rscl = "";
    String rsct = "binary";

    String stringToSign =
            signedpermissions + "\n" +
                    signedstart + "\n" +
                    signedexpiry + "\n" +
                    canonicalizedResource + "\n" +
                    signedidentifier + "\n" +
                    signedIP + "\n" +
                    signedProtocol + "\n" +
                    signedversion + "\n" +
                    rscc + "\n" +
                    responsecontent + "\n" +
                    rsce + "\n" +
                    rscl + "\n" +
                    rsct;

   String sig = computeHmac256(stringToSign,Base64.getDecoder().decode(accountKey));

    StringBuffer param = new StringBuffer();
    param.append("?")
            .append("sv=").append(URLEncoder.encode(signedversion, "UTF-8")).append("&")
            .append("sr=").append(URLEncoder.encode("b", "UTF-8")).append("&")
            .append("sig=").append(URLEncoder.encode(sig, "UTF-8")).append("&")
            .append("st=").append(URLEncoder.encode(signedstart, "UTF-8")).append("&")
            .append("se=").append(URLEncoder.encode(signedexpiry, "UTF-8")).append("&")
            .append("sp=").append(URLEncoder.encode(signedpermissions, "UTF-8")).append("&")
            .append("rscd=").append(URLEncoder.encode(responsecontent, "UTF-8")).append("&")
            .append("rsct=").append(URLEncoder.encode(rsct, "UTF-8"));
    String sasURL = url + param.toString();
    return sasURL;
}

static String computeHmac256(String stringToSign, byte[] accountKey) throws Exception {
    try {
        /*
        We must get a new instance of the Mac calculator for each signature calculated because the instances are
        not threadsafe and there is some suggestion online that they may not even be safe for reuse, so we use a
        new one each time to be sure.
         */
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        hmacSha256.init(new SecretKeySpec(accountKey, "HmacSHA256"));
        byte[] utf8Bytes = stringToSign.getBytes("UTF-8");
        return Base64.getEncoder().encodeToString(hmacSha256.doFinal(utf8Bytes));
    } catch (Exception e) {
        throw new Error(e);
    }
}

Suppose I have a picture which url is : https://taelearninguat2.blob.core.chinacloudapi.cn/resource/8a5dcc036edbba6a016ede49fec30000.jpg

so the stringToSign is :

r
2020-02-18T08:49Z
2020-02-28T08:49Z
/blob/taelearninguat2/resource/8a5dcc036edbba6a016ede49fec30000.jpg

2015-04-05

file; attachment

binary

SAS url : https://taelearninguat2.blob.core.chinacloudapi.cn/resource/8a5dcc036edbba6a016ede49fec30000.jpg?sv=2015-04-05&sr=b&sig=IbBspyUvIyOoxq7XRs7nQ3zHK%2BrlZzoen9jwSN%2B1Yfw%3D&st=2020-02-18T08%3A49Z&se=2020-02-28T08%3A49Z&sp=r&rscd=file%3B+attachment&rsct=binary

<AuthenticationErrorDetail>Signature did not match. String to sign used was r 2020-02-18T08:49Z 2020-02-28T08:49Z /blob/taelearninguat2/resource/8a5dcc036edbba6a016ede49fec30000.jpg 2015-04-05 file; attachment</AuthenticationErrorDetail>

new update:
alter the time params:
signedstart = 2019-11-27
signedexpiry = 2019-12-04
then result to be :
Signature not valid in the specified time frame: Start [Wed, 27 Nov 2019 00:00:00 GMT] - Expiry [Wed, 04 Dec 2019 00:00:00 GMT] - Current [Thu, 20 Feb 2020 14:45:57 GMT]

but
signedstart = 2020-02-19
signedexpiry = 2020-02-25
still signature not match

Body:
Please try changing the following line of code:

byte[] shaSig = HMACSHA256(stringToSign, accountKey);

to

byte[] shaSig = HMACSHA256(stringToSign, Base64.getDecoder().decode(accountKey));

Basically your account key is a base64 encoded string you would need to decode it first.

You can also take a look at the code here as to how Azure SDK is doing the signing: https://github.com/Azure/azure-sdk-for-java/blob/1e2982e008aead0453e2295d41df5352c603fd34/storage/data-plane/src/main/java/com/microsoft/azure/storage/blob/SharedKeyCredentials.java#L213


问:
This code compiles fine but file is not created?Please point out the error
I was just starting file handling and started to write the code to create, read and write using binary files, I passed the structure to it and tried to run it but i found out any file as specified in the code was not created in my directory though the code compiled fine. </p>

```<code>#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Student
{
    char name[20];
    int student_id;
    char department[20];
    char address[30];
};
ostream & operator <<(ostream &out,Student &s1)
{
    out<<"Name: "<<s1.name<<endl;
    out<<"Student Id: "<<s1.student_id<<endl;
    out<<"Department: "<<s1.department<<endl;
    out<<"Address: "<<s1.address<<endl;
}
int main()
{
    Student s1;
    strcpy(s1.name, "Sandeep");
    s1.student_id = 1;
    strcpy(s1.department,"BCT");
    strcpy(s1.address, "New Baneshwor,Kathmandu");
    fstream file;  //file part
    file.open("Student.dat",ios::in | ios::out |ios::binary); //create a file
    file.write((char*)(&s1),sizeof(Student)); //write to it
    if(file.is_open())
    {
        cout<<"nice"; //check if it's open(code not running)
    }
    file.seekg(0);
    file.read((char*)(&s1),sizeof(Student)); //read from a file just created
    cout<<s1;
    if(file.fail())
    {
        cout<<"Cannot create file"; //check if file is not created
    }
    file.close();

}
</code>```

答:
Because you use ios::in | ios::out, the file must already exist. You can do:

```<code>file.open("Student.dat", ios::in | ios::out | ios::binary);
if ( !file.is_open() ) {
   file.clear();
   file.open("Student.dat", ios::out | ios::binary );
   file.close();
   file.open("Student.dat", ios::in | ios::out | ios::binary);
}
</code>```

Shamelessly stolen from here

Body:
I was just starting file handling and started to write the code to create, read and write using binary files, I passed the structure to it and tried to run it but i found out any file as specified in the code was not created in my directory though the code compiled fine.

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Student
{
    char name[20];
    int student_id;
    char department[20];
    char address[30];
};
ostream & operator <<(ostream &out,Student &s1)
{
    out<<"Name: "<<s1.name<<endl;
    out<<"Student Id: "<<s1.student_id<<endl;
    out<<"Department: "<<s1.department<<endl;
    out<<"Address: "<<s1.address<<endl;
}
int main()
{
    Student s1;
    strcpy(s1.name, "Sandeep");
    s1.student_id = 1;
    strcpy(s1.department,"BCT");
    strcpy(s1.address, "New Baneshwor,Kathmandu");
    fstream file;  //file part
    file.open("Student.dat",ios::in | ios::out |ios::binary); //create a file
    file.write((char*)(&s1),sizeof(Student)); //write to it
    if(file.is_open())
    {
        cout<<"nice"; //check if it's open(code not running)
    }
    file.seekg(0);
    file.read((char*)(&s1),sizeof(Student)); //read from a file just created
    cout<<s1;
    if(file.fail())
    {
        cout<<"Cannot create file"; //check if file is not created
    }
    file.close();

}

Body:
Because you use ios::in | ios::out, the file must already exist. You can do:

file.open("Student.dat", ios::in | ios::out | ios::binary);
if ( !file.is_open() ) {
   file.clear();
   file.open("Student.dat", ios::out | ios::binary );
   file.close();
   file.open("Student.dat", ios::in | ios::out | ios::binary);
}

Shamelessly stolen from here


问:
Best practice using RecyclerView, ListAdapter and ViewModel for saving checked status
I am using RecyclerView with ListAdapter which using DiffUtil internally to show the data. Of course, all the data was provided by ViewModel via LiveData.

Now each item view has a CheckBox, meanwhile I implemented drag selection function by adding RecyclerView.SimpleOnItemTouchListener. Selection status is now maintained by the adapter, it is not a good idea since status will lost after screen rotation.

I want to let ViewModel save the selection status and it is my idea:

Fragment will call the ViewModel to change the status when receiving the relevant callback.

ViewModel will change the data list (or create a new one if it is not mutable) and post to LiveData.

Fragment receives the data change and submits it to ListAdapter.

The problem is that the selection status can change very frequently if user acitvate drag selection. DifferUtil has to spend a long time comparing if there are a lot of data. Unlike saving status inside the adapter, now I cannot notify item changed accurately because I don't know which position is changed.

The core idea of MVVM is data-driven view, but in this case we lost additional information(e.g. position) causing extra calculations. So what is the best practice?

Part of the adapter code (based on GroupListAdapter which extend ListAdapter):

```<code>    private val selectedGroups = mutableSetOf<Int>()
    private val selectedImages = mutableSetOf<Image>()

    override fun onBindGroupViewHolder(holder: StubViewHolder, groupIndex: Int, flattedPosition: Int) {
        holder.setText(R.id.itemImageTitleTextView, getGroupItem(groupIndex).title)
    }

    override fun onBindChildViewHolder(holder: StubViewHolder, groupIndex: Int, childIndex: Int, flattedPosition: Int) {
        val data = getChildItem(groupIndex, childIndex)
        GlideApp.with(fragment).load(data.uri).into(holder.getView(R.id.itemImageView))
    }

    override fun onBindGroupViewHolder(holder: StubViewHolder, groupIndex: Int, flattedPosition: Int,
                                       payloads: MutableList<Any>) {
        holder.setGroupSelectionMode(isInSelectMode())
        holder.setGroupChecked(selectedGroups.contains(flattedPosition))
    }

    override fun onBindChildViewHolder(holder: StubViewHolder, groupIndex: Int, childIndex: Int, flattedPosition: Int,
                                       payloads: MutableList<Any>) {
        if (isInSelectMode()) {
            holder.setImageSelectionMode(true)
            if (selectedImages.contains(getItem(flattedPosition))) {
                holder.getView<MaskImageView>(R.id.itemImageView).isChecked = true
                holder.setImageChecked(true)
            } else {
                holder.getView<MaskImageView>(R.id.itemImageView).isChecked = false
                holder.setImageChecked(false)
            }
        } else {
            holder.getView<MaskImageView>(R.id.itemImageView).isChecked = false
            holder.setImageSelectionMode(false)
        }
    }

    fun setSelected(position: Int, isSelected: Boolean, refreshItem: Boolean = true) {
        if (!isChildItem(position)) {
            return
        }
        if (isSelected) {
            selectedImages.add(getItem(position) as Image)
        } else {
            selectedImages.remove(getItem(position))
        }
        if (refreshItem) {
            notifyItemChanged(position, true)
        }
        onSelectChangedCallback?.invoke(selectedImages.size)
    }
</code>```

答: May be I'm mistaken, but looks like you are not using paging? Depending on your data nature, you could use any descendant datasources of https://developer.android.com/reference/androidx/paging/DataSource.html. Your DiffUtils would then operate on much smaller subset of data. You could offset selected items (I'm assuming it can be more then one) to viewmodel, keep them as state, and even dynamically wrap your original data into some wrapper that has indication of selection - inside datasource itself. Thus your adapter would be purely data driven.</p>

Body:
I am using RecyclerView with ListAdapter which using DiffUtil internally to show the data. Of course, all the data was provided by ViewModel via LiveData.

Now each item view has a CheckBox, meanwhile I implemented drag selection function by adding RecyclerView.SimpleOnItemTouchListener. Selection status is now maintained by the adapter, it is not a good idea since status will lost after screen rotation.

I want to let ViewModel save the selection status and it is my idea:

Fragment will call the ViewModel to change the status when receiving the relevant callback.

ViewModel will change the data list (or create a new one if it is not mutable) and post to LiveData.

Fragment receives the data change and submits it to ListAdapter.

The problem is that the selection status can change very frequently if user acitvate drag selection. DifferUtil has to spend a long time comparing if there are a lot of data. Unlike saving status inside the adapter, now I cannot notify item changed accurately because I don't know which position is changed.

The core idea of MVVM is data-driven view, but in this case we lost additional information(e.g. position) causing extra calculations. So what is the best practice?

Part of the adapter code (based on GroupListAdapter which extend ListAdapter):

    private val selectedGroups = mutableSetOf<Int>()
    private val selectedImages = mutableSetOf<Image>()

    override fun onBindGroupViewHolder(holder: StubViewHolder, groupIndex: Int, flattedPosition: Int) {
        holder.setText(R.id.itemImageTitleTextView, getGroupItem(groupIndex).title)
    }

    override fun onBindChildViewHolder(holder: StubViewHolder, groupIndex: Int, childIndex: Int, flattedPosition: Int) {
        val data = getChildItem(groupIndex, childIndex)
        GlideApp.with(fragment).load(data.uri).into(holder.getView(R.id.itemImageView))
    }

    override fun onBindGroupViewHolder(holder: StubViewHolder, groupIndex: Int, flattedPosition: Int,
                                       payloads: MutableList<Any>) {
        holder.setGroupSelectionMode(isInSelectMode())
        holder.setGroupChecked(selectedGroups.contains(flattedPosition))
    }

    override fun onBindChildViewHolder(holder: StubViewHolder, groupIndex: Int, childIndex: Int, flattedPosition: Int,
                                       payloads: MutableList<Any>) {
        if (isInSelectMode()) {
            holder.setImageSelectionMode(true)
            if (selectedImages.contains(getItem(flattedPosition))) {
                holder.getView<MaskImageView>(R.id.itemImageView).isChecked = true
                holder.setImageChecked(true)
            } else {
                holder.getView<MaskImageView>(R.id.itemImageView).isChecked = false
                holder.setImageChecked(false)
            }
        } else {
            holder.getView<MaskImageView>(R.id.itemImageView).isChecked = false
            holder.setImageSelectionMode(false)
        }
    }

    fun setSelected(position: Int, isSelected: Boolean, refreshItem: Boolean = true) {
        if (!isChildItem(position)) {
            return
        }
        if (isSelected) {
            selectedImages.add(getItem(position) as Image)
        } else {
            selectedImages.remove(getItem(position))
        }
        if (refreshItem) {
            notifyItemChanged(position, true)
        }
        onSelectChangedCallback?.invoke(selectedImages.size)
    }