Friday, June 18, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


LP maximization problem Python: Hydro power model

Posted: 18 Jun 2021 09:15 AM PDT

I have a optimization problem (simple hydro power model) with this properties:

Objective function:

Maximize {sum[p(i)w(i)] + vv} for i=(0,24)

Constraints:
0 <= w(i) <= 16
0 <= V(i) <= 45

Where:
V(i+1) = V(i) - w(i) + q
V(0) = 30
vv = 275
p=[280.91, 280.3, 279.48, 27825, 276.81, 274.66, 271.89, 276.91, 274.45, 277.22, 276.91, 275.99, 271.59, 267.49, 265.95, 268.31, 271.28, 276.2, 276.91, 277.02, 276.4, 276.81, 274.45, 271.59]

p - known array with 24 elements
w - variable array with 24 elemets
V - array with 24 elements dependent of w(i)

Do anyone have a suggestion on how to solve this problem? I have found many mathematical problems, but no one with arrays. Also happy if you know any helpful articles/discussions.

Guess I also need help to format my mathematical expressions.

If you are curious about the model:
p - power price
w - power production
V - reservoir volume
vv - water value (known constant)
q - inflow (known constant)

Why is MySQL writing 5 times more data to disk, than is committed to the database?

Posted: 18 Jun 2021 09:14 AM PDT

I have installed MySQL 8.0.25 on top of Ubuntu 20.04, running on the C5.2xlarge instance.

Then I ran a script that fills 10 tables with data. The test took exactly 2 hours, during which is has created 123146.5MB of data: enter image description here

That means that on average, 17.1MB/s were written to the database. However, atop is reporting something weird: while it shows disk activity around 18-19MB/s, it also shows that the process mysqld wrote 864MB in the 10 second sample - which translates to 86.4MB/s, about 5 times as much as the amount of data actually committed to the database: enter image description here

Why such disrepancy?

iotop is also typically showing that MySQL is writing 5x: enter image description here

Same for pidstat: enter image description here

I also tried to use pt-diskstats from the Percona toolkit, but it didn't show anything... enter image description here

I also reproduced the issue on RDS. In both cases (EC2 and RDS), the Cloudwatch statistics also show 5x writes...

The database has 10 tables that were filled. 5 of them have this definition:

mysql> SHOW CREATE TABLE shark;  +-------+---------------------------------------------------------------------------------+  | Table | Create Table                                                                    |  +-------+---------------------------------------------------------------------------------+  | shark | CREATE TABLE `shark` (    `height` int DEFAULT NULL,    `weight` int DEFAULT NULL,    `name` mediumtext,    `shark_id` bigint NOT NULL,    `owner_id` bigint DEFAULT NULL,    PRIMARY KEY (`shark_id`),    KEY `owner_id` (`owner_id`),    CONSTRAINT `shark_ibfk_1` FOREIGN KEY (`owner_id`) REFERENCES `shark_owners` (`owner_id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |  +-------+---------------------------------------------------------------------------------+  

another 5 tables have this definition:

mysql> SHOW CREATE TABLE shark_owners;  +--------------+---------------------------------------------------+  | Table        | Create Table                                      |  +--------------+---------------------------------------------------+  | shark_owners | CREATE TABLE `shark_owners` (    `name` mediumtext,    `owner_id` bigint NOT NULL,    PRIMARY KEY (`owner_id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |  +--------------+---------------------------------------------------+  

I could understand if the difference was about 2x - data is first written to a transaction log, and then it is committed to the database, but 5x? Is this a normal behavior for MySQL, or is something in my tables triggering this? And why are there so many "cancelled writes" - about 12% ?

ChartJS - How to display grid lines (without showing label) between each ticks?

Posted: 18 Jun 2021 09:14 AM PDT

enter image description here

I'm using Chart.js 2 (React-chart-js 2) to display a line chart.

Does anyone have any reference to keeping the vertical gridline between each displayed label?

It seems like the vertical gridline only showing on each displayed label.

Dynamically add a tag component for words of a text - Angular 12

Posted: 18 Jun 2021 09:13 AM PDT

I'm trying to tag some words of a text given the start and end position of a word. I want the tag to be a component so that it can be expanded with more features.

I'm trying to render the TagComponent using innerHTML but that doesn't work with Angular.

How can I render dynamically multiple components?

Here's an example of what I want to achieve:

enter image description here

I'm currently using a pipe which replaces all occurrences with the tag but that as I said, does not work.

Simplifying onClick function prop

Posted: 18 Jun 2021 09:13 AM PDT

I have a React component where I am passing onClick function. I originally just had button.onClick, but I need to check if isBannerClickable is false before setting this. If isBannerClickable === true, then I don't want to set onClick.

Is it possible to simplify or clean this onClick prop?

onClick={!!isBannerClickable === false ? button.onClick : null}  

How to print Products in 2 column layout in Qweb report. Odoo 14

Posted: 18 Jun 2021 09:13 AM PDT

In my report , I want to display products in this way(according to count field which is the quantity in my case)

enter image description here

But actually with the following code , I get :

enter image description here

<?xml version="1.0" encoding="utf-8"?>  <odoo>      <data>          <template id="productt">              <t t-call="web.html_container">                  <t t-call="web.basic_layout">                      <t t-foreach="docs" t-as="doc">                          <div class="page">                              <t t-foreach="doc.product_template_ids" t-as='product'>                                  <t t-foreach="range(int(product.count))" t-as='i'>                                      <div  style="border:2px solid black; width: 95mm; height: 73mm; padding-left: 25px; page-break-inside: avoid;">                                              <span t-esc="product.name"/>                                        </div>                                  </t>                              </t>                  </div>                      </t>                  </t>              </t>          </template>     </data>  </odoo>  

How can I fix it please? Thanks.

How to define selection range of variable length?

Posted: 18 Jun 2021 09:13 AM PDT

Suppose I have a vector of 100 elements. How can I define the selection range based on another vector in the loop? The selection range for each iteration is different, e.g. 50, 30, 20 elements out of 100.

vec = c(50, 30, 20)  for (i in seq_along(vec)) {    # ???  }  

As a result, these ranges are expected:

1:50  51:80  81:100  

If the selection ranges are identical (for example 50, 50, 50), this is easy to do:

vec = c(50, 50, 50)  for (i in seq_along(vec) - 1) {    idx_min = i * 50 + 1    idx_max = i * 50 + 50    print(paste0(idx_min, ":", idx_max))  }  
[1] "1:50"  [1] "51:100"  [1] "101:150"  

Activate autoplay on HTML popup video player

Posted: 18 Jun 2021 09:13 AM PDT

I have bought an HTML template which has a button to play a video in a popup. This is the code:

<div class="video-play-button">  <a href="https://xxxxx/yyyyy/zzz.mp4" class="video  video-play mfp-iframe" data-toggle="modal" data-target="#video-popup">  <span class="ti-control-play"></span>  </a>  </div>  

the video file is stored in AWS S3. When I click on the button, the pop-up with the video player appears but I still need to press Play in order to see the video.

I would like to get the video starting automatically. I know that if the video was on youtube I could use something like ...?autoplay=1 in the URL, but I really need the file on S3

Caret error says: "Metric RMSE not applicable for classification models", but I'm passing it continuous data

Posted: 18 Jun 2021 09:13 AM PDT

I'm trying to pass caret some training data where y is an n x 1 matrix of continuous data. Calling typeof(dfm_y1_train) confirms that it is of type double.

This is the code I'm using:

ctrl <- trainControl(    method = "repeatedcv",    number = 20,    repeats = 3,    allowParallel = TRUE,    search = "random",    verbose = TRUE  )    rf_base <- train(    x = dfm_X1_train,    y = dfm_y1_train,    method = "rf",    # tuneGrid = tune_grid,    tuneLength = 20,    trControl = ctrl,    num.trees = 1000  )  

How I can encourage / convince / force caret to apply regression using a Random Forest?

I also tried using method = "ranger" from Random Forest Regression using Caret, but had the same issue.

Use C# LINQ to return back all database names

Posted: 18 Jun 2021 09:13 AM PDT

I am using MySQL and I need to loop through all the names of the schemas in MySQL and then return back as an array to allow me to loop through the names. How do I achieve this using LINQ?

Are there any way to open greyed buttons in websites?

Posted: 18 Jun 2021 09:14 AM PDT

this picture is from my university's exam website and first button is my next exam. And it makes you go to questions which will be ask from you. How we can gain access to this link before exam without confirmation of the teacher?

Why can't I change the text of a button in HTML?

Posted: 18 Jun 2021 09:14 AM PDT

I'm trying to change the textcontent of a button in HTML using JavaScript.

It does reach the right if statement (the div is by default not showing), and if I use it on a random header in my HTML code it does change that.

// once page is loaded  window.addEventListener('DOMContentLoaded', (e) => {    console.log('loaded');    // get element, and run a function when clicked    document.getElementById("toggleVisibilityButton").addEventListener("click", () => {      console.log("show or hide method");        let element = document.getElementById('reasonsNotConnectedDiv');      let button = document.getElementById('toggleVisibilityButton');        //If element is already hidden.      if (element.style.display === "none") {        //Change button style whether shown or not.        button.textContent = 'Hide info ↑'          //Make contents visible.        element.style.display = "block"      }        //If element is not hidden.      if (element.style.display === "block") {        //Change button style whether shown or not.        button.innerText = button.textContent = "See more ↓"          //Make content invisible.        element.style.display = "none"      }    });  });
<button name="toggleVisibilityButton" id="toggleVisibilityButton">See more ↓</button> and

I have tried different HTML variants of making a button as shown below as well.

// once page is loaded  window.addEventListener('DOMContentLoaded', (e) => {    console.log('loaded');    // get element, and run a function when clicked    document.getElementById("toggleVisibilityButton").addEventListener("click", () => {      console.log("show or hide method");        let element = document.getElementById('reasonsNotConnectedDiv');      let button = document.getElementById('toggleVisibilityButton');        //If element is already hidden.      if (element.style.display === "none") {        //Change button style whether shown or not.        button.textContent = 'Hide info ↑'          //Make contents visible.        element.style.display = "block"      }        //If element is not hidden.      if (element.style.display === "block") {        //Change button style whether shown or not.        button.innerText = button.textContent = "See more ↓"          //Make content invisible.        element.style.display = "none"      }    });  });
<button name="toggleVisibilityButton" id="toggleVisibilityButton" value="See more ↓"></button>

Extract data from a column in pandas DataFrame

Posted: 18 Jun 2021 09:14 AM PDT

how can we extract the car model from the dataframe below:

Output:

2015 Maruti Swift VDI ABS........................... VDI ABS

2012 Maruti Swift Dzire VDI BS IV..............VDI BS IV

2013 Maruti Swift VDI......................................VDI

2012 Maruti Swift VDI......................................VDI

2010 Honda City S MT PETROL................... S MT PETROL

2013 Maruti Swift Dzire VDI BS IV..............VDI BS IV

2014 Maruti Swift Dzire VDI BS IV.............. VDI BS IV

2014 Maruti Swift VDI.......................... ...........VDI

2014 Maruti Swift VXI...................................... VXI

2016 Hyundai Grand i10 SPORTZ 1.2 KAPPA VTVT............................. SPORTZ 1.2 KAPPA VTVT

2013 Maruti Swift Dzire ZDI..........................ZDI

2012 Hyundai i20 SPORTZ 1.4 CRDI......................1.4 CRDI

2010 Hyundai i10 MAGNA 1.2 KAPPA2......................MAGNA 1.2KAPPA2

2019 Maruti Vitara Brezza VDI ................VDI

2017 Maruti Vitara Brezza VDI OPT......................VDI OPT

2013 Maruti Swift Dzire VXI 1.2 BS IV..................VXI 1.2 B

2017 Maruti Alto 800 LXI...............................800 LXI

2009 Hyundai i10 MAGNA 1.2.............................MAGNA 1.2

AWS windows userdata hung at startup

Posted: 18 Jun 2021 09:14 AM PDT

AWS user data is not running in windows custom AMI , because instance initialization script stuck at system startup.

user-data executed successfully if we execute user-data script manually from task schedular else it's stuck at  " tag was provided.. running PowerShell content" (logs from C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution)

userdata logs

enter image description here

Instance initialization hung screenshot 

enter image description here

in the user-data we are trying to execute the below PowerShell script.

  <powershell>    cd 'C:\Projects\'    pm2 kill    pm2 start    </powershell>    <persist>true</persist>  

Extract song names from a long string

Posted: 18 Jun 2021 09:13 AM PDT

I am making a small little project that should extract song and artist names from youtube videos. Currently I have the video description that has the following structure

Text text text    Tracklist:  [00:00] Sobs - Girl  [02:25] Mopac - Cross-Eyed Dreaming  [05:54] L I P S - In Summer  [09:18] Small Wood House - T.V    Text text text  

I want to be able to extract the Artist name and Song name from this string. I am trying to use Regex to do this and the regex I have right now matches the timecode and any text before a newline.

'((.*([0-9]?[0-9]:)?[0-5][0-9]:[0-5][0-9]).*\n)+'  

Now I need to find a way to match any text before the timecodes but not include them in the final string and also do this for the timecode. I tried to use capturing groups but it was unsuccessful.

The result I want should look like this

Sobs - Girl  Mopac - Cross-Eyed Dreaming  L I P S - In Summer  Small Wood House - T.V  

Meteor import async function to be used in a method call

Posted: 18 Jun 2021 09:14 AM PDT

This Meteor app gives the error TypeError: vinXXX is not a function when trying to call an exported async function saved in a const variable "vinXXX" from within a method call in a sibiling folder which has been imported in the methods follder. Any idea why and how to fix it? Thanks

//imports/api/vehicles/methods.js    import { vinXXX } from './vinXXX.js'  Meteor.methods({      'extractData': function (plate) {          console.log('method called: ', plate)          vinXXX(plate, 'UUU');  // CAR HISTORY      }  });        //imports/api/vehicles/vinXXX.js    const vinXXX = async (plate, state) => {...}  module.exports = vinXXX;

PyQt - Q types vs builtin types

Posted: 18 Jun 2021 09:14 AM PDT

I recently started working with PyQt and noticed that there are some Q types that more or less resemble python builtin types like QString and QStringList (I guess there are some more).

Till now i just used builtin types like str and list instead of these, which worked perfectly fine.

But now I'm wondering:

  • What is the use of these Q types?
  • Should I use these instead of the builtin types?

How do I filter MatTableDataSource using wildcards

Posted: 18 Jun 2021 09:13 AM PDT

I am using the example Table with filtering from Angular Material's site https://material.angular.io/components/table/examples

I want to let users search using wildcards. In this case, a %

I wrote the following:

    const filterValue = (event.target as HTMLInputElement).value;        let filterArray = filterValue.trim().toLowerCase().split("%");        for (let fil of filterArray) {        //I know this line below won't work, as it will just replace the filter with each iteration, but showing for sake of example        this.tableData.filter = fil;              }  

So if the user types one%two in the input field, I would want the filter to find table rows where both the words "one" AND "two" exist somewhere in the row.

I have tried several variations of code, but nothing seems to work quite right. Any ideas on how to make this work?

how to split a full file path into a path and a file name without an extension

Posted: 18 Jun 2021 09:14 AM PDT

how to split a full file path into a path and a file name without an extension? I'm looking for any files with the extension .conf: find /path -name .conf /path/file1.conf /path/smth/file2.conf /path/smth/file3.conf /path/smth/smth1/.conf ... /path/smt//*.conf

I need the output in string(without extension .conf): /path;file1|path/smth;file2;file3|...

What's the best way to do it? I was thinking of a solution - save the output of the find work to a file and process them in a loop..but maybe there is a more effective way. Sorry for mistakes, I newbie.. Thanx for u feedback, guys!

Package validation Error while loading data from SQL server to flat file using SSIS

Posted: 18 Jun 2021 09:13 AM PDT

I am trying to load data from an SQL server to a text file using OLE DB Connection. I am facing the below error message. Could someone help in resolving this? enter image description here

OLEDB connection is already details enter image description here

Calculate progress based on possible paths (JavaScript Questions)

Posted: 18 Jun 2021 09:13 AM PDT

I'm trying to workout remaining questionnaire progress without bouncing the progress bar percentage back every time there is more questions added.

End goal scenario:

User enters questionnaire, they're on question one there is 4 questions to answers the progress bar is split in to 4. The user gets to question 3 but by clicking option 2 on question 3 now adds 2 extra questions to answer. The progress bar should stay at the current percentage but work out the remaining percentage based on 3 answers.

Hope the above scenario makes sense.

Below is a very rough idea of what I have so far:

// Questions  let questions = {      1: {          title: "Title",          firstQuestion: true,          options: [{              tooltip: "",              nextQuestion: 2          }, {              tooltip: "",              nextQuestion: 2          }, {              tooltip: "",              nextQuestion: 10000          }]      },      2: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 3          }, {              tooltip: "",              nextQuestion: 3          }, {              tooltip: "",              nextQuestion: 3          }, {              tooltip: "",              nextQuestion: 3          }]      },      3: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 4          }, {              tooltip: "",              nextQuestion: 4          }, {              tooltip: "",              nextQuestion: 4          }]      },      4: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 13          }, {              tooltip: "",              nextQuestion: 5          }]      },      5: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 6          }, {              tooltip: "",              nextQuestion: 6          }, {              tooltip: "",              nextQuestion: 6          }, {              tooltip: "",              nextQuestion: 10000          }]      },      6: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 7          }, {              tooltip: "",              nextQuestion: 7          }, {              tooltip: "",              nextQuestion: 7          }, {              tooltip: "",              nextQuestion: 7          }, {              tooltip: "",              nextQuestion: 14          }]      },      7: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 17          }, {              tooltip: "",              nextQuestion: 17          }, {              tooltip: "",              nextQuestion: 17          }, {              tooltip: "",              nextQuestion: 17          }, {              tooltip: "",              nextQuestion: 17          }]      },      8: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 9          }, {              tooltip: "",              nextQuestion: 9          }, {              tooltip: "",              nextQuestion: 9          }]      },      9: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 10          }, {              tooltip: "",              nextQuestion: 10          }, {              tooltip: "",              nextQuestion: 10          }]      },      10: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 11          }, {              value: "Roof",              attribute: "Flue Exit",              tooltip: "",              nextQuestion: 15          }]      },      11: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 12          }, {              tooltip: "",              nextQuestion: 12          }]      },      12: {          finalQuestion: true,          input: true,          placeHolder: 'e.g SWS'      },      13: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 6          }, {              tooltip: "",              nextQuestion: 6          }]      },      14: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 7          }, {              tooltip: "",              nextQuestion: 7          }, {              tooltip: "",              nextQuestion: 10000          }]      },      15: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 12          }, {              tooltip: "",              nextQuestion: 12          }]      },      17: {          title: "Title",          options: [{              tooltip: "",              nextQuestion: 8          }, {              tooltip: "",              nextQuestion: 8          }, {              tooltip: "",              nextQuestion: 8          }, {              tooltip: "",              nextQuestion: 8          }, {              tooltip: "",              nextQuestion: 8          }]      },      // Errors      10000: {          isError: true,          title: "Finally, what is the first part of your postcode?",          error: "Postcode"      }  };    // Answers filled in  let answersPath = [1, 2, 3];    // Find the max valid answer  function maxValidAnswer () {      let objectKeys = Object.keys(questions).filter(x => {      return questions[x].error == undefined    });            return objectKeys.length;  }    // Calculate Percentage  function calculateAnswers () {      const myBar = document.getElementById('myBar');     const lastAnswerFilled = Math.max.apply(Math, answersPath);    const percentage = ((lastAnswerFilled / maxValidAnswer()) / 100) * 10000;          myBar.style.width = `${percentage}%`;    myBar.innerHTML = `${percentage}%`  }    calculateAnswers();
#myProgress {    width: 100%;    background-color: #ddd;  }    #myBar {    width: 10%;    height: 30px;    background-color: #04AA6D;    text-align: center;    line-height: 30px;    color: white;  }
<div id="myProgress">    <div id="myBar"></div>  </div>

After speaking in comments

The best scenario would be to generate all possible paths and work out the progress based on already selected questions vs possible path. Possible paths like this solution but based on questions: https://nsisodiya.medium.com/find-all-paths-from-point-1-to-n-algorithm-problem-solving-with-javascript-9de778a22243?source=follow_footer---------4----------------------------

Include a line feed in a powershell script argument

Posted: 18 Jun 2021 09:13 AM PDT

I am using a .bat file to invoke a powershell script.

Powershell.exe -executionpolicy remotesigned -File C:\Users\%UserName%\Desktop\PushOverPS.ps1 "Line1\nLine2"  

I want my pushover message to be multiline, and the above just has a single line with the \n in it. The Pushover support people said I should try including a line feed rather than the \n. How would I do that?

Here is the powershell script:

$uri = "https://api.pushover.net/1/messages.json"  $parameters = @{    token = "removed"    user = "removed"    message = $args[0]  }  $parameters | Invoke-RestMethod -Uri $uri -Method Post   

My .bat file is passing an argument (string) to the PS script. So far, adding \n or ` in the string being passed does not result in a multiline message.

Finding the longest most frequent subset in list of lists

Posted: 18 Jun 2021 09:14 AM PDT

I need an efficient Python algorithm to get to the following outcome(s):

example 1:

l = [[1, 2, 3, 4], [2, 1, 4], [3, 1], [4, 1, 2]]    r = [[1, 2, 4], [3]]  

example 2:

l = [[1, 2, 3, 4], [2, 1], [3, 1], [4, 1]]    r = [[1, 2], [3], [4]]  

example 3:

l = [[1], [2, 3, 4], [3, 2, 5, 6], [4, 2] , [5, 3], [6, 3]]    r = [[2, 3], [1], [4], [5], [6]]  

In these examples l is a list of lists, where:

  • the first element of each list is always the index of the element
  • if element 1 contains the value 3, then in its turn the 3rd list will always contain the 1 itself.

What I need is to find an efficient way to group matching subsets using 3 criteria: length of subset, frequency of sub-elements and the fact that a sub-element can only be part of 1 resulting subset.

In the 1st example the sub-element [1] would be the most frequent subset, but the fact that the longer subset [1, 2, 4] was found in 3 of the 4 elements is more important: length trumps frequency.

In the 2nd example a grouping such as [1, 3] has the same length and frequency as [1, 2], but the the 1 is "taken" by the firstly found subset.

Later edit:

What I did so far is:

  • I turned my list of lists into a dictionary
  • then I built a function which repeatedly builds square matrixes of matched and not matched values, based on all possible permutations the unique keys of my dictionary
  • then in the square matrixes I search for the largest squares along the main diagonal (based on a code provided here: Python find the largest square in the matrix dynamic programming)
  • then I eliminate the largest squares which overlap and start allover again

My code is totally inefficient because the number of permutations grows exponentially with the size of my initial dictionary, therefore I am looking for a new idea, a new approach.

Here is what I have done so far:

  from itertools import chain, permutations    def group_matches(my_dict, matched=None):        def update_my_dict(my_dict, matched):          ret_val = {}          for k, v in my_dict.items():              if k not in matched:                  for unique_ind in matched:                      if unique_ind in v:                          v.remove(unique_ind)                  ret_val[k] = v          return ret_val        def get_matches(unique_ind_permutation, my_dict):          def create_matrix(unique_ind_permutation, my_dict):              matrix = []              for k in unique_ind_permutation:                  r = [True if f in my_dict[k] else False                       for f in unique_ind_permutation]                  matrix += [r]              return matrix          matrix = create_matrix(unique_ind_permutation, my_dict)          dp = [[0] * len(matrix) for _ in range(len(matrix))]          max_squares = [(0, None, None)]          for ri, r in enumerate(matrix):              for ci, c in enumerate(r):                  dp[ri][ci] = 0 if not c \                      else (1 if ri == 0 or ci == 0                      else min(dp[ri - 1][ci], dp[ri][ci - 1], dp[ri - 1][ci - 1]) + 1)                  max_squares = [(dp[ri][ci], ri, ci)] if dp[ri][ci] > max_squares[0][0] \                      else (max_squares + [(dp[ri][ci], ri, ci)] if dp[ri][ci] == max_squares[0][0]                      else max_squares)          matches = []          if max_squares[0][0] != 0:              for max_square in max_squares:                  rows = [r for r in range(max_square[1]+1-max_square[0],max_square[1]+1)]                  columns = [c for c in range(max_square[2]+1-max_square[0],max_square[2]+1)]                  if rows == columns:                      matches += [tuple(rows)]              matches = eliminate_common_matches(matches)          matches_to_unique_ind = []          l = 0          if len(matches) > 0:              l = len(matches[0])              for m in matches:                  m_unique_ind = sorted([unique_ind_permutation[x] for x in m])                  matches_to_unique_ind += [m_unique_ind]          return matches_to_unique_ind, l        def eliminate_common_matches(matches):          for m in matches:              aux = matches.copy()              aux.remove(m)              for a in aux:                  common = (set(m) & set(a))                  if len(common) > 0:                      min_m = min(m)                      min_a = min(a)                      if min_m <= min_a:                          matches.remove(a)                      else:                          matches.remove(m)          return matches        def find_matched(unique_indexes, matches):          matched = []          unmatched = []          for unique_ind in unique_indexes:              for m in matches:                  if unique_ind in m:                      matched += [unique_ind]                  else:                      unmatched += [unique_ind]          return matched, unmatched        if matched is not None:          my_dict = update_my_dict(my_dict, matched)      unique_indexes = list(my_dict.keys())      p_unique_indexes = list(permutations(unique_indexes))      matches = []      last_l = 0      for p in p_unique_indexes:          m, l = get_matches(p, my_dict)          if last_l < l:              matches.clear()              last_l = l          if last_l == l and l > 0:              matches += m      matches = set(tuple(l) for l in matches)      matches_order = []      for m in matches:          mx = sorted([unique_indexes.index(unique_ind_x) for unique_ind_x in m])          matches_order += [mx]      matches_order = eliminate_common_matches(matches_order)      matches = []      for mo in matches_order:          mx = [unique_indexes[x] for x in mo]          matches += [mx]      matched, unmatched = find_matched(unique_indexes, matches)      return matches, matched, unmatched    my_dict = {1:[1, 2, 3, 4],             2:[2, 1, 4],             3:[3, 1],             4:[4, 1, 2]}       unique_indexes = list(my_dict.keys())  matches = []  matched = None  while True:      instance_matches, matched, unmatched = group_matches(my_dict, matched)      if len(instance_matches) > 0:          matches += instance_matches      if len(unmatched) == 0 or len(instance_matches) == 0:          break  unmatched = list(set(unique_indexes) - set(list(chain(*matches))))  matches_unique = []  for i, x in enumerate(matches):      if x not in matches[:i]:          matches_unique += [x]  matches = matches_unique + unmatched        print(matches)    

Another more complicated example:

  my_dict = {              'a':['a', 'b', 'c', 'h'],              'b':['b', 'a', 'c', 'i'],              'c':['c', 'a', 'b', 'd', 'e'],              'd':['d', 'c', 'e', 'f'],              'e':['e', 'c', 'd', 'f'],              'f':['f', 'd', 'e', 'g', 'h'],              'g':['g', 'f', 'h'],              'h':['h', 'a', 'f', 'g'],              'i':['i',  'c']            }  # expected outcome:  res = [['c', 'd', 'e'], ['f', 'g', 'h'], ['a', 'b'], ['i']]    

The subset ['d', 'e', 'f'] is not part of the expected outcome, because the 'd' and the 'e' are already taken by the first subset.

Autocurrency selector infinately refreshing page

Posted: 18 Jun 2021 09:13 AM PDT

I have a currency selector function that automatically detects the location of the user and updates the website's currency & the select location both on load and when the #currency_form is changed.

The problem is that when I run the code, the page infinately refreshes. How do I change my code so that the currency and selector is updated on load and if the user changes the selector value from the #currency_form?

Submitting the form refreshes the page and updates the currency / location. This needs to happen on load where mycurrency matches the location & when the select is changed since it will change the currencies that are displayed on the site.

window.addEventListener('DOMContentLoaded', function() {    (function($) {      $(document).ready(function() {        var currmap = {          "USD",          "GBP"        };        $.getJSON('//freegeoip.app/json/', function(location) {          if (location.country_code) {            var mycurrency = currmap[location.country_code];            if (mycurrency) {              $("#currency_form select").val(mycurrency);              $("#currency_form select").change();              $('#currency_form').submit();            }          }        });      });    })(jQuery);  });  $('#currency_form select').on('change', function() {    $('#currency_form').submit();  });  

Convert System.Drawing.Image to DlibDotNet Array2DBase

Posted: 18 Jun 2021 09:14 AM PDT

I am trying to identify the position (x,y) of lip, jaw from the photo using DlibDotNet NuGet package. How to set System.Drawing.Image to the Dlib fb.Operator()?

Here is my code:

using (Image image = Image.FromStream(HttpPostedFileBase_file.InputStream, true, false))  {      using (var fd = Dlib.GetFrontalFaceDetector())      {          //var img = Dlib.LoadImage<RgbPixel>();                                             var faces = fd.Operator(img);      }  }  

when I try to get address using geocoder, given a run time error of "Unhandled Exception: PlatformException(failed, Failed, null)"

Posted: 18 Jun 2021 09:14 AM PDT

I try to get the location using dart plugin of "geolocation and geocode" using. but the code gives an error of "Unhandled Exception: PlatformException(failed, Failed, null)". how do I overcome it?

import 'package:geolocator/geolocator.dart';  import 'package:geocoder/geocoder.dart';    Future<String> getCurrentLocation() async {    final location = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);    String latitude =(location.latitude).toString();    String longitude = (location.longitude).toString();    String _center = latitude + "," + longitude;    print(_center);    final coordinates = await new Coordinates(location.latitude, location.longitude);    var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);      var first = addresses.first;    print("${first.featureName} : ${first.addressLine}");    return _center;  }  

How to update existing model class generated by Scaffold-DbContext

Posted: 18 Jun 2021 09:13 AM PDT

Working with ASP.NET CORE EF, I have generated model classes from existing database with following command:

Scaffold-DbContext "Server=myserver\mydb;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  

Now my database is changed, for example I added a new column in a table AppUser. I don't want to use migrations to keep sync models with database.

I already made changes in database and now I want to update my existing model classes from current database state. Any suggestion how to do this?

Should I delete my existing model classes and regenerate by using the same command Scaffold-DbContext or do we have any other way make existing model classes to reflect new changes.

MongoDB atlas, connection not working

Posted: 18 Jun 2021 09:13 AM PDT

I just created a free MongoDB atlas cluster instance. But somehow I am failing to connect it from my application as well as from the MongoDB Compas.

I get below error when I try to run my application.

Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=experimental-1-epdri.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: experimental-1-epdri.mongodb.net}, caused by {java.net.UnknownHostException: experimental-1-epdri.mongodb.net}}]      at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:377) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:104) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:411) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.operation.CreateIndexesOperation.execute(CreateIndexesOperation.java:144) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.operation.CreateIndexesOperation.execute(CreateIndexesOperation.java:71) ~[mongodb-driver-core-3.4.2.jar:na]      at com.mongodb.Mongo.execute(Mongo.java:845) ~[mongodb-driver-3.4.2.jar:na]      at com.mongodb.Mongo$2.execute(Mongo.java:828) ~[mongodb-driver-3.4.2.jar:na]      at com.mongodb.MongoCollectionImpl.createIndexes(MongoCollectionImpl.java:491) ~[mongodb-driver-3.4.2.jar:na]      at com.mongodb.MongoCollectionImpl.createIndex(MongoCollectionImpl.java:458) ~[mongodb-driver-3.4.2.jar:na]      at org.axonframework.mongo.eventsourcing.eventstore.AbstractMongoEventStorageStrategy.ensureIndexes(AbstractMongoEventStorageStrategy.java:201) ~[axon-mongo-3.0.5.jar:3.0.5]      at org.axonframework.mongo.eventsourcing.eventstore.MongoEventStorageEngine.ensureIndexes(MongoEventStorageEngine.java:123) ~[axon-mongo-3.0.5.jar:3.0.5]      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]      at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]      at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]      at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]      at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]      ... 76 common frames omitted      Process finished with exit code 1  

On Compas it simply says MongoDB instance isn't running at this place. I have checked my cluster and I see below.

Seems like it is up..

But still I can't connect to mongo cluster. Further more I tried with `Mongo CLI as well where I found error as shown below. Error while connecting using CLI.

Below is the connection string that I get from the MongoDB atlas page.

mongodb+srv://admin_eventdb:<PASSWORD>@experimental-1-epdri.mongodb.net/test?retryWrites=true

Please help solve this.

How to return a reference to a sub-value of a value that is under a mutex?

Posted: 18 Jun 2021 09:13 AM PDT

I have a structure that looks somewhat like this:

pub struct MyStruct {      data: Arc<Mutex<HashMap<i32, Vec<i32>>>>,  }  

I can easily get a lock on the mutex and query the underlying HashMap:

let d = s.data.lock().unwrap();  let v = d.get(&1).unwrap();  println!("{:?}", v);  

Now I want to make a method to encapsulate the querying, so I write something like this:

impl MyStruct {      pub fn get_data_for(&self, i: &i32) -> &Vec<i32> {          let d = self.data.lock().unwrap();          d.get(i).unwrap()      }  }  

This fails to compile because I'm trying to return a reference to the data under a Mutex:

error: `d` does not live long enough    --> <anon>:30:9     |  30 |         d.get(i).unwrap()     |         ^     |  note: reference must be valid for the anonymous lifetime #1 defined on the block at 28:53...    --> <anon>:28:54     |  28 |     pub fn get_data_for(&self, i: &i32) -> &Vec<i32> {     |                                                      ^  note: ...but borrowed value is only valid for the block suffix following statement 0 at 29:42    --> <anon>:29:43     |  29 |         let d = self.data.lock().unwrap();     |                                           ^  

I can fix it by wrapping the HashMap values in an Arc, but it looks ugly (Arc in Arc) and complicates the code:

pub struct MyStruct {      data: Arc<Mutex<HashMap<i32, Arc<Vec<i32>>>>>,  }  

What is the best way to approach this? Is it possible to make a method that does what I want, without modifying the data structure?

Full example code.

How to properly function annotate / type hint a list of strings

Posted: 18 Jun 2021 09:14 AM PDT

I am trying to figure out how to properly function annotate or type hint a list of strings. For example, if I had a function like this:

def send_email(self, from_address: str, to_addresses: list[str]):      pass  

to_addresses should be a list of strings. But when I try to use that annotation I get the following error in my Python 3.4.3 interpreter:

TypeError: 'type' object is not subscriptable

I am positive the list[str] is causing the issue, because if I change it to str the error goes away, but that doesn't properly reflect my intentions for the parameter.

No comments:

Post a Comment