问:
How to style dropdown flex-block so it wouldn't push content under him, but overlap it without position?
I have this code.

When i click on second menu bar - flex dropdownmenu goes down.

But it pushes "header-flex" and other content under him down.

How can i make dropdown menu so it would overlap and not push blocks away?

I've tried position: relative-absolute, but it seems to break flex-container.

Is there a way to do this withoud position: relative/absolute?

Or maybe a way to "fix" flex and not let it break with all adaptive features?

Thanks

function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown-menu {
  display: flex;
  flex-wrap: wrap;
  max-width: 1240px;
  margin-left: auto;
  margin-right: auto;
  height: auto;
  background-color: #F3F3F3;
  border: 1px solid gray;
  justify-content: space-around;
  font-family: Arial, Helvetica, sans-serif;
  padding-bottom: 20px;
  box-sizing: border-box;
  gap: 10px;
  margin-bottom: 10px;
  margin-top: -20px;
}

.dropdown-menu-column {
  display: flex;
  flex-direction: column;
  width: 200px;

}

.dropdown-menu-column-block {
  display: flex;
  flex-direction: column;
}

.dropdown-menu-column-block-header {
    font-size: 14px;
    line-height: 14px;
    font-weight: bold;
    color: #595959;
    background-color: #dedede;
    padding-top: 9px;
    padding-bottom: 9px;
    display: block;
    text-align: center;
    margin-bottom: 10px;
     padding-left: 10px;
  padding-right: 10px;
  margin-top: 15px;
}

.dropdown-menu-column-block-element a {
  font-size: 13px;
  line-height: 22px;
  color: #167491;
}

.hide {
    display: none;
}

.dropdown-menu {
  display: none;
}

.hide:checked + label + div {
    display: flex;
}

@media (max-width: 444px) {
 .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}

.hide + label:before {
    background-color: #2CB1D9;
    color: black;
    content: "\002B";
    display: block;
    float: right;
    font-size: 14px;
    font-weight: bold;
    height: 16px;
    line-height: 16px;
    margin: 3px 5px;
    text-align: center;
    width: 16px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    border: 1px solid black;
}

.hide:checked + label:before {
    content: "\2212";
}

  .dropdown-menu {
    gap: 0px;
    padding-bottom: 0px;
  }

  .dropdown-menu-column {
    width: 100%;
  }

  .dropdown-menu-column-block-header {
    margin-bottom: 0px;
    margin-top: 0px;
  }

  .dropdown-menu-column-block {
    border: 1px solid #CDCDCD;
  }

  .dropdown-menu-column-block-element a {
    padding-left: 10px;
    display: inline-block;
  }

  }

  .header-flex {
  width: 100%;
  max-width: 1240px;
  display: flex;
  margin-left: auto;
  margin-right: auto;
  justify-content: space-between;
  border: 1px solid black;
  align-items: center;
  border: 1px solid #cecece;
  font-size: 18px;
  color: #1c1c1c;
  position: relative;
  height: 60px;
  box-sizing: border-box;
  }

  .article-header {
  font-size: 24px;
  font-weight: bold;
  padding-left: 10px;
}

.article-header-price {
  color: red;
  font-size: 24px;
  font-weight: bold;
}

.sidebar-button {
    font-size: 15px;
    line-height: 15px;
    font-weight: bold;
    color: #fff;
    text-align: center;
    background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/feedBackButton.png);
    height: 40px;
    width: 187px;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #863e39;
    border-radius: 2px;
    cursor: pointer;
    display: block;
  margin-right: 20px;
}

.sidebar-button:hover {
    background-color: #1fa6ce;
    background-image: none;
}

.menu {
  display: flex;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  border: 1px dotted black;
  max-width: 1240px;
  color: white;
  font-size: 1rem;
  font-weight: bold;
  width: 100%;
  flex-wrap: nowrap;
  border-radius: 2px;
  margin-bottom: 20px;
  align-items: center;
  box-sizing: border-box;
  background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3.jpg');
  border: 0px;
/*   border-bottom: 1px solid 167491; */
}

.menu-block:hover {
 background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3-hover.jpg');
}

.menu-block {
 width: 33%;
  box-sizing: border-box;
/*   padding: 10px 0;  */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.menu-block-3 {
  min-width: 33%;
  flex-basis: 33.5%;
  max-width: 34%;
}

 .menu-block-divider {
  width: 1px;
  height: 35px;
  margin-left: 1px;
  margin-right: 1px;
  background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/menuTop-li.gif);
} </code>```

О сервисе

      Услуги и цены

Контактная информация

      <input class="hide" id="hd-1" type="checkbox">
      Техническое обслуживание авто

Техническое обслуживание авто

Акции

      <input class="hide" id="hd-2" type="checkbox">
      Рулевое управление

Рулевое управление - прайс лист

Ремонт и замена рулевой рейки

Ремонт гидроусилителя руля (ГУР)

        <input class="hide" id="hd-3" type="checkbox">
        Трансмиссия

Трансмиссия- прайс-лист

Замена сцепления

Стоимость и ремонт вариатора

Диагноситка и ремонт РКПП

Ремонт раздаточной кородки TOD

      <input class="hide" id="hd-4" type="checkbox">
      Двигатель

Двигатель - прайс лист

Ремонт турбин

Замена маслосъемных колпачков

Ремонт и замена головок

Замена колец

Замена двигателя

Замена масла в двигателе

Замена свечей накала

Ремонт компонентов ГРМ

Замена цепи ГРМ

      <input class="hide" id="hd-5" type="checkbox">
      Топливная система

Топливная система - прайс лист

Ремонт топливной системы

Ремонт инжекторной системы

Ремонт узлов системы впрыска

Замена и диагностика форсунок

Замена топливного фильтра

      <input class="hide" id="hd-6" type="checkbox">
      Система электрики

Электрика - прайс лист

      <input class="hide" id="hd-7" type="checkbox">
      Системы охлаждения

Охлаждение - прайс лист

Замена радиатора охлаждения

Замена термостата

      <input class="hide" id="hd-8" type="checkbox">
      Тормозная система

Тормозная система - прайс-лист

Тормозная система

      <input class="hide" id="hd-9" type="checkbox">
      Выхлопная система

Выхлопная система - прайс лист

Ремонт выхлопной системы

Ремонт и замена глушителя

Замена гофры глушителя

Замена резинок глушителя

Замена средней части глушителя

Замена приемной трубы глушителя

Замена кольца глушителя

Замена прокладки катализатора

Замена заднего глушителя

      <input class="hide" id="hd-10" type="checkbox">
      Подвеска

Подвеска - прайс лист

Диагностика и ремонт ходовой

Диагностика подвески

Замена амортизаторов

Замена ступичного подшипника

Замена шаровой опоры

Замена стоек стабилизатора

Замена рычагов подвески

Замена сайлентблоков подвески

Замена и ремонт головок двигателя от 3000 руб.

  <button class="sidebar-button">Запрос цены и сроков</button>
```

答:
function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown-menu-container {
    position: absolute;
    z-index: 1000;
    top: 40px;
    width: 100%;
}

.dropdown-menu {
    display: flex;
    flex-wrap: wrap;
    max-width: 1240px;
    height: auto;
    background-color: #F3F3F3;
    border: 1px solid gray;
    justify-content: space-around;
    font-family: Arial, Helvetica, sans-serif;
    margin: 0 auto;
}

.dropdown-menu-column {
    display: flex;
    flex-direction: column;
    width: 200px;

}

.dropdown-menu-column-block {
    display: flex;
    flex-direction: column;
}

.dropdown-menu-column-block-header {
    font-size: 14px;
    line-height: 14px;
    font-weight: bold;
    color: #595959;
    background-color: #dedede;
    padding-top: 9px;
    padding-bottom: 9px;
    display: block;
    text-align: center;
    margin-bottom: 10px;
    padding-left: 10px;
    padding-right: 10px;
    margin-top: 15px;
}

.dropdown-menu-column-block-element a {
    font-size: 13px;
    line-height: 22px;
    color: #167491;
}

.hide {
    display: none;
}

.dropdown-menu-container {
    display: none;
}

.hide:checked+label+div {
    display: flex;
}

@media (max-width: 444px) {

    .hide,
    .hide+label~div {
        display: none;
    }

    .hide:checked+label+div {
        display: block;
    }

    .hide+label:before {
        background-color: #2CB1D9;
        color: black;
        content: "\002B";
        display: block;
        float: right;
        font-size: 14px;
        font-weight: bold;
        height: 16px;
        line-height: 16px;
        margin: 3px 5px;
        text-align: center;
        width: 16px;
        -webkit-border-radius: 50%;
        -moz-border-radius: 50%;
        border-radius: 50%;
        border: 1px solid black;
    }

    .hide:checked+label:before {
        content: "\2212";
    }

    .dropdown-menu {
        gap: 0px;
        padding-bottom: 0px;
    }

    .dropdown-menu-column {
        width: 100%;
    }

    .dropdown-menu-column-block-header {
        margin-bottom: 0px;
        margin-top: 0px;
    }

    .dropdown-menu-column-block {
        border: 1px solid #CDCDCD;
    }

    .dropdown-menu-column-block-element a {
        padding-left: 10px;
        display: inline-block;
    }

}

.header-flex {
    width: 100%;
    max-width: 1240px;
    display: flex;
    margin-left: auto;
    margin-right: auto;
    justify-content: space-between;
    border: 1px solid black;
    align-items: center;
    border: 1px solid #cecece;
    font-size: 18px;
    color: #1c1c1c;
    position: relative;
    height: 60px;
    box-sizing: border-box;
}

.article-header {
    font-size: 24px;
    font-weight: bold;
    padding-left: 10px;
}

.article-header-price {
    color: red;
    font-size: 24px;
    font-weight: bold;
}

.sidebar-button {
    font-size: 15px;
    line-height: 15px;
    font-weight: bold;
    color: #fff;
    text-align: center;
    background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/feedBackButton.png);
    height: 40px;
    width: 187px;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #863e39;
    border-radius: 2px;
    cursor: pointer;
    display: block;
    margin-right: 20px;
}

.sidebar-button:hover {
    background-color: #1fa6ce;
    background-image: none;
}

.menu {
    display: flex;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    border: 1px dotted black;
    max-width: 1240px;
    color: white;
    font-size: 1rem;
    font-weight: bold;
    width: 100%;
    flex-wrap: nowrap;
    border-radius: 2px;
    margin-bottom: 20px;
    align-items: center;
    box-sizing: border-box;
    background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3.jpg');
    border: 0px;
    /*   border-bottom: 1px solid 167491; */
}

.menu-block:hover {
    background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3-hover.jpg');
}

.menu-block {
    width: 33%;
    box-sizing: border-box;
    /*   padding: 10px 0;  */
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.menu-block-3 {
    min-width: 33%;
    flex-basis: 33.5%;
    max-width: 34%;
}

.menu-block-divider {
    width: 1px;
    height: 35px;
    margin-left: 1px;
    margin-right: 1px;
    background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/menuTop-li.gif);
}</code>```

О сервисе

            Услуги и цены

Контактная информация

                <input class="hide" id="hd-1" type="checkbox">
                Техническое обслуживание авто

Техническое обслуживание авто

Акции

                <input class="hide" id="hd-2" type="checkbox">
                Рулевое управление

Рулевое управление - прайс лист

Ремонт и замена рулевой рейки

Ремонт гидроусилителя руля (ГУР)

                    <input class="hide" id="hd-3" type="checkbox">
                    Трансмиссия

Трансмиссия- прайс-лист

Замена сцепления

Стоимость и ремонт вариатора

Диагноситка и ремонт РКПП

Ремонт раздаточной кородки TOD

                <input class="hide" id="hd-4" type="checkbox">
                Двигатель

Двигатель - прайс лист

Ремонт турбин

Замена маслосъемных колпачков

Ремонт и замена головок

Замена колец

Замена двигателя

Замена масла в двигателе

Замена свечей накала

Ремонт компонентов ГРМ

Замена цепи ГРМ

                <input class="hide" id="hd-5" type="checkbox">
                Топливная система

Топливная система - прайс лист

Ремонт топливной системы

Ремонт инжекторной системы

Ремонт узлов системы впрыска

Замена и диагностика форсунок

Замена топливного фильтра

                <input class="hide" id="hd-6" type="checkbox">
                Система электрики

Электрика - прайс лист

                <input class="hide" id="hd-7" type="checkbox">
                Системы охлаждения

Охлаждение - прайс лист

Замена радиатора охлаждения

Замена термостата

                <input class="hide" id="hd-8" type="checkbox">
                Тормозная система

Тормозная система - прайс-лист

Тормозная система

                <input class="hide" id="hd-9" type="checkbox">
                Выхлопная система

Выхлопная система - прайс лист

Ремонт выхлопной системы

Ремонт и замена глушителя

Замена гофры глушителя

Замена резинок глушителя

Замена средней части глушителя

Замена приемной трубы глушителя

Замена кольца глушителя

Замена прокладки катализатора

Замена заднего глушителя

                <input class="hide" id="hd-10" type="checkbox">
                Подвеска

Подвеска - прайс лист

Диагностика и ремонт ходовой

Диагностика подвески

Замена амортизаторов

Замена ступичного подшипника

Замена шаровой опоры

Замена стоек стабилизатора

Замена рычагов подвески

Замена сайлентблоков подвески

Замена и ремонт головок двигателя от 3000 руб.

    <button class="sidebar-button">Запрос цены и сроков</button>
```

Body:
I have this code.

When i click on second menu bar - flex dropdownmenu goes down.

But it pushes "header-flex" and other content under him down.

How can i make dropdown menu so it would overlap and not push blocks away?

I've tried position: relative-absolute, but it seems to break flex-container.

Is there a way to do this withoud position: relative/absolute?

Or maybe a way to "fix" flex and not let it break with all adaptive features?

Thanks

function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}

.dropdown-menu {
  display: flex;
  flex-wrap: wrap;
  max-width: 1240px;
  margin-left: auto;
  margin-right: auto;
  height: auto;
  background-color: #F3F3F3;
  border: 1px solid gray;
  justify-content: space-around;
  font-family: Arial, Helvetica, sans-serif;
  padding-bottom: 20px;
  box-sizing: border-box;
  gap: 10px;
  margin-bottom: 10px;
  margin-top: -20px;
}

.dropdown-menu-column {
  display: flex;
  flex-direction: column;
  width: 200px;

}

.dropdown-menu-column-block {
  display: flex;
  flex-direction: column;
}

.dropdown-menu-column-block-header {
    font-size: 14px;
    line-height: 14px;
    font-weight: bold;
    color: #595959;
    background-color: #dedede;
    padding-top: 9px;
    padding-bottom: 9px;
    display: block;
    text-align: center;
    margin-bottom: 10px;
     padding-left: 10px;
  padding-right: 10px;
  margin-top: 15px;
}

.dropdown-menu-column-block-element a {
  font-size: 13px;
  line-height: 22px;
  color: #167491;
}

.hide {
    display: none;
}

.dropdown-menu {
  display: none;
}

.hide:checked + label + div {
    display: flex;
}

@media (max-width: 444px) {
 .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}

.hide + label:before {
    background-color: #2CB1D9;
    color: black;
    content: "\002B";
    display: block;
    float: right;
    font-size: 14px;
    font-weight: bold;
    height: 16px;
    line-height: 16px;
    margin: 3px 5px;
    text-align: center;
    width: 16px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    border: 1px solid black;
}

.hide:checked + label:before {
    content: "\2212";
}

  .dropdown-menu {
    gap: 0px;
    padding-bottom: 0px;
  }

  .dropdown-menu-column {
    width: 100%;
  }

  .dropdown-menu-column-block-header {
    margin-bottom: 0px;
    margin-top: 0px;
  }

  .dropdown-menu-column-block {
    border: 1px solid #CDCDCD;
  }

  .dropdown-menu-column-block-element a {
    padding-left: 10px;
    display: inline-block;
  }

  }

  .header-flex {
  width: 100%;
  max-width: 1240px;
  display: flex;
  margin-left: auto;
  margin-right: auto;
  justify-content: space-between;
  border: 1px solid black;
  align-items: center;
  border: 1px solid #cecece;
  font-size: 18px;
  color: #1c1c1c;
  position: relative;
  height: 60px;
  box-sizing: border-box;
  }

  .article-header {
  font-size: 24px;
  font-weight: bold;
  padding-left: 10px;
}

.article-header-price {
  color: red;
  font-size: 24px;
  font-weight: bold;
}

.sidebar-button {
    font-size: 15px;
    line-height: 15px;
    font-weight: bold;
    color: #fff;
    text-align: center;
    background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/feedBackButton.png);
    height: 40px;
    width: 187px;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #863e39;
    border-radius: 2px;
    cursor: pointer;
    display: block;
  margin-right: 20px;
}

.sidebar-button:hover {
    background-color: #1fa6ce;
    background-image: none;
}

.menu {
  display: flex;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  border: 1px dotted black;
  max-width: 1240px;
  color: white;
  font-size: 1rem;
  font-weight: bold;
  width: 100%;
  flex-wrap: nowrap;
  border-radius: 2px;
  margin-bottom: 20px;
  align-items: center;
  box-sizing: border-box;
  background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3.jpg');
  border: 0px;
/*   border-bottom: 1px solid 167491; */
}

.menu-block:hover {
 background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3-hover.jpg');
}

.menu-block {
 width: 33%;
  box-sizing: border-box;
/*   padding: 10px 0;  */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.menu-block-3 {
  min-width: 33%;
  flex-basis: 33.5%;
  max-width: 34%;
}

 .menu-block-divider {
  width: 1px;
  height: 35px;
  margin-left: 1px;
  margin-right: 1px;
  background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/menuTop-li.gif);
}

О сервисе

      Услуги и цены

Контактная информация

      <input class="hide" id="hd-1" type="checkbox">
      Техническое обслуживание авто

Техническое обслуживание авто

Акции

      <input class="hide" id="hd-2" type="checkbox">
      Рулевое управление

Рулевое управление - прайс лист

Ремонт и замена рулевой рейки

Ремонт гидроусилителя руля (ГУР)

        <input class="hide" id="hd-3" type="checkbox">
        Трансмиссия

Трансмиссия- прайс-лист

Замена сцепления

Стоимость и ремонт вариатора

Диагноситка и ремонт РКПП

Ремонт раздаточной кородки TOD

      <input class="hide" id="hd-4" type="checkbox">
      Двигатель

Двигатель - прайс лист

Ремонт турбин

Замена маслосъемных колпачков

Ремонт и замена головок

Замена колец

Замена двигателя

Замена масла в двигателе

Замена свечей накала

Ремонт компонентов ГРМ

Замена цепи ГРМ

      <input class="hide" id="hd-5" type="checkbox">
      Топливная система

Топливная система - прайс лист

Ремонт топливной системы

Ремонт инжекторной системы

Ремонт узлов системы впрыска

Замена и диагностика форсунок

Замена топливного фильтра

      <input class="hide" id="hd-6" type="checkbox">
      Система электрики

Электрика - прайс лист

      <input class="hide" id="hd-7" type="checkbox">
      Системы охлаждения

Охлаждение - прайс лист

Замена радиатора охлаждения

Замена термостата

      <input class="hide" id="hd-8" type="checkbox">
      Тормозная система

Тормозная система - прайс-лист

Тормозная система

      <input class="hide" id="hd-9" type="checkbox">
      Выхлопная система

Выхлопная система - прайс лист

Ремонт выхлопной системы

Ремонт и замена глушителя

Замена гофры глушителя

Замена резинок глушителя

Замена средней части глушителя

Замена приемной трубы глушителя

Замена кольца глушителя

Замена прокладки катализатора

Замена заднего глушителя

      <input class="hide" id="hd-10" type="checkbox">
      Подвеска

Подвеска - прайс лист

Диагностика и ремонт ходовой

Диагностика подвески

Замена амортизаторов

Замена ступичного подшипника

Замена шаровой опоры

Замена стоек стабилизатора

Замена рычагов подвески

Замена сайлентблоков подвески

Замена и ремонт головок двигателя от 3000 руб.

  <button class="sidebar-button">Запрос цены и сроков</button>

Body:
function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}

.dropdown-menu-container {
    position: absolute;
    z-index: 1000;
    top: 40px;
    width: 100%;
}

.dropdown-menu {
    display: flex;
    flex-wrap: wrap;
    max-width: 1240px;
    height: auto;
    background-color: #F3F3F3;
    border: 1px solid gray;
    justify-content: space-around;
    font-family: Arial, Helvetica, sans-serif;
    margin: 0 auto;
}

.dropdown-menu-column {
    display: flex;
    flex-direction: column;
    width: 200px;

}

.dropdown-menu-column-block {
    display: flex;
    flex-direction: column;
}

.dropdown-menu-column-block-header {
    font-size: 14px;
    line-height: 14px;
    font-weight: bold;
    color: #595959;
    background-color: #dedede;
    padding-top: 9px;
    padding-bottom: 9px;
    display: block;
    text-align: center;
    margin-bottom: 10px;
    padding-left: 10px;
    padding-right: 10px;
    margin-top: 15px;
}

.dropdown-menu-column-block-element a {
    font-size: 13px;
    line-height: 22px;
    color: #167491;
}

.hide {
    display: none;
}

.dropdown-menu-container {
    display: none;
}

.hide:checked+label+div {
    display: flex;
}

@media (max-width: 444px) {

    .hide,
    .hide+label~div {
        display: none;
    }

    .hide:checked+label+div {
        display: block;
    }

    .hide+label:before {
        background-color: #2CB1D9;
        color: black;
        content: "\002B";
        display: block;
        float: right;
        font-size: 14px;
        font-weight: bold;
        height: 16px;
        line-height: 16px;
        margin: 3px 5px;
        text-align: center;
        width: 16px;
        -webkit-border-radius: 50%;
        -moz-border-radius: 50%;
        border-radius: 50%;
        border: 1px solid black;
    }

    .hide:checked+label:before {
        content: "\2212";
    }

    .dropdown-menu {
        gap: 0px;
        padding-bottom: 0px;
    }

    .dropdown-menu-column {
        width: 100%;
    }

    .dropdown-menu-column-block-header {
        margin-bottom: 0px;
        margin-top: 0px;
    }

    .dropdown-menu-column-block {
        border: 1px solid #CDCDCD;
    }

    .dropdown-menu-column-block-element a {
        padding-left: 10px;
        display: inline-block;
    }

}

.header-flex {
    width: 100%;
    max-width: 1240px;
    display: flex;
    margin-left: auto;
    margin-right: auto;
    justify-content: space-between;
    border: 1px solid black;
    align-items: center;
    border: 1px solid #cecece;
    font-size: 18px;
    color: #1c1c1c;
    position: relative;
    height: 60px;
    box-sizing: border-box;
}

.article-header {
    font-size: 24px;
    font-weight: bold;
    padding-left: 10px;
}

.article-header-price {
    color: red;
    font-size: 24px;
    font-weight: bold;
}

.sidebar-button {
    font-size: 15px;
    line-height: 15px;
    font-weight: bold;
    color: #fff;
    text-align: center;
    background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/feedBackButton.png);
    height: 40px;
    width: 187px;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #863e39;
    border-radius: 2px;
    cursor: pointer;
    display: block;
    margin-right: 20px;
}

.sidebar-button:hover {
    background-color: #1fa6ce;
    background-image: none;
}

.menu {
    display: flex;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    border: 1px dotted black;
    max-width: 1240px;
    color: white;
    font-size: 1rem;
    font-weight: bold;
    width: 100%;
    flex-wrap: nowrap;
    border-radius: 2px;
    margin-bottom: 20px;
    align-items: center;
    box-sizing: border-box;
    background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3.jpg');
    border: 0px;
    /*   border-bottom: 1px solid 167491; */
}

.menu-block:hover {
    background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3-hover.jpg');
}

.menu-block {
    width: 33%;
    box-sizing: border-box;
    /*   padding: 10px 0;  */
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.menu-block-3 {
    min-width: 33%;
    flex-basis: 33.5%;
    max-width: 34%;
}

.menu-block-divider {
    width: 1px;
    height: 35px;
    margin-left: 1px;
    margin-right: 1px;
    background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/menuTop-li.gif);
}

<div class="menu" id="menuTop">
    <div class="menu-block">
        <div class="icon-1"><img src=""></div>
        <div class="menu-block-1">О сервисе</div>

    </div>
    <div class="menu-block-divider"></div>
    <div class="menu-block">
        <div class="icon-2"><img src=""></div>
        <div class="menu-block-2" onclick="myFunction()">
            Услуги и цены </div>

    </div>

    <div class="menu-block-divider"></div>
    <div class="menu-block menu-block-3">
        <div class="icon-3"><img src=""></div>
        <div class="menu-block-33">Контактная информация </div>
    </div>
</div>
<div class="dropdown-menu-container" id="dropdown">
    <div class="dropdown-menu">
        <div class="dropdown-menu-column column-1">
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-1" type="checkbox">
                <label for="hd-1" class="dropdown-menu-column-block-header">Техническое обслуживание авто</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Техническое обслуживание авто</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Акции</a></div>
                </div>
            </div>
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-2" type="checkbox">
                <label for="hd-2" class="dropdown-menu-column-block-header">Рулевое управление</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Рулевое управление - прайс лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт и замена рулевой рейки</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт гидроусилителя руля (ГУР)</a>
                    </div>
                </div>
                <div class="dropdown-menu-column-block">
                    <input class="hide" id="hd-3" type="checkbox">
                    <label for="hd-3" class="dropdown-menu-column-block-header">Трансмиссия</label>
                    <div class="drodown-menu-column-block-element-hider">
                        <div class="dropdown-menu-column-block-element"><a href="">Трансмиссия- прайс-лист</a></div>
                        <div class="dropdown-menu-column-block-element"><a href="">Замена сцепления</a></div>
                        <div class="dropdown-menu-column-block-element"><a href="">Стоимость и ремонт вариатора</a>
                        </div>
                        <div class="dropdown-menu-column-block-element"><a href="">Диагноситка и ремонт РКПП</a></div>
                        <div class="dropdown-menu-column-block-element"><a href="">Ремонт раздаточной кородки TOD</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="dropdown-menu-column column-2">
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-4" type="checkbox">
                <label for="hd-4" class="dropdown-menu-column-block-header">Двигатель</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Двигатель - прайс лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт турбин</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена маслосъемных колпачков</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт и замена головок</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена колец</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена двигателя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена масла в двигателе</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена свечей накала</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт компонентов ГРМ</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена цепи ГРМ</a></div>
                </div>
            </div>
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-5" type="checkbox">
                <label for="hd-5" class="dropdown-menu-column-block-header">Топливная система</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Топливная система - прайс лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт топливной системы</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт инжекторной системы</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт узлов системы впрыска</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена и диагностика форсунок</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена топливного фильтра</a></div>
                </div>
            </div>
        </div>
        <div class="dropdown-menu-column column-3">
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-6" type="checkbox">
                <label for="hd-6" class="dropdown-menu-column-block-header">Система электрики</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Электрика - прайс лист</a></div>
                </div>
            </div>
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-7" type="checkbox">
                <label for="hd-7" class="dropdown-menu-column-block-header">Системы охлаждения</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Охлаждение - прайс лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена радиатора охлаждения</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена термостата</a></div>
                </div>
            </div>
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-8" type="checkbox">
                <label for="hd-8" class="dropdown-menu-column-block-header">Тормозная система</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Тормозная система - прайс-лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Тормозная система</a></div>
                </div>
            </div>
        </div>
        <div class="dropdown-menu-column column-4">
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-9" type="checkbox">
                <label for="hd-9" class="dropdown-menu-column-block-header">Выхлопная система</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Выхлопная система - прайс лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт выхлопной системы</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Ремонт и замена глушителя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена гофры глушителя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена резинок глушителя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена средней части глушителя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена приемной трубы глушителя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена кольца глушителя</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена прокладки катализатора</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена заднего глушителя</a></div>
                </div>
            </div>
        </div>
        <div class="dropdown-menu-column column-5">
            <div class="dropdown-menu-column-block">
                <input class="hide" id="hd-10" type="checkbox">
                <label for="hd-10" class="dropdown-menu-column-block-header">Подвеска</label>
                <div class="drodown-menu-column-block-element-hider">
                    <div class="dropdown-menu-column-block-element"><a href="">Подвеска - прайс лист</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Диагностика и ремонт ходовой</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Диагностика подвески</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена амортизаторов</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена ступичного подшипника</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена шаровой опоры</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена стоек стабилизатора</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена рычагов подвески</a></div>
                    <div class="dropdown-menu-column-block-element"><a href="">Замена сайлентблоков подвески</a></div>
                </div>
            </div>
        </div>
    </div>
</div>
<header class="header-flex">
    <div class="article-header">Замена и ремонт головок двигателя <span class="article-header-price">от 3000 руб.</span>
    </div>
    <button class="sidebar-button">Запрос цены и сроков</button>
</header>


来源: stackexchange

问:
trying to create a row on a table after making a POST -django
How can I create a new row in table notificacao everytime i make this post? (save is not working i get 'QuerySet' object has no attribute 'save')</p>
```<code>def post(self, request):
        cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf'])
        cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf'])
        notificacao1 = Notificacao.objects.all()

        if cliente1.saldo >= request.data['quantia']:
            cliente1.saldo -= request.data['quantia']
            cliente1.save()

            cliente2.saldo += request.data['quantia']
            cliente2.save()

            notificacao1.cpf_remetente = request.data['cliente1_cpf_transf']
            notificacao1.cpf_destinatario = request.data['cliente2_cpf_transf']
            notificacao1.valor = request.data['quantia']
            notificacao1.save()
</code>```

答:
QuerySet is kinda like a list, and you cannot save all objects in list just like that.

You are probably in need to make notificacao1 as new Notificacao object. You need to create it like this:

```<code>notificacao1 = Notificacao.objects.create(cpf_remetente=cliente1, cpf_destinatario=cliente2, valor=request.data['quantia'])
</code>```

Whole suggested code:

```<code>   def post(self, request):
        cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf'])
        cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf'])
        valor = request.data['quantia']

        if cliente1.saldo >= valor :
            cliente1.saldo -= valor
            cliente1.save()

            cliente2.saldo += valor
            cliente2.save()

            Notificacao.objects.create(cpf_remetente=cliente1, cpf_destinatario=cliente2, valor=valor)
</code>```

Because this is calling all objects of model Notificacao:

```<code>all_objects_of_notificacao = Notificacao.objects.all()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I create a new row in table notificacao everytime i make this post? (save is not working i get 'QuerySet' object has no attribute 'save')

def post(self, request):
        cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf'])
        cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf'])
        notificacao1 = Notificacao.objects.all()

        if cliente1.saldo >= request.data['quantia']:
            cliente1.saldo -= request.data['quantia']
            cliente1.save()

            cliente2.saldo += request.data['quantia']
            cliente2.save()

            notificacao1.cpf_remetente = request.data['cliente1_cpf_transf']
            notificacao1.cpf_destinatario = request.data['cliente2_cpf_transf']
            notificacao1.valor = request.data['quantia']
            notificacao1.save()

Body:
QuerySet is kinda like a list, and you cannot save all objects in list just like that.

You are probably in need to make notificacao1 as new Notificacao object. You need to create it like this:

notificacao1 = Notificacao.objects.create(cpf_remetente=cliente1, cpf_destinatario=cliente2, valor=request.data['quantia'])

Whole suggested code:

   def post(self, request):
        cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf'])
        cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf'])
        valor = request.data['quantia']

        if cliente1.saldo >= valor :
            cliente1.saldo -= valor
            cliente1.save()

            cliente2.saldo += valor
            cliente2.save()

            Notificacao.objects.create(cpf_remetente=cliente1, cpf_destinatario=cliente2, valor=valor)

Because this is calling all objects of model Notificacao:

all_objects_of_notificacao = Notificacao.objects.all()


问:
Update-Database command is not working in ASP.Net Core / Entity Framework Core because object in database already exists
I was updating my database by the command line, but then I manually updated one of my tables.

This seems to have disrupted my ability to update-database. I receive the following error when I try to update:

```<code> System.Data.SqlClient.SqlException: There is already an object named 'ClientsAndTestimonials' in the database.    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
    at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
    at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
    at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean openConnection, Boolean closeConnection)
    at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues, Boolean manageConnection)
    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
    at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
    at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
    at Microsoft.EntityFrameworkCore.Tools.Cli.DatabaseUpdateCommand.<>c__DisplayClass0_0.<Configure>b__0()
    at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
    at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
 ClientConnectionId:d89989a8-ce8b-4167-be7e-fcddc4bcdf98
 Error Number:2714,State:6,Class:16
 There is already an object named 'ClientsAndTestimonials' in the database.
</code>```

I have been trying to fix this problem for the past few days. Most fellow developers suggest some variation of using Add-migration "Reset" -IgnoreChanges, like John Salewski from the following link.

However, I keep getting an error that says "A parameter cannot be found that matches parameter name 'IgnoreChanges'".

Any suggestions would be greatly appreciated!

答:
For this helped:

comment out all of the Up() method of the initial migration file

run the application

in the database in the EFMigrationsHistory is then the first entry generated

i changed the Up() method back to original

run application again and the bug is gone

worked for me locally and on the server.

Body:
I was updating my database by the command line, but then I manually updated one of my tables.

This seems to have disrupted my ability to update-database. I receive the following error when I try to update:

 System.Data.SqlClient.SqlException: There is already an object named 'ClientsAndTestimonials' in the database.    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
    at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
    at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
    at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean openConnection, Boolean closeConnection)
    at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues, Boolean manageConnection)
    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
    at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
    at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
    at Microsoft.EntityFrameworkCore.Tools.Cli.DatabaseUpdateCommand.<>c__DisplayClass0_0.<Configure>b__0()
    at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
    at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
 ClientConnectionId:d89989a8-ce8b-4167-be7e-fcddc4bcdf98
 Error Number:2714,State:6,Class:16
 There is already an object named 'ClientsAndTestimonials' in the database.

I have been trying to fix this problem for the past few days. Most fellow developers suggest some variation of using Add-migration "Reset" -IgnoreChanges, like John Salewski from the following link.

However, I keep getting an error that says "A parameter cannot be found that matches parameter name 'IgnoreChanges'".

Any suggestions would be greatly appreciated!


问:
Composite Foreign Key Question
I am trying to figure out if it is possible to create a foreign key in this way.

First there are two parent tables in this scenario.

Table 1 has a PK int and another int column. When combined the two are unique.

Table 2 has a PK int and another int column. When combined the two are unique.

The paired value between the two ints is how we currently select the child records for either table.

Table 3 has a value for the PK and other int column from one of the first two tables. It is reliably selectable because the two fields when both used in a search are unique to one of the above tables.

So I am looking to create a FK or possibly two FK for this scenario. I would like to be able to do cascading deletes from either of the first tables into the third table, and would also like to use this for the entity relationships in Entity Framework.

Please let me know if this is not making sense. I have read it several times, and it is about as clear as I can get it.

Thanks

答:
If Table3 contains all values in Table1 UNION Table2, then you have an inheritance scheme:

```<code>Table3 { (int id, int type) PK }
Table1 { (int id, int type [CHECK type = 1]) FK Table3 }
Table2 { (int id, int type [CHECK type = 2]) FK Table3 }
</code>```

With that, deleting from Table3 will cascade to Table1 or Table2 appropriately.

Otherwise, if Table3 is just a subset of Table1 UNION Table2 - then introducing Table4 as the full set would work.

```<code>Table4 { (int id, int type [CHECK type IN (1,2)]) PK }
Table1 { (int id, int type [CHECK type = 1]) FK Table4 }
Table2 { (int id, int type [CHECK type = 2]) FK Table4 }
Table3 { (int id, int type) FK Table4 }
</code>```

To handle cascaded deletes, though, you'd need to delete from Table4 (though you could do a trigger on Table3 to handle that for you).

Edit (because I think it's an important point that should be seen, seperate from the comments):

Yeah, the problem with this is that one and two are the parents. They both have related records in 3, which would be a FK, not a PK for that table. It seems to be pretty much impossible using a FK constraint. Thanks for the response! – Chrisb (an hour ago)

IMO - your data model is broken then. Table1 and Table2 are unrelated, but you're trying to stuff them into the same column in Table3. If Table1 and Table2 are related somehow, then you need to model that.

Either introduce a parent table (Table4) if they're related, or either a 2nd column in Table3 (Table1 FK, Table2 FK) or 2 join tables if they're not. Don't try to put a round peg into a square hole - and don't try to make up for it with a trigger. ;)

ContentLicense: CC BY-SA 2.5

Title: Composite Foreign Key Question

Body:
If Table3 contains all values in Table1 UNION Table2, then you have an inheritance scheme:

Table3 { (int id, int type) PK }
Table1 { (int id, int type [CHECK type = 1]) FK Table3 }
Table2 { (int id, int type [CHECK type = 2]) FK Table3 }

With that, deleting from Table3 will cascade to Table1 or Table2 appropriately.

Otherwise, if Table3 is just a subset of Table1 UNION Table2 - then introducing Table4 as the full set would work.

Table4 { (int id, int type [CHECK type IN (1,2)]) PK }
Table1 { (int id, int type [CHECK type = 1]) FK Table4 }
Table2 { (int id, int type [CHECK type = 2]) FK Table4 }
Table3 { (int id, int type) FK Table4 }

To handle cascaded deletes, though, you'd need to delete from Table4 (though you could do a trigger on Table3 to handle that for you).

Edit (because I think it's an important point that should be seen, seperate from the comments):

Yeah, the problem with this is that one and two are the parents. They both have related records in 3, which would be a FK, not a PK for that table. It seems to be pretty much impossible using a FK constraint. Thanks for the response! – Chrisb (an hour ago)

IMO - your data model is broken then. Table1 and Table2 are unrelated, but you're trying to stuff them into the same column in Table3. If Table1 and Table2 are related somehow, then you need to model that.

Either introduce a parent table (Table4) if they're related, or either a 2nd column in Table3 (Table1 FK, Table2 FK) or 2 join tables if they're not. Don't try to put a round peg into a square hole - and don't try to make up for it with a trigger. ;)

OwnerDisplayName: Mark Brackett

LastEditorDisplayName: Mark Brackett


问:
How to Represent Composite keys in Hibernate using Annotations?
So I reverse engineered some tables from my db and when I try to save my object to the db I get the following  error:

Initial SessionFactory creation failed.org.hibernate.AnnotationException: A Foreign key refering com.mycode.Block from com.mycode.Account has the wrong number of column. should be 2
Exception in thread "main" java.lang.ExceptionInInitializerError

The Domain objects Are Block which contains a number of Account Objects:

```<code>    @OneToMany(fetch = FetchType.LAZY, mappedBy = "Block")
public Set<EAccount> getAccounts() {
    return this.Accounts;
}
</code>```

Account has a Composite key of Id and Role. This has been setup in a seperate Class:

```<code>@Embeddable
public class BlockAccountId implements java.io.Serializable {

private long blockOid;
private String accountRole;

public BlockAccountId() {
}

public BlockAccountId(long blockOid, String accountRole) {
    this.blockOid = blockOid;
    this.accountRole = accountRole;
}

@Column(name = "BLOCK_OID", nullable = false)
public long getBlockOid() {
    return this.blockOid;
}

public void setBlockOid(long blockOid) {
    this.blockOid = blockOid;
}

@Column(name = "ACCOUNT_ROLE", nullable = false, length = 10)
public String getAccountRole() {
    return this.accountRole;
}

public void setAccountRole(String accountRole) {
    this.accountRole = accountRole;
}
</code>```

So I want to know. How can I Link the tables Block and account on blockOid but still ensure the account table has both blockOid and accountRole as a composite key.

Any examples would be greatly appreciated!

N.B this is a Block (One) to Account (Many) relationship.

Thanks

答:
The easiest is to place your association directly in the embedded id component.

Hibernate reference documentation

Section 5.1.2.1.1. id as a property using a component type ()

Example (Only write the important getter() and setter())

```<code>@Entity
public class Block {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="BLOCK_OID")
    long blockOid;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "id.block", cascade=CascadeType.ALL)
    Set<Account> accounts = new HashSet<Account>();
}

@Entity
public class Account {

    @EmbeddedId BlockAccountId id;

    public Account()
    {
        this.id = new BlockAccountId();
    }

    public void setBlock(Block pBlock) {
        this.id.setBlock(pBlock);
    }

    public Block getBlock() {
        return this.id.getBlock();
    }

    public String getAccountRole() {
        return this.id.getAccountRole();
    }

    public void setAccountRole(String accountRole) {
        this.id.setAccountRole(accountRole);
    }
}

@Embeddable
public class BlockAccountId implements java.io.Serializable {

    @ManyToOne(optional = false)
    private Block block;

    @Column(name = "ACCOUNT_ROLE", nullable = false, length = 10)
    private String accountRole;

    public BlockAccountId() {

    }

    //Implement equals and hashcode
}
</code>```

The corresponding database table are :

```<code>CREATE TABLE  block (
  BLOCK_OID bigint(20) NOT NULL auto_increment,
  PRIMARY KEY  (`BLOCK_OID`)
)

CREATE TABLE  account (
  ACCOUNT_ROLE varchar(10) NOT NULL,
  block_BLOCK_OID bigint(20) NOT NULL,
  PRIMARY KEY  (`ACCOUNT_ROLE`,`block_BLOCK_OID`),
  KEY `FK_block_OID` (`block_BLOCK_OID`),
  CONSTRAINT `FK_block_OID` FOREIGN KEY (`block_BLOCK_OID`) REFERENCES `block` (`BLOCK_OID`)
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I reverse engineered some tables from my db and when I try to save my object to the db I get the following  error:

Initial SessionFactory creation failed.org.hibernate.AnnotationException: A Foreign key refering com.mycode.Block from com.mycode.Account has the wrong number of column. should be 2
Exception in thread "main" java.lang.ExceptionInInitializerError

The Domain objects Are Block which contains a number of Account Objects:

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "Block")
public Set<EAccount> getAccounts() {
    return this.Accounts;
}

Account has a Composite key of Id and Role. This has been setup in a seperate Class:

@Embeddable
public class BlockAccountId implements java.io.Serializable {

private long blockOid;
private String accountRole;

public BlockAccountId() {
}

public BlockAccountId(long blockOid, String accountRole) {
    this.blockOid = blockOid;
    this.accountRole = accountRole;
}

@Column(name = "BLOCK_OID", nullable = false)
public long getBlockOid() {
    return this.blockOid;
}

public void setBlockOid(long blockOid) {
    this.blockOid = blockOid;
}

@Column(name = "ACCOUNT_ROLE", nullable = false, length = 10)
public String getAccountRole() {
    return this.accountRole;
}

public void setAccountRole(String accountRole) {
    this.accountRole = accountRole;
}

So I want to know. How can I Link the tables Block and account on blockOid but still ensure the account table has both blockOid and accountRole as a composite key.

Any examples would be greatly appreciated!

N.B this is a Block (One) to Account (Many) relationship.

Thanks

Body:
The easiest is to place your association directly in the embedded id component.

Hibernate reference documentation

Section 5.1.2.1.1. id as a property using a component type ()

Example (Only write the important getter() and setter())

@Entity
public class Block {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="BLOCK_OID")
    long blockOid;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "id.block", cascade=CascadeType.ALL)
    Set<Account> accounts = new HashSet<Account>();
}

@Entity
public class Account {

    @EmbeddedId BlockAccountId id;

    public Account()
    {
        this.id = new BlockAccountId();
    }

    public void setBlock(Block pBlock) {
        this.id.setBlock(pBlock);
    }

    public Block getBlock() {
        return this.id.getBlock();
    }

    public String getAccountRole() {
        return this.id.getAccountRole();
    }

    public void setAccountRole(String accountRole) {
        this.id.setAccountRole(accountRole);
    }
}

@Embeddable
public class BlockAccountId implements java.io.Serializable {

    @ManyToOne(optional = false)
    private Block block;

    @Column(name = "ACCOUNT_ROLE", nullable = false, length = 10)
    private String accountRole;

    public BlockAccountId() {

    }

    //Implement equals and hashcode
}

The corresponding database table are :

CREATE TABLE  block (
  BLOCK_OID bigint(20) NOT NULL auto_increment,
  PRIMARY KEY  (`BLOCK_OID`)
)

CREATE TABLE  account (
  ACCOUNT_ROLE varchar(10) NOT NULL,
  block_BLOCK_OID bigint(20) NOT NULL,
  PRIMARY KEY  (`ACCOUNT_ROLE`,`block_BLOCK_OID`),
  KEY `FK_block_OID` (`block_BLOCK_OID`),
  CONSTRAINT `FK_block_OID` FOREIGN KEY (`block_BLOCK_OID`) REFERENCES `block` (`BLOCK_OID`)
)


问:
My code prints out 'Invalid input' every time in a game Rock Paper Scissors
My code prints out every time 'Invalid input', but I want it to print 'Invalid input' only when something other besides "rock", 'paper' , 'scissors', '!exit', '!rating' is written in the input, can someone help me, please, I don't really get why it is like this. Here you can see my code:</p>
```<code>import random
import math

HELP_TEXT = '"'
class Rating:
    def __init__(self, name):
        self._old_data = None
        self._user_name = name
        self.score = self._get()

    def _get(self):
        try:
            with open('rating.txt', 'r') as f:
                for line in f:
                    name, score = line.split()
                    if name == self._user_name:
                        self._old_data = line
                        return int(score)
            with open('rating.txt', 'a') as f:
                f.write(f'{self._user_name} 0')
            self._old_data = f'{self._user_name} 0'
            return 0
        except FileNotFoundError:
            with open('rating.txt', 'w') as f:
                f.write(f'{self._user_name} 0')
            self._old_data = f'{self._user_name} 0'
            return 0

    def add(self, score):
        self.score += score

    def save(self):
        with open('rating.txt', 'r') as f:
            old_data = f.read()
        new_data = old_data.replace(self._old_data, f'{self._user_name} {self.score}\n')
        with open('rating.txt', 'w') as f:
            f.write(new_data)

class User:
    def __init__(self):
        self.name = ''
        self._hello_user()
        self.rating = Rating(self.name)

    def _hello_user(self):
        self.name = input('Enter your name: ').strip().replace(' ', '')
        print(f'Hello, {self.name}')

class Game:
    def __init__(self):
        self.RPS = {}
        self.user_choice = ''
        self.game_choice = ''
        self.result = ''
        self.help = HELP_TEXT
        self.user = User()

    def referee(self):
        if self.user_choice == self.game_choice:
            return 'draw'
        elif self.user_choice in self.RPS.get(self.game_choice):
            return 'win'
        else:
            return 'lose'

    def result_processing(self):
        if self.result == 'draw':
            self.user.rating.add(50)
            print(f'There is a draw ({self.game_choice})')
        elif self.result == 'lose':
            print(f'Sorry, but computer chose {self.game_choice}')
        elif self.result == 'win':
            self.user.rating.add(100)
            print(f'Well done. Computer chose {self.game_choice} and failed')
        else :
            print('Invalid input')

    def generator(self, user_input):
        output = {}
        items = list(user_input.split(','))
        if len(items) == 1:
            return {'rock': ['paper'], 'paper': ['scissors'], 'scissors': ['rock']}
        double_items = items + items
        half_items = math.ceil(len(items) / 2)
        for i in range(len(items)):
            output[items[i]] = double_items[i + 1:i + half_items:1]
        return output

    def run(self):
        self.RPS = self.generator(input())
        print('Okay, let\'s start')
        while True:
            self.user_choice = input().strip()
            if self.user_choice == '!exit':
                break
            elif self.user_choice == '!rating':
                print(f'Your rating: {self.user.rating.score}')
                continue
            elif self.user_choice == '!help':
                print(self.help)
                continue
            self.game_choice = random.choice(list(self.RPS.keys()))
            self.result = self.referee()
            self.result_processing()
        self.user.rating.save()
        print('Bye!')

if __name__ == '__main__':
    game = Game()
    game.run()
</code>```

答:
You can add a check that the input is one of the keys to referee().

```<code>    def referee(self):
        if self.user_choice == self.game_choice:
            return 'draw'
        elif self.user_choice not in self.RPS:
            return 'invalid'
        elif self.user_choice in self.RPS[self.game_choice]:
            return 'win'
        else:
            return 'lose'
</code>```

Body:
My code prints out every time 'Invalid input', but I want it to print 'Invalid input' only when something other besides "rock", 'paper' , 'scissors', '!exit', '!rating' is written in the input, can someone help me, please, I don't really get why it is like this. Here you can see my code:

import random
import math

HELP_TEXT = '"'
class Rating:
    def __init__(self, name):
        self._old_data = None
        self._user_name = name
        self.score = self._get()

    def _get(self):
        try:
            with open('rating.txt', 'r') as f:
                for line in f:
                    name, score = line.split()
                    if name == self._user_name:
                        self._old_data = line
                        return int(score)
            with open('rating.txt', 'a') as f:
                f.write(f'{self._user_name} 0')
            self._old_data = f'{self._user_name} 0'
            return 0
        except FileNotFoundError:
            with open('rating.txt', 'w') as f:
                f.write(f'{self._user_name} 0')
            self._old_data = f'{self._user_name} 0'
            return 0

    def add(self, score):
        self.score += score

    def save(self):
        with open('rating.txt', 'r') as f:
            old_data = f.read()
        new_data = old_data.replace(self._old_data, f'{self._user_name} {self.score}\n')
        with open('rating.txt', 'w') as f:
            f.write(new_data)

class User:
    def __init__(self):
        self.name = ''
        self._hello_user()
        self.rating = Rating(self.name)

    def _hello_user(self):
        self.name = input('Enter your name: ').strip().replace(' ', '')
        print(f'Hello, {self.name}')

class Game:
    def __init__(self):
        self.RPS = {}
        self.user_choice = ''
        self.game_choice = ''
        self.result = ''
        self.help = HELP_TEXT
        self.user = User()

    def referee(self):
        if self.user_choice == self.game_choice:
            return 'draw'
        elif self.user_choice in self.RPS.get(self.game_choice):
            return 'win'
        else:
            return 'lose'

    def result_processing(self):
        if self.result == 'draw':
            self.user.rating.add(50)
            print(f'There is a draw ({self.game_choice})')
        elif self.result == 'lose':
            print(f'Sorry, but computer chose {self.game_choice}')
        elif self.result == 'win':
            self.user.rating.add(100)
            print(f'Well done. Computer chose {self.game_choice} and failed')
        else :
            print('Invalid input')

    def generator(self, user_input):
        output = {}
        items = list(user_input.split(','))
        if len(items) == 1:
            return {'rock': ['paper'], 'paper': ['scissors'], 'scissors': ['rock']}
        double_items = items + items
        half_items = math.ceil(len(items) / 2)
        for i in range(len(items)):
            output[items[i]] = double_items[i + 1:i + half_items:1]
        return output

    def run(self):
        self.RPS = self.generator(input())
        print('Okay, let\'s start')
        while True:
            self.user_choice = input().strip()
            if self.user_choice == '!exit':
                break
            elif self.user_choice == '!rating':
                print(f'Your rating: {self.user.rating.score}')
                continue
            elif self.user_choice == '!help':
                print(self.help)
                continue
            self.game_choice = random.choice(list(self.RPS.keys()))
            self.result = self.referee()
            self.result_processing()
        self.user.rating.save()
        print('Bye!')

if __name__ == '__main__':
    game = Game()
    game.run()

Body:
You can add a check that the input is one of the keys to referee().

    def referee(self):
        if self.user_choice == self.game_choice:
            return 'draw'
        elif self.user_choice not in self.RPS:
            return 'invalid'
        elif self.user_choice in self.RPS[self.game_choice]:
            return 'win'
        else:
            return 'lose'


问:
Function log2l has no function body
I am new to Vivado HLS ( using Vivado HLS 2018.3 ). I am writing this code to generate a 16-bit CRC (Cyclic Redundancy Check) using a 128-bit message and 17-bit generator polynomial. Here in the source code, I am using log2l() in order to find out the number of bits. This code runs smoothly during C Simulation but during C Synthesis, it throws the error :

```<code>Function 'log2l' has no function body
</code>```

Please see the full source code below :

```<code>#include "header.h"
#include "ap_int.h"
using namespace std;

int crc(ap_int<128>  dword,ap_int<17>  gen){

int l_gen = floor(log2l(gen) + 1);

ap_int<136> dividend = dword << (l_gen-1);

// shft specifies the no. of least significant bits not being XORed

int shft = (int) (floor(log2l(dividend))+1) - l_gen;

ap_int<16> rem;  //rem variable stores the CRC value

while (shft >= 0){

    // bitwise XOR the MSBs of dividend with generator
    // replace the operated MSBs from the dividend with
    // remainder generated
    rem = (dividend >> shft) ^ gen;//
    // (dividend & ((1 << shft) - 1)) : bits of dividend that were not XORed
    dividend = (dividend & ((1 << shft) - 1)) | (rem << shft); // new dividend

    // change shft variable
   shft = (int) (floor(log2l(dividend))+1) - l_gen;

}

// finally, AND the initial dividend with the remainder (=dividend)
ap_int<144> codeword;  //128 bit message plus 16 bit CRC = 144 bit
codeword = (dword << (l_gen - 1)) | dividend;
cout << "Remainder: " << dividend << endl;
cout << "Codeword to be sent : " << codeword << endl;

return 0 ;
</code>```

}

The test bench that I am using is :

```<code>#include "header.h"
#include "ap_int.h"
using namespace std;

int crc(ap_int<128> , ap_int<17> );

int main()

{
    ap_int<128>dataword ;
    ap_int<17> generator;
    dataword = 36;
    generator = 13;
    crc(dataword, generator);
    cout<<" Majid wins";
    return 0;
}
</code>```

The header file is :

```<code>#include<iostream>
#include<math.h>
#include "ap_fixed.h"
#include "hls_stream.h"
</code>```

In C simulation, the output that I get is :

```<code>Remainder: 1
Codeword to be sent : 289
Majid wins
</code>```

I am using only three files : source , testbench and header.

Please tell me why this code is not working in C Synthesis. Also if you find anything amiss in my code, please tell me. Thanks !

答:
I suspect it has something to do with the inclusion of the math library. I guess Vivado HLS has some configurations or flags to supply in compilation and then in synthesis regarding the use of mathematical functions.

Nevertheless, a simple and effective workaround would be to implement floor(log2(x)) yourself, something that looks as follows:

template <typename T>
unsigned int mylog2 (T val) {
#pragma HLS PIPELINE II=1
    if (val == 0) return (1 << (val::size-1)); // A very big number, assuming T is always ap_int<>
    if (val == 1) return 0;
    unsigned int ret = 0;
    while (val > 1) {
        val >>= 1;
        ret++;
    }
    return ret;
}
```

I'm pretty sure that Vivado will optimize the function and generate a proper hardware module.

Reference: How to do an integer log2() in C++?

Edit: I added a Pipeline pragma in order to be sure to obtain a 1-cycle hardware module.

Title: Function log2l has no function body

Body:
I am new to Vivado HLS ( using Vivado HLS 2018.3 ). I am writing this code to generate a 16-bit CRC (Cyclic Redundancy Check) using a 128-bit message and 17-bit generator polynomial. Here in the source code, I am using log2l() in order to find out the number of bits. This code runs smoothly during C Simulation but during C Synthesis, it throws the error :

Function 'log2l' has no function body

Please see the full source code below :

#include "header.h"
#include "ap_int.h"
using namespace std;

int crc(ap_int<128>  dword,ap_int<17>  gen){

int l_gen = floor(log2l(gen) + 1);

ap_int<136> dividend = dword << (l_gen-1);

// shft specifies the no. of least significant bits not being XORed

int shft = (int) (floor(log2l(dividend))+1) - l_gen;

ap_int<16> rem;  //rem variable stores the CRC value

while (shft >= 0){

    // bitwise XOR the MSBs of dividend with generator
    // replace the operated MSBs from the dividend with
    // remainder generated
    rem = (dividend >> shft) ^ gen;//
    // (dividend & ((1 << shft) - 1)) : bits of dividend that were not XORed
    dividend = (dividend & ((1 << shft) - 1)) | (rem << shft); // new dividend

    // change shft variable
   shft = (int) (floor(log2l(dividend))+1) - l_gen;

}

// finally, AND the initial dividend with the remainder (=dividend)
ap_int<144> codeword;  //128 bit message plus 16 bit CRC = 144 bit
codeword = (dword << (l_gen - 1)) | dividend;
cout << "Remainder: " << dividend << endl;
cout << "Codeword to be sent : " << codeword << endl;

return 0 ;

}

The test bench that I am using is :

#include "header.h"
#include "ap_int.h"
using namespace std;

int crc(ap_int<128> , ap_int<17> );

int main()

{
    ap_int<128>dataword ;
    ap_int<17> generator;
    dataword = 36;
    generator = 13;
    crc(dataword, generator);
    cout<<" Majid wins";
    return 0;
}

The header file is :

#include<iostream>
#include<math.h>
#include "ap_fixed.h"
#include "hls_stream.h"

In C simulation, the output that I get is :

Remainder: 1
Codeword to be sent : 289
Majid wins

I am using only three files : source , testbench and header.

Please tell me why this code is not working in C Synthesis. Also if you find anything amiss in my code, please tell me. Thanks !

Body:
I suspect it has something to do with the inclusion of the math library. I guess Vivado HLS has some configurations or flags to supply in compilation and then in synthesis regarding the use of mathematical functions.

Nevertheless, a simple and effective workaround would be to implement floor(log2(x)) yourself, something that looks as follows:

template <typename T>
unsigned int mylog2 (T val) {
#pragma HLS PIPELINE II=1
    if (val == 0) return (1 << (val::size-1)); // A very big number, assuming T is always ap_int<>
    if (val == 1) return 0;
    unsigned int ret = 0;
    while (val > 1) {
        val >>= 1;
        ret++;
    }
    return ret;
}

I'm pretty sure that Vivado will optimize the function and generate a proper hardware module.

Reference: How to do an integer log2() in C++?

Edit: I added a Pipeline pragma in order to be sure to obtain a 1-cycle hardware module.


问:
How to run Python scripts on Azure?
I am trying to run some Python code in Azure, for the first time ever. I Googled 'how to run Python scripts in Azure' and came across the following link.

https://learn.microsoft.com/en-us/azure/automation/learn/automation-tutorial-runbook-textual-python-3

Essentially, I need to do this.

Open the textual editor by selecting Edit on the MyFirstRunbook-Python3 pane.

Add the following code to authenticate to Azure:

```<code>import os
from azure.mgmt.compute import ComputeManagementClient
import azure.mgmt.resource
import automationassets

def get_automation_runas_credential(runas_connection):
    from OpenSSL import crypto
    import binascii
    from msrestazure import azure_active_directory
    import adal

    # Get the Azure Automation RunAs service principal certificate
    cert = automationassets.get_automation_certificate("AzureRunAsCertificate")
    pks12_cert = crypto.load_pkcs12(cert)
    pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())

    # Get run as connection information for the Azure Automation service principal
    application_id = runas_connection["ApplicationId"]
    thumbprint = runas_connection["CertificateThumbprint"]
    tenant_id = runas_connection["TenantId"]

    # Authenticate with service principal certificate
    resource ="https://management.core.windows.net/"
    authority_url = ("https://login.microsoftonline.com/"+tenant_id)
    context = adal.AuthenticationContext(authority_url)
    return azure_active_directory.AdalAuthentication(
    lambda: context.acquire_token_with_client_certificate(
            resource,
            application_id,
            pem_pkey,
            thumbprint)
    )

# Authenticate to Azure using the Azure Automation RunAs service principal
runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
azure_credential = get_automation_runas_credential(runas_connection)
</code>```

When I run that code, I get this error.

```<code>Failed
Traceback (most recent call last):  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 155, in _issue_request    response = urllib.request.urlopen(request)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 222, in urlopen    return opener.open(url, data, timeout)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 531, in open    response = meth(req, response)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 640, in http_response    response = self.parent.error(  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 569, in error    return self._call_chain(*args)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 502, in _call_chain    result = func(*args)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 649, in http_error_default    raise HTTPError(req.full_url, code, msg, hdrs, fp)urllib.error.HTTPError: HTTP Error 404: Not FoundDuring handling of the above exception, another exception occurred:Traceback (most recent call last):  File "C:\Temp\nmcijfgi.bro\a761c289-67d9-493a-99b2-3ba7d46a7cd9", line 36, in <module>    runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 232, in get_automation_connection    connection = _client.get_connection_asset(name)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 187, in get_connection_asset    return self._issue_request(url, method=self._GET)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 158, in _issue_request    raise AutomationAssetNotFound()automationassets.AutomationAssetNotFound
</code>```

Do I need 'cert', 'pks12_cert', or 'pem_pkey'? I don't think I have those. I'm not even sure what those things are.  Again, I am trying to setup my Azure environment to run a Python script, which works totally fine on my desktop (Spyder).

答: Most likely you haven't created an Azure Run As Account. Follow the steps here to do so.

Title: How to run Python scripts on Azure?

Body:
I am trying to run some Python code in Azure, for the first time ever. I Googled 'how to run Python scripts in Azure' and came across the following link.

https://learn.microsoft.com/en-us/azure/automation/learn/automation-tutorial-runbook-textual-python-3

Essentially, I need to do this.

Open the textual editor by selecting Edit on the MyFirstRunbook-Python3 pane.

Add the following code to authenticate to Azure:

import os
from azure.mgmt.compute import ComputeManagementClient
import azure.mgmt.resource
import automationassets

def get_automation_runas_credential(runas_connection):
    from OpenSSL import crypto
    import binascii
    from msrestazure import azure_active_directory
    import adal

    # Get the Azure Automation RunAs service principal certificate
    cert = automationassets.get_automation_certificate("AzureRunAsCertificate")
    pks12_cert = crypto.load_pkcs12(cert)
    pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())

    # Get run as connection information for the Azure Automation service principal
    application_id = runas_connection["ApplicationId"]
    thumbprint = runas_connection["CertificateThumbprint"]
    tenant_id = runas_connection["TenantId"]

    # Authenticate with service principal certificate
    resource ="https://management.core.windows.net/"
    authority_url = ("https://login.microsoftonline.com/"+tenant_id)
    context = adal.AuthenticationContext(authority_url)
    return azure_active_directory.AdalAuthentication(
    lambda: context.acquire_token_with_client_certificate(
            resource,
            application_id,
            pem_pkey,
            thumbprint)
    )

# Authenticate to Azure using the Azure Automation RunAs service principal
runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
azure_credential = get_automation_runas_credential(runas_connection)

When I run that code, I get this error.

Failed
Traceback (most recent call last):  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 155, in _issue_request    response = urllib.request.urlopen(request)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 222, in urlopen    return opener.open(url, data, timeout)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 531, in open    response = meth(req, response)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 640, in http_response    response = self.parent.error(  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 569, in error    return self._call_chain(*args)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 502, in _call_chain    result = func(*args)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\urllib\request.py", line 649, in http_error_default    raise HTTPError(req.full_url, code, msg, hdrs, fp)urllib.error.HTTPError: HTTP Error 404: Not FoundDuring handling of the above exception, another exception occurred:Traceback (most recent call last):  File "C:\Temp\nmcijfgi.bro\a761c289-67d9-493a-99b2-3ba7d46a7cd9", line 36, in <module>    runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 232, in get_automation_connection    connection = _client.get_connection_asset(name)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 187, in get_connection_asset    return self._issue_request(url, method=self._GET)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\automationassets.py", line 158, in _issue_request    raise AutomationAssetNotFound()automationassets.AutomationAssetNotFound

Do I need 'cert', 'pks12_cert', or 'pem_pkey'? I don't think I have those. I'm not even sure what those things are.  Again, I am trying to setup my Azure environment to run a Python script, which works totally fine on my desktop (Spyder).


问:
How to scale my app on nginx metrics without prometheus?
I want to scale my application based on custom metrics (RPS or active connections in this cases). Without having to set up prometheus or use any external service. I can expose this API from my web app. What are my options?</p>

答:
Monitoring different types of metrics (e.g. custom metrics) on most Kubernetes clusters is the foundation that leads to more stable and reliable systems/applications/workloads. As discussed in the comments section, to monitor custom metrics, it is recommended to use  tools designed for this purpose rather than inventing a workaround. I'm glad that in this case the final decision was to use Prometheus and KEDA to properly scale the web application.

I would like to briefly show other community members who are struggling with similar considerations how KEDA works.

To use Prometheus as a scaler for Keda, we need to install and configure Prometheus.
There are many different ways to install Prometheus and you should choose the one that suits your needs.

I've installed the kube-prometheus stack with Helm:

NOTE: I allowed Prometheus to discover all PodMonitors/ServiceMonitors within its namespace, without applying label filtering by setting the prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues and prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues values to false.

```<code>$ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
$ helm repo update
$ helm install prom-1 prometheus-community/kube-prometheus-stack --set prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues=false --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false

$ kubectl get pods
NAME                                                     READY   STATUS    RESTARTS   AGE
alertmanager-prom-1-kube-prometheus-sta-alertmanager-0   2/2     Running   0          2m29s
prom-1-grafana-865d4c8876-8zdhm                          3/3     Running   0          2m34s
prom-1-kube-prometheus-sta-operator-6b5d5d8df5-scdjb     1/1     Running   0          2m34s
prom-1-kube-state-metrics-74b4bb7857-grbw9               1/1     Running   0          2m34s
prom-1-prometheus-node-exporter-2v2s6                    1/1     Running   0          2m34s
prom-1-prometheus-node-exporter-4vc9k                    1/1     Running   0          2m34s
prom-1-prometheus-node-exporter-7jchl                    1/1     Running   0          2m35s
prometheus-prom-1-kube-prometheus-sta-prometheus-0       2/2     Running   0          2m28s
</code>```

Then we can deploy an application that will be monitored by Prometheus. I've created a simple application that exposes some metrics (such as nginx_vts_server_requests_total) on the /status/format/prometheus path:

```<code>$ cat app-1.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-1
spec:
  selector:
    matchLabels:
      app: app-1
  template:
    metadata:
      labels:
        app: app-1
    spec:
      containers:
      - name: app-1
        image: mattjcontainerregistry/nginx-vts:v1.0
        resources:
          limits:
            cpu: 50m
          requests:
            cpu: 50m
        ports:
        - containerPort: 80
          name: http
---
apiVersion: v1
kind: Service
metadata:
  name: app-1
  labels:
    app: app-1
spec:
  ports:
  - port: 80
    targetPort: 80
    name: http
  selector:
    app: app-1
  type: LoadBalancer
</code>```

Next, create a ServiceMonitor that describes how to monitor our app-1 application:

```<code>$ cat servicemonitor.yaml
kind: ServiceMonitor
apiVersion: monitoring.coreos.com/v1
metadata:
  name: app-1
  labels:
    app: app-1
spec:
  selector:
    matchLabels:
      app: app-1
  endpoints:
  - interval: 15s
    path: "/status/format/prometheus"
    port: http
</code>```

After waiting some time, let's check the app-1 logs to make sure that it is scrapped correctly:

```<code>$ kubectl get pods | grep app-1
app-1-5986d56f7f-2plj5                                   1/1     Running   0          35s

$ kubectl logs -f app-1-5986d56f7f-2plj5
10.44.1.6 - - [07/Feb/2022:16:31:11 +0000] "GET /status/format/prometheus HTTP/1.1" 200 2742 "-" "Prometheus/2.33.1" "-"
10.44.1.6 - - [07/Feb/2022:16:31:26 +0000] "GET /status/format/prometheus HTTP/1.1" 200 3762 "-" "Prometheus/2.33.1" "-"
10.44.1.6 - - [07/Feb/2022:16:31:41 +0000] "GET /status/format/prometheus HTTP/1.1" 200 3762 "-" "Prometheus/2.33.1" "-"
</code>```

Now it's time to deploy KEDA. There are a few approaches to deploy KEDA runtime as described in the KEDA documentation.
I chose to install KEDA with Helm because it's very simple :-)

```<code>$ helm repo add kedacore https://kedacore.github.io/charts
$ helm repo update
$ kubectl create namespace keda
$ helm install keda kedacore/keda --namespace keda
</code>```

The last thing we need to create is a ScaledObject which is used to define how KEDA should scale our application and what the triggers are. In the example below, I used the nginx_vts_server_requests_total metric.

NOTE: For more information on the prometheus trigger, see the Trigger Specification documentation.

```<code>$ cat scaled-object.yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: scaled-app-1
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: app-1
  pollingInterval: 30
  cooldownPeriod:  120
  minReplicaCount: 1
  maxReplicaCount: 5
  advanced:
    restoreToOriginalReplicaCount: false
    horizontalPodAutoscalerConfig:
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
          - type: Percent
            value: 100
            periodSeconds: 15
  triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prom-1-kube-prometheus-sta-prometheus.default.svc:9090
      metricName: nginx_vts_server_requests_total
      query: sum(rate(nginx_vts_server_requests_total{code="2xx", service="app-1"}[2m])) # Note: query must return a vector/scalar single element response
      threshold: '10'

$ kubectl apply -f scaled-object.yaml
scaledobject.keda.sh/scaled-app-1 created
</code>```

Finally, we can check if the app-1 application scales correctly based on the number of requests:

```<code>$ for a in $(seq 1 10000); do curl <PUBLIC_IP_APP_1> 1>/dev/null 2>&1; done

$ kubectl get hpa -w
NAME                    REFERENCE          TARGETS          MINPODS   MAXPODS   REPLICAS
keda-hpa-scaled-app-1   Deployment/app-1   0/10 (avg)        1         5         1
keda-hpa-scaled-app-1   Deployment/app-1   15/10 (avg)       1         5         2
keda-hpa-scaled-app-1   Deployment/app-1   12334m/10 (avg)   1         5         3
keda-hpa-scaled-app-1   Deployment/app-1   13250m/10 (avg)   1         5         4
keda-hpa-scaled-app-1   Deployment/app-1   12600m/10 (avg)   1         5         5

$ kubectl get pods | grep app-1
app-1-5986d56f7f-2plj5                                   1/1     Running   0          36m
app-1-5986d56f7f-5nrqd                                   1/1     Running   0          77s
app-1-5986d56f7f-78jw8                                   1/1     Running   0          94s
app-1-5986d56f7f-bl859                                   1/1     Running   0          62s
app-1-5986d56f7f-xlfp6                                   1/1     Running   0          45s
</code>```

As you can see above, our application has been correctly scaled to 5 replicas.

Body:
Monitoring different types of metrics (e.g. custom metrics) on most Kubernetes clusters is the foundation that leads to more stable and reliable systems/applications/workloads. As discussed in the comments section, to monitor custom metrics, it is recommended to use  tools designed for this purpose rather than inventing a workaround. I'm glad that in this case the final decision was to use Prometheus and KEDA to properly scale the web application.

I would like to briefly show other community members who are struggling with similar considerations how KEDA works.

To use Prometheus as a scaler for Keda, we need to install and configure Prometheus.
There are many different ways to install Prometheus and you should choose the one that suits your needs.

I've installed the kube-prometheus stack with Helm:

NOTE: I allowed Prometheus to discover all PodMonitors/ServiceMonitors within its namespace, without applying label filtering by setting the prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues and prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues values to false.

$ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
$ helm repo update
$ helm install prom-1 prometheus-community/kube-prometheus-stack --set prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues=false --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false

$ kubectl get pods
NAME                                                     READY   STATUS    RESTARTS   AGE
alertmanager-prom-1-kube-prometheus-sta-alertmanager-0   2/2     Running   0          2m29s
prom-1-grafana-865d4c8876-8zdhm                          3/3     Running   0          2m34s
prom-1-kube-prometheus-sta-operator-6b5d5d8df5-scdjb     1/1     Running   0          2m34s
prom-1-kube-state-metrics-74b4bb7857-grbw9               1/1     Running   0          2m34s
prom-1-prometheus-node-exporter-2v2s6                    1/1     Running   0          2m34s
prom-1-prometheus-node-exporter-4vc9k                    1/1     Running   0          2m34s
prom-1-prometheus-node-exporter-7jchl                    1/1     Running   0          2m35s
prometheus-prom-1-kube-prometheus-sta-prometheus-0       2/2     Running   0          2m28s

Then we can deploy an application that will be monitored by Prometheus. I've created a simple application that exposes some metrics (such as nginx_vts_server_requests_total) on the /status/format/prometheus path:

$ cat app-1.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-1
spec:
  selector:
    matchLabels:
      app: app-1
  template:
    metadata:
      labels:
        app: app-1
    spec:
      containers:
      - name: app-1
        image: mattjcontainerregistry/nginx-vts:v1.0
        resources:
          limits:
            cpu: 50m
          requests:
            cpu: 50m
        ports:
        - containerPort: 80
          name: http
---
apiVersion: v1
kind: Service
metadata:
  name: app-1
  labels:
    app: app-1
spec:
  ports:
  - port: 80
    targetPort: 80
    name: http
  selector:
    app: app-1
  type: LoadBalancer

Next, create a ServiceMonitor that describes how to monitor our app-1 application:

$ cat servicemonitor.yaml
kind: ServiceMonitor
apiVersion: monitoring.coreos.com/v1
metadata:
  name: app-1
  labels:
    app: app-1
spec:
  selector:
    matchLabels:
      app: app-1
  endpoints:
  - interval: 15s
    path: "/status/format/prometheus"
    port: http

After waiting some time, let's check the app-1 logs to make sure that it is scrapped correctly:

$ kubectl get pods | grep app-1
app-1-5986d56f7f-2plj5                                   1/1     Running   0          35s

$ kubectl logs -f app-1-5986d56f7f-2plj5
10.44.1.6 - - [07/Feb/2022:16:31:11 +0000] "GET /status/format/prometheus HTTP/1.1" 200 2742 "-" "Prometheus/2.33.1" "-"
10.44.1.6 - - [07/Feb/2022:16:31:26 +0000] "GET /status/format/prometheus HTTP/1.1" 200 3762 "-" "Prometheus/2.33.1" "-"
10.44.1.6 - - [07/Feb/2022:16:31:41 +0000] "GET /status/format/prometheus HTTP/1.1" 200 3762 "-" "Prometheus/2.33.1" "-"

Now it's time to deploy KEDA. There are a few approaches to deploy KEDA runtime as described in the KEDA documentation.
I chose to install KEDA with Helm because it's very simple :-)

$ helm repo add kedacore https://kedacore.github.io/charts
$ helm repo update
$ kubectl create namespace keda
$ helm install keda kedacore/keda --namespace keda

The last thing we need to create is a ScaledObject which is used to define how KEDA should scale our application and what the triggers are. In the example below, I used the nginx_vts_server_requests_total metric.

NOTE: For more information on the prometheus trigger, see the Trigger Specification documentation.

$ cat scaled-object.yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: scaled-app-1
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: app-1
  pollingInterval: 30
  cooldownPeriod:  120
  minReplicaCount: 1
  maxReplicaCount: 5
  advanced:
    restoreToOriginalReplicaCount: false
    horizontalPodAutoscalerConfig:
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
          - type: Percent
            value: 100
            periodSeconds: 15
  triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prom-1-kube-prometheus-sta-prometheus.default.svc:9090
      metricName: nginx_vts_server_requests_total
      query: sum(rate(nginx_vts_server_requests_total{code="2xx", service="app-1"}[2m])) # Note: query must return a vector/scalar single element response
      threshold: '10'

$ kubectl apply -f scaled-object.yaml
scaledobject.keda.sh/scaled-app-1 created

Finally, we can check if the app-1 application scales correctly based on the number of requests:

$ for a in $(seq 1 10000); do curl <PUBLIC_IP_APP_1> 1>/dev/null 2>&1; done

$ kubectl get hpa -w
NAME                    REFERENCE          TARGETS          MINPODS   MAXPODS   REPLICAS
keda-hpa-scaled-app-1   Deployment/app-1   0/10 (avg)        1         5         1
keda-hpa-scaled-app-1   Deployment/app-1   15/10 (avg)       1         5         2
keda-hpa-scaled-app-1   Deployment/app-1   12334m/10 (avg)   1         5         3
keda-hpa-scaled-app-1   Deployment/app-1   13250m/10 (avg)   1         5         4
keda-hpa-scaled-app-1   Deployment/app-1   12600m/10 (avg)   1         5         5

$ kubectl get pods | grep app-1
app-1-5986d56f7f-2plj5                                   1/1     Running   0          36m
app-1-5986d56f7f-5nrqd                                   1/1     Running   0          77s
app-1-5986d56f7f-78jw8                                   1/1     Running   0          94s
app-1-5986d56f7f-bl859                                   1/1     Running   0          62s
app-1-5986d56f7f-xlfp6                                   1/1     Running   0          45s

As you can see above, our application has been correctly scaled to 5 replicas.