Friday, October 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Screen Splitter not working for Arabic right to left Alignment

Posted: 01 Oct 2021 08:32 AM PDT

I am using a splitter.js library for splitting the screen in 2. I have to reverse the screen for Right To Left(RTL) alignment. But when I do that using transformScaleX(-1) property, the Splitter's behavior reverses If I drag it left, it goes right and If I drag it right, it goes left. JQuery has been used heavily to integrate the Splitter in the code. Also the Splitter does not recognise the MouseUp event so that code can be executed after it has been dragged. How should I approach the problem? https://jquery.jcubic.pl/splitter.php This is a demo of the library I am using In this demo, if I transform it, I face the same issue.

Compile error adding CameraX dependency in Build Gradle

Posted: 01 Oct 2021 08:32 AM PDT

I am trying to add CameraX dependency in the App Gradle but I am getting build errors and I'm not sure why. I have tried commenting out the app's dependencies one by one but still have had no luck.

has anyone ever ran across this build error: "A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction"

Gradle Screenshot 1

Gradle Screenshot 2

Gradle 3

Gradle 4

Error screenshot 1

Error screenshot 2

How can an object reference in java hold the reference to a primitive double dimensional int array

Posted: 01 Oct 2021 08:32 AM PDT

I have a piece of code-

public class Sudoku {      static int[][] game;        public static void main(String[] args) {          int [][] games= new int[3][3];          Object obj =games;      }    }  

My question here is how can the "games" reference variable be assigned to the reference variable of type "Object"? I thought the "ClassCastException" would be thrown at runtime. But the code compiles and runs fine. Isnt the reference variable "games" incompatible to be assigned to an Object reference because of 2 reasons- 1)"games" is the reference to a double dimensional int array, whereas "obj" is the reference to an Object. 2)int is clearly a primitive variable..how can it be assigned to a variable of type object? I am running this in the Intellij IDE. I am a bit new to Java and trying to understand the nuances. If you want to downvote please let me know as to why you are downvoting so that I dont repeat the same mistake in this forum.

Name matching in sql

Posted: 01 Oct 2021 08:32 AM PDT

How can I implement name matching function in sql? I searched online, but I found them using T-Sql for name matching. I want to implement name matching in sql, so that I pass two strings to that function and get matching score in return.

Question Related to private docker repository

Posted: 01 Oct 2021 08:32 AM PDT

Please help me on my doubt

when we are pushing the docker image to the private docker repository using the jenkins for example docker hub then the image will also pack the war artficat that is build by jenkins?

for example suppose that we have pushed the 3 docker image having 1/2/3 version and when I roll back to 1st version then it will contain that war file for that 1st version ?

please help me if im correct or not

Save uploaded picture to static/pictures in spring boot

Posted: 01 Oct 2021 08:32 AM PDT

I am trying to upload a picture to my spring boot application, placing it in static/pictures so that the thymeleaf html page can read the picture. But I am unable to find out how to specify the path to that folder.

There is no problem saving the file to System.getProperty("user.dir");

//working  private String userDirectory = System.getProperty("user.dir");  //Not working  private String userDirectory = "/static/pictures";  @PostMapping("/upload")  public String singleFileUpload(@RequestParam("file") MultipartFile file,                                 RedirectAttributes redirectAttributes) {  

I would like the upload path to point to /static/pictures but will always get java.nio.file.NoSuchFileException no matter how I define the path.

        // Get the file and save it somewhere          byte[] bytes = file.getBytes();          Path path = Paths.get( uploadPath + file.getOriginalFilename());          Files.write(path, bytes);            redirectAttributes.addFlashAttribute("message",                  "You successfully uploaded '" + file.getOriginalFilename() + "'");        } catch (IOException e) {          e.printStackTrace();      }        //return "redirect:/uploadStatus";      return "index";  }  

I have also tried setting upload.path in the properties file.

upload.path=/META-INF/resources/static/pictures/  

When i try to make a http request it shows up as a connection error whereas before it didn't show up as a connection error

Posted: 01 Oct 2021 08:32 AM PDT

import json  import requests    country = 'GB'  url = ('http://kitkabackend.eastus.cloudapp.azure.com:5010/highscore/crowns/list?country='+country)    r = requests.get(url)  print(r.text)  

The same code was working for me for a while before but now it suddenly gives me an error like before. I've tried adding headers when requesting but that also didn't fix the error.(im a beginner using repl.it)

error shown on console - raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response

Postgres: inserting as many rows as a value on another table

Posted: 01 Oct 2021 08:31 AM PDT

I'm trying to implement a ticket service of sorts, where each user has a certain ammount of tickets assigned to them. I have one table, users, that stores the name of the user and the ammount of tickets that will be asigned to them. But i have another table, tickets, that should have an entry for each ticket available with a foreign key that references its owner from the table users. So, for example, if my table users contains:

User_id Name Quantity
1 Ana 3
2 Mark 4

I would like to have in my tickets table:

ticket_id user_id
1 1
2 1
3 1
4 2
5 2
6 2
7 2

Where ticket_id is serial.

Is there a easy way to insert as many rows as the quantity indicates in users? I dont want to insert them all by hand...

Grails opens a new window but I am unable to specify the window size. How do I use G:actionSubmit to open a smaller window?

Posted: 01 Oct 2021 08:31 AM PDT

I am using Grails and I'm trying to pop up a new window which is smaller that the window I am in, so I've tried this which works, except the new window is full size.

<g:form controller="myController">          <g:actionSubmit value="View the New Page" action="index" formtarget="_blank" params="width=200, height=500"/>   </g:form>  

How can I make the new window smaller? The params bit in my code doesn't seem to do much to help.

Using group_by for only certain attributes

Posted: 01 Oct 2021 08:31 AM PDT

I have an array roads of objects that have many attributes. What I would like to do is find which district_code (one attribute) has more than one state (another attribute)

Ommitting the other attributes for simplicity - eg:

roads = [['1004', 'VIC'], ['1004', 'BRI'], ['1011', 'VIC'], ['1010', 'ACT'], ['1000', 'ACT'], ['1019', 'VIC'], ['1004', 'VIC']]  

If I was to use roads.group_by { |ro| ro[0] } I get the result:

=> {"1004"=>[["1004", "VIC"], ["1004", "BRI"], ["1004", "VIC"]], "1011"=>[["1011", "VIC"]], "1010"=>[["1010", "ACT"]], "1000"=>[["1000", "ACT"]], "1019"=>[["1019", "VIC"]]}

What I want is the hash to only show where there has been more than one unique value for state, like so:

=> {"1004"=>["VIC", "BRI"]}  

Any ideas on how to group_by or map by the number of values / or for a specific attribute within a value?

Thanks!

How do you selectively inline an SVG in CSS with Webpack 5?

Posted: 01 Oct 2021 08:31 AM PDT

I'm compiling my SCSS to CSS using Webpack 5. I want to selectively inline some of the SVGs. Ideally, I'd like to achieve this either by file name, path, or some query parameter in its URL.

Say I have the following SCSS:

/* src/scss/main.scss */  .logo {      background-image: url('/images/logo.svg');  }  

And this webpack.config.js:

const path = require('path');    const MiniCssExtractPlugin = require('mini-css-extract-plugin');    const src_dir = path.resolve(__dirname, "src");    module.exports = {      entry: {          "styles": path.resolve(__dirname, "src/scss/main.scss")      },      output: {          clean: true,          path: path.resolve(__dirname, "dist"),          publicPath: "",      },      module: {          rules: [ ... ]      },      plugins: [          // Extract the generated CSS from the JS-CSS into actual CSS.          new MiniCssExtractPlugin({              filename: "[name].[contenthash].css"          }),      ]  }  

This is my rule compiling SCSS to CSS if it's relevant:

{      test: /\.scss$/,      use: [          // Extract the generated CSS from the JS-CSS into actual CSS.          {              loader: MiniCssExtractPlugin.loader,              options: {                  esModule: false,              }          },          {              loader: 'css-loader',          },          // Compile SCSS to JS-CSS.          {              loader: 'sass-loader',              options: {                  sassOptions: {},                  sourceMap: true              }          }      ]  },  

This is my current asset rule:

{      test: /\.(jpg|png|svg)$/,      type: "asset/resource",      generator: {          // Do not copy the asset to the output directory.          emit: false,          // Rewrite asset filesystem path to be relative to the asset public path.          filename: (pathData) => {              const file = pathData.module.resource;              if (file.startsWith(`${src_dir}/`)) {                  return path.relative(src_dir, file);              }              throw new Error(`Unexpected asset path: ${file}`);          },          // The public path (prefix) for assets.          publicPath: "/a/",      }  }  

How do I configure a new rule to inline only logo.svg? From what I gather, I need something along the lines of:

{      test: /\.svg$/,      type: "asset/inline",      // ... some unknown webpack-foo.  },  

But what do I do from here? The webpack documentation is sorely lacking in any useful examples for CSS. This isn't some JavaScript aplication where every asset is imported using require(). I'm only using SCSS/CSS.

how to get top N latest created pods inside kubernetes based on filter

Posted: 01 Oct 2021 08:31 AM PDT

In kubernetes, using filter we can limit the output from k8s on interesting resource, and I wonder whether it is possible to list top 5 latest created pods using only filter.

The current example mostly list all pods and pipe to another unix (head command)

kubectl get pods --sort-by=.metadata.creationTimestamp | head -n 5  

But I guess it takes the quite long time to get all first from server side, then list first 5.

Can I use special filter will make it more efficiency?

What are the differences and characteristics of the symbol table of C language and Java language

Posted: 01 Oct 2021 08:31 AM PDT

I would like to know the differences and characteristics of symbol tables of C and Java languages, and how they handle the arguments of functions respectively.

Storing reading data stored in EV3 with micro python

Posted: 01 Oct 2021 08:32 AM PDT

I'm programming my EV3 to save information such as distance using datalog() and it stores it in the EV3 as a csv file, this I have no problem with.

The problem is I tried to read it using the following code:

with open('straight_line.csv''r') as my_file  Data = my_file.read()  

And got a syntax error I don't know what is though, so then I tried doing it this way

my_file = open('straight_line.csv','r')  Data = my_file.read()   

And got the following error:

OSError: [ Errno 2] ENOENT  

Anyone knows how I can fix this?

JS dynamically created SVG not working/animating in IOS

Posted: 01 Oct 2021 08:31 AM PDT

I have this code working perfectly on windows and android in chrome, edge and FF but broken results on ipad in FF, edge, chrome and safari. Basically no animation or sign of this instance on IOS.

    var height = document.documentElement.clientHeight;      var width = document.documentElement.clientWidth;        //DYNAMICALLY CREATE SVG POLYGON        const bgSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');      const bgPoly = document.createElementNS('http://www.w3.org/2000/svg','polygon');      const animate = document.createElementNS('http://www.w3.org/2000/svg','animate');        bgSvg.setAttribute('class', 'mobiNav_Poly_Close');      bgSvg.setAttribute('width', `${width}`);      bgSvg.setAttribute('height', `${height}`);      bgSvg.setAttribute('fill', 'white');      bgSvg.setAttribute('viewBox', `0 0 ${width} ${height}`);      bgPoly.setAttribute('class', 'Poly_Close');      bgPoly.setAttribute('points', `0,${height} ${width},${height} 0,0 ${width},0`);      animate.setAttribute('attributeName','points');       animate.setAttribute('dur','0.5s');      animate.setAttribute('keyTimes', '0 ; 1');      animate.setAttribute('keySplines', '.67,.01,.16,1');      animate.setAttribute('calcMode', 'spline');      animate.setAttribute('fill','freeze');      animate.setAttribute('from',`${width},${height}, 0,${height}, 0,0 ${width},0`);      animate.setAttribute('to',`${width},${height}, ${width},0, 0,0 ${width},0`);        bgSvg.appendChild(bgPoly);      bgPoly.appendChild(animate);      document.querySelector('.mobiNav_overlay').appendChild(bgSvg);   

In another function I have a close state on a click event where this svg element is removed and replaced by essentially the same thing with new points and to/from in reverse. I get what appears to be a flash of garbage (mixed up/transposed points) and no animation. I only have an iPad to test on and so debugging has been tricky to say the least. I've outputted to innerHTML these attributes and all appears normal.

Why wont the MOD_SHIFT event key work in PYGAME Mac

Posted: 01 Oct 2021 08:31 AM PDT

I'm trying to build a little python program using pygame that detects when the shift key is pressed but it isn't working it isn't printing the debug print that I put in there here is my code

while running:      screen.fill((0, 0, 0))      x, y = pygame.mouse.get_pos()      for event in pygame.event.get():          if event.type == pygame.QUIT:              running = False          if event.type == pygame.MOUSEBUTTONDOWN:              rectangle = "green"          if event.type == pygame.MOUSEBUTTONUP:              rectangle = "red"          if event.type == pygame.KEYDOWN:              if event.key == pygame.KMOD_SHIFT:                  modshift = "down"                  print("debug shift")              if event.key == pygame.KMOD_CTRL:                  modctrl = "down"          if event.type == pygame.KEYUP:              if event.key == pygame.KMOD_SHIFT:                  modshift = "up"  

How can I replace specific words inside a paragraph with links? [duplicate]

Posted: 01 Oct 2021 08:32 AM PDT

I'm trying to replace specific words in an HTML page with the same word but as a URL (linking each to a different resource). I have an array of the words which should be turned into urls. For example this:

var words = ["Build The Earth", "PippenFTS", "Earth"]  <p>Build The Earth was created by YouTuber PippenFTS in March 2020 as a collaborative effort to recreate Earth in the video game Minecraft.</p>  

Should become:

<p><a href="xxx.yyy/buildtheearth">Build The Earth</a> was created by YouTuber <a href="xxx.yyy/pippenfts">PippenFTS</a> in March 2020 as a collaborative effort to recreate <a href="xxx.yyy/earth">Earth</a> in the video game Minecraft.</p>  

Is there a way to do this? I tried with text.replace() in a for cycle, but as the cycle goes on each of the words already turned into a link goes back to being just plain text.

I tried so hard for days but I just can't wrap my mind around this.

Each help would be very much appreciated! Thank you :)

EDIT: sorry, I didn't post what I tried. Here were some attempts, by creating and appending my link after splitting the paragraph (but it affected the other urls):

var paragraphSplit = paragraphs[j].innerHTML.split(words_to_replace[i]);      console.log(paragraphSplit[0]);      console.log(paragraphSplit[1]);      paragraphs[j].appendChild(link);  

By using an other user's answer to this question, but it only worked for one word in each paragraph, while I should replace multiple words.

How does this line of code negate a std::uint64_t value?

Posted: 01 Oct 2021 08:32 AM PDT

I'm trying to understand what this code does. This is supposed to negate the coefficient coeff of type uint64_t* of a polynomial with coefficients modulus modulus_value of type const uint64_t:

std::int64_t non_zero = (*coeff != 0);  *coeff = (modulus_value - *coeff) & static_cast<std::uint64_t>(-non_zero);  

What's up with the & static_cast<std::uint64_t>(-non_zero)? How does this negate anything?

The code is from here.

Getting PK from another table that isn't user - Django REST framework

Posted: 01 Oct 2021 08:32 AM PDT

I need help with the following problem please. I've managed to connect a user's id to another table, but I can't seem to replicate the same process when connecting a table to another's primary key. What am I doing wrong?

MODEL

Parent model

class TestDataTwo(models.Model):  user = models.OneToOneField("auth.User", related_name="testdatatwo", on_delete=models.CASCADE)  test_name = models.CharField(max_length=1024, null=True, default="N/A")  

Child model

class TestDataThree(models.Model):  user = models.OneToOneField("auth.User", related_name="testdatathree", on_delete=models.CASCADE)  sdgdata = models.OneToOneField(TestDataTwo, related_name="testdatatwo", on_delete=models.CASCADE, default=-1)  test_name_again = models.CharField(max_length=1024, null=True, default="N/A")  

SERIALIZER

Parent serializer

class TestDataTwoSerializer(serializers.ModelSerializer):  class Meta:      model = TestDataTwo      fields = (          "id",          "user_id",          "test_name",      )  

Child serializer

class TestDataThreeSerializer(serializers.ModelSerializer):  class Meta:      model = TestDataThree      fields = (          "id",          "user_id",          "test_name_again",      )  

VIEW

Parent serializer

class TestDataTwoViewSet(ModelViewSet):  queryset = TestDataTwo.objects.all().order_by('id')  serializer_class = TestDataTwoSerializer  paginator = None    # CREATE NEW TESTDATATWO ROW FOR USER  def perform_create(self, serializer):      serializer.save(user=self.request.user)    # GET ALL ENTRIES OF TESTDATATWO FOR SPECIFIC USER, EXCEPT IF SUPERUSER, THEN RETURN ALL  def get_queryset(self):      # if self.request.user.is_superuser:      #     return self.queryset      # else:      return self.queryset.filter(user=self.request.user)    # PUT/PATCH  def perform_update(self, serializer):      serializer.save(user=self.request.user)      return Response(serializer.data, status=status.HTTP_200_OK)    # DELETE TESTDATATWO ID  def destroy(self, request, *args, **kwargs):      instance = self.get_object()      self.perform_destroy(instance)      return Response(status=status.HTTP_204_NO_CONTENT)  

Child serializer

class TestDataThreeViewSet(ModelViewSet):  queryset = TestDataThree.objects.all().order_by('id')  serializer_class = TestDataThreeSerializer  paginator = None    # CREATE NEW TESTDATATHREE ROW FOR USER  def perform_create(self, serializer):      serializer.save(user=self.request.user)    # GET ALL ENTRIES OF TESTDATATHREE FOR SPECIFIC USER, EXCEPT IF SUPERUSER (THEN RETURN ALL INSTEAD)  def get_queryset(self):      # if self.request.user.is_superuser:      #     return self.queryset      # else:      return self.queryset.filter(user=self.request.user)    # DELETE TESTDATATHREE ID  def destroy(self, request, *args, **kwargs):      instance = self.get_object()      self.perform_destroy(instance)      return Response("Deleted Successfully", status=status.HTTP_204_NO_CONTENT)  

I am guessing I need to change something in the views class, but not sure what. Appreciate any help here.

Example of output in Postman:

enter image description here

enter image description here

Passing variable from module to user form

Posted: 01 Oct 2021 08:32 AM PDT

I've searched a lot of pages and don't have a clear answer to this.

I have VBA code which does a lot of processing of Word revisions and I'd like to display a userform to inform the user of what's happening.

I track two variables (TotalRevisionCount and RevisionIndex) which count the total number of revisions being processed, and the individual revision number respectively. I've declared these as public variables in my main module.

I'd like my userform to display "Processing revision 2 of 36". I think the code to do this is really simple but I just can't join the dots.

Help?

***UPDATE This is a cut down version of the calling code:

Sub TestSub()  updateTotal = 10000    PlsWaitForm.Show (False)    For i = 1 To 10000      UpdateNum = i      PlsWaitForm.Repaint  Next i  Unload PlsWaitForm    End Sub  

...and this is what I have in my userform:

Sub DisplayStuff()      PlsWaitText.Caption = "Currently processing " & UpdateNum & " of " UpdateTotal & " records."  End Sub  

How do I add cookie value in order metadata without using plugin in wordpress?

Posted: 01 Oct 2021 08:31 AM PDT

I want the value of cookie 'my_cookie' in order metadata.

add_action('init','thankyou_grab_cookie_as_meta_data', 10, 1 );  function thankyou_grab_cookie_as_meta_data( $order_id ){      if( ! $order_id ){          return; }      if(isset($_COOKIE["my_cookie"]) && ! get_post_meta( $order_id, 'some default value', true ) ){          update_post_meta( $order_id, 'some default value',  esc_attr($_COOKIE["my_cookie"]) );      }  }  [The metadata shown now in postman][1]        [1]: https://i.stack.imgur.com/ix3w5.png  

why quantile(0.5) and median output different result when I use groupby?

Posted: 01 Oct 2021 08:31 AM PDT

I use groupby function and followed by median, but the result is different when I change median to quantile(0.5) why?

df.groupby(['PUMA', 'R65'])['HINCP'].quantile(0.5)    df.groupby(['PUMA', 'R65'])['HINCP'].median()  

The above should be the same right?

check the screenshot

FYI. The dataset is here: https://github.com/kihyukh/stats206/raw/master/data/pums_short.csv.gz

And my pandas version is 1.0.1

Allowing CORS for api.glossgenius.com

Posted: 01 Oct 2021 08:31 AM PDT

I need assistance, i am unsure how to make the API response from "api.glossgenius.com" work properly to get elements of the site working.

https://studio21md.com/portfolio

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.glossgenius.com/v3/web/portfolio_images?slug=meganhammett. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.glossgenius.com/v3/web/portfolio_images?slug=meganhammett. (Reason: CORS request did not succeed).

Can anyone assist on Nginx how i would solve this specific issue?

Here is my config, Thank you for your assistance.

 server {      listen       80;      server_name  www.studio21md.com studio21md.com;      #charset koi8-r;      #access_log  logs/host.access.log  main;        location / {          proxy_pass   https://meganhammett.glossgenius.com;  }  

Loading a local file in a remote Lisp with swank/slime

Posted: 01 Oct 2021 08:31 AM PDT

Say that I am connected to a remote Lisp using swank/slime. I have a data file on my local machine on disk or, perhaps, in an emacs buffer. I want to process this file using the remote Lisp.

I can obviously drop out to a shell and scp the file to the server, load the file, process it, close, delete the file so that I don't make a mess on the server.

I can also paste the file into the repl:

> (defparameter *my-file* "[paste file here]")  

But this is nasty if the text has quotes in it or the file is binary.

Both options are cumbersome.

Is there a nice way to get the local emacs to tunnel a file to the remote Lisp so that the remote Lisp can open it as a stream?

I'm picturing something like:

> (swank:with-open-client-file (s #p"/path/to/local/file") ... )  

Edit: This example feels like it could open some holes in my local file system. Could it be done without causing serious security problems?

How to vectorize a 2 level loop in NumPy

Posted: 01 Oct 2021 08:31 AM PDT

Based on the comments, I have revised the example:

Consider the following code

import numpy as np    def subspace_angle(A, B):      M = A.T @ B      s = np.linalg.svd(M, compute_uv=False)      return s[0]    def principal_angles(bases):          k = bases.shape[0]      r = np.zeros((k, k))      for i in range(k):          x = bases[i]          r[i, i] = subspace_angle(x, x)          for j in range(i):              y = bases[j]              r[i, j] = subspace_angle(x, y)              r[j, i] = r[i, j]      r = np.minimum(1, r)      return np.rad2deg(np.arccos(r))  

Following is an example use:

bases = []  # number of subspaces  k = 5  # ambient dimension  n = 8  # subspace dimension  m = 4  for i in range(5):      X = np.random.randn(n, m)      Q,R = np.linalg.qr(X)      bases.append(Q)  # combine the orthonormal bases for all the subspaces  bases = np.array(bases)  # Compute the smallest principal angles between each pair of subspaces.  print(np.round(principal_angles(bases), 2))  

Is there a way to avoid the two-level for loops in the principal_angles function, so that the code could be sped up? As a result of this code, the matrix r is symmetric. Since subspace_angle could be compute-heavy depending on the array size, it is important to avoid computing it twice for r[i,j] and r[j,i].

On the comment about JIT, actually, I am writing the code with Google/JAX. The two-level loop does get JIT compiled giving performance benefits. However, the JIT compilation time is pretty high (possibly due to two levels of for-loop). I am wondering if there is a better way to write this code so that it may compile faster.

No Activity found to handle Intent whien trying to open word file or excel file

Posted: 01 Oct 2021 08:31 AM PDT

"here i want to open file "

val intent = Intent()  intent.action = Intent.ACTION_VIEW  intent.setDataAndType(Uri.parse(docList[position]?.image), docList[position]?.contentType)  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)  startActivity(holder.itemView.context, intent, null)  

Django Admin: two ListFilter Spanning multi-valued relationships

Posted: 01 Oct 2021 08:32 AM PDT

I have a Blog model and an Entry model, following the example in django's documentation.

Entry has a ForeignKey to Blog: one Blog has several Entries.

I have two FieldListFilters for Blog: one for "Entry title", one for "Entry published year".

If in the admin I filter for both entry__title='Lennon' and entry__published_year=2008, then I see all Blogs which have at least one entry with title "Lennon" and at least one entry from 2008. They do not have to be the same entry.

However, that's not what I want. What I want is to filter blogs which have entries that have both got the title "Lennon" and are from 2008.

So for example say I have this data:

Blog Entry Title Entry year
A McCartney 2008
A Lennon 2009
B Lennon 2008

The admin list page for Blog currently filters in Blog A, because it has one entry from 2008 and one entry for "Lennon", as well as Blog B. I only want to see Blog B.

This is because django does this when it builds the queryset:

qs = qs.filter(title_filter)  qs = qs.filter(published_filter)  

As per the docs, to get the desired result it would need to do make just one filter call:

qs = qs.filter(title_filter & published_filter)  

How can I achieve this behaviour with filtering in the admin?

Why is it that I cannot see the remote branches of a git repository after a shallow clone? [duplicate]

Posted: 01 Oct 2021 08:31 AM PDT

I have a remote repository that I have to clone at depth 1 using git clone --depth 1 [url] and then use git fetch --unshallow and git fetch --all to get the full repository.

The problem is that I can only see branches that I have created locally. I cannot see any remote branches unless I created them locally and pushed them to the remote server. This means that if anything happens to my local repo, I will have to start work on any remote branches all over again.

Edit: This question is answered elsewhere, but I am leaving it up because it asks the question in a different way, making the solution more searchable.

How do I resolve this issue?

How to create a Flipbook in Houdini using only the Python source editor?

Posted: 01 Oct 2021 08:32 AM PDT

I have a scene created in Houdini and I want to save that as a flipbook to a file location (my desktop for example) using only Python scripting in the python shell/source editor. I have read the sidefx website on creating a flipbook here, but I couldn't figure it out, specifically, I don't know what scene is referring to in that example. Here is what I have written in my source editor. When I call the function, Houdini just shuts down and I don't know why.

# create flipbook  fbsettings = toolutils.sceneViewer().flipbookSettings().stash()  fbsettings.output('$JOB/Desktop/test.avi')  fbsettings.outputToMPlay(0)  # Launch the flipbook  toolutils.sceneViewer().flipbook(viewport=None, settings=fbsettings, open_dialog=False)  

opencv4nodejs how to calculate the blur degree with variance of laplacian

Posted: 01 Oct 2021 08:32 AM PDT

I have a code:

const cv = require('opencv4nodejs');    let text = "";    let image = cv.imread('./images/focused.jpg');  let gray = image.cvtColor(cv.COLOR_BGR2GRAY);  let fm = image.laplacian(cv.CV_64F);  cv.imwrite('./images/new_very_blured.jpg', gray);    console.log(image);  console.log(fm);  console.log(fm.step / image.step);

And picture, which i saved is the black square, but its isn't what i expected. I read an article about calculating the blur degrees and there:

cv2.Laplacian(image, cv2.CV_64F).var() // Python function  

This article - https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/

But i using nodejs and in nodejs this function isn't exists, so i try to use other function, but it work doesn't as in Python. Please help me, how i need to edit my code to do it works. In the console i need to get a percent from 1 to 100, which will show me the blur degree.

No comments:

Post a Comment