how to Reduce number of queries generated by Django ORM [closed]

I have below models

class Order(models.Model):    ....  class Component(models.Model):      line = models.ForeignKey(         Line,         on_delete=models.CASCADE,         blank=True,         null=True,         related_name="components",     )   ...  class Detail(models.Model):     line = models.ForeignKey(         "Line",         on_delete=models.CASCADE,         blank=True,         null=True,         related_name="details",     )   order= models.ForeignKey(Order, on_delete=models.CASCADE, related_name="details")    .....  class Line(models.Model):  ....  **Serializer** class ComponentSerializer(serializers.ModelSerializer):     qty = serializers.SerializerMethodField(read_only=True)      def get_qty(self,component):         return (component.qty)-sum(                map(                    some_calculation,                    Detail.objects.filter(                        line__components=component,order__active=True)                )            ) 

I have a list view using model viewsets

def list(self, request):  queryset = Order.objects.filter(order__user=request.user.id,active=True)   serilizer = OrderSerializer(queryset,many=true) 

The component serializer is used inside the order serializer. My question is the query inside the ComponentSerializer hits DB fpr every order record. If my understanding is correct, is there any way to reduce this?

How we fit our own generated probability distribution on real data

I want to fit derived distribution on real data and I need MLE parameters, standard errors of the estimated parameters, AIC, Loglikelihood, Goodness of fit test (Chi-square, Anderson etc), PDF, CDF, Plots and QQplots. The data,CDF and PDF are

data = {3.70, 2.74, 2.73, 2.50, 3.60, 3.11, 3.27, 2.87, 1.47, 3.11,     4.42, 2.41, 3.19, 3.22, 1.69, 3.28, 3.09, 1.87, 3.15, 4.90, 3.75,     2.43, 2.95, 2.97, 3.39, 2.96, 2.53, 2.67, 2.93, 3.22, 3.39, 2.81,     4.20, 3.33, 2.55, 3.31, 3.31, 2.85, 2.56, 3.56, 3.15, 2.35, 2.55,     2.59, 2.38, 2.81, 2.77, 2.17, 2.83, 1.92, 1.41, 3.68, 2.97, 1.36,     0.98, 2.76, 4.91, 3.68, 1.84, 1.59, 3.19, 1.57, 0.81, 5.56, 1.73,     1.59, 2.00, 1.22, 1.12, 1.71, 2.17, 1.17, 5.08, 2.48, 1.18, 3.51,     2.17, 1.69, 1.25, 4.38, 1.84, 0.39, 3.68, 2.48, 0.85, 1.61, 2.79,     4.70, 2.03, 1.80, 1.57, 1.08, 2.03, 1.61, 2.12, 1.89, 2.88, 2.82,     2.05, 3.65}; cdf = (1 - (1 + ((1 - (1 + x^\[Xi])^-\[Psi] )^\[Lambda]/(1 - (1 - (1 + x^\[Xi])^-\[Psi] )^\[Lambda]))^[Gamma])^-\[Alpha])^(\[Beta]) \[ScriptCapitalD] = ProbabilityDistribution[-((\[Alpha] \[Beta] \[Gamma] \[Lambda] \[Xi] \[Psi] x^(-1 + \[Xi]) (-1 + 1/(1 - (1 - (1 + x^\[Xi])^-\[Psi])^\[Lambda]))^\[Gamma] (1 - (1 + (-1 + 1/(1 - (1 - (1 + x^\[Xi])^-\[Psi])^\[Lambda]))^\[Gamma])^-\[Alpha])^\[Beta])/((1 + x^\[Xi]) (-1 + (1 + x^\[Xi])^\[Psi]) (-1 + (1 - (1 + x^\[Xi])^-\[Psi])^\[Lambda]) (1 + (-1 + 1/(1 - (1 - (1 + x^\[Xi])^-\[Psi])^\[Lambda]))^\[Gamma]) (-1 + (1 + \(-1 + 1/(1 - (1 - (1 + x^\[Xi])^-\[Psi])^\[Lambda]))^\[Gamma])^\[Alpha])))\, {x, 0, Infinity} , Assumptions -> \[Alpha] > 0 && \[Beta] > 0 && \[Gamma] > 0 && \[Lambda] > 0 && \[Psi] > 0 && \[Xi] > 0  ]; 

How do Baldur’s Gate and Baldur’s Gate 2’s “rolling” for stats actually get generated? [closed]

When I have played BG1 & BG2, a big part of the character creation is rolling (and rerolling) for stats. This rolling for stats is subjected to racial minimums and maximums (and class minimums iirc).

The result of the rolling mechanism is a number of points allocated to specific scores, but you can reassign them in a simple 1-1 fashion between stats, subject to the relevant minimums and maximums.

How, though, are the stats generated? Is it in line with AD&D 2nd edition rules? Or have they come up with their own rolling mechanism for the game, and if so what is that rolling mechanism?

The reason behind the question is that I am interested in developing a similar stats generation system for D&D 5e tabletop games I run, but wanted to get a baseline for the “canonicity” of this generation system in relation to AD&D 2e rules first.

I have no Idea how to calculate the faces for my programily generated mesh

So I am making a programily generating cave program and I have all the vertices but I have no idea how to solve for the faces of my mesh. My code:

using System.Collections; using System.Collections.Generic; using UnityEngine;  public class MapGen : MonoBehaviour {     Mesh mesh;      int[] triangles;      public int xSize = 20;     public int zSize = 20;     public int ySize = 20;     [Range(0f, 4.5f)]     public float SurfaceLevel = 3.5f;     Vector3[] interest;     Vector3 old = new Vector3(0, 0, 0);     public bool ShowAlg = false;     [Header("Slows down the scene veiw dramaticly when in play mode!")]     public bool ShowVert = true;      // Start is called before the first frame update     void Start()     {         mesh = new Mesh();         GetComponent<MeshFilter>().mesh = mesh;          CreateShape();         SolveFaces();         UpdateMesh();     }     void CreateShape()     {         interest = new Vector3[(xSize + 1) * (zSize + 1) * (ySize + 1)];          float seed = Random.Range(0.2f, 0.5f);         Debug.Log(seed);          for (int x = 0; x <= ySize; x++)         {             for (int i = 0, y = 0; y <= zSize; y++)             {                 for (int z = 0; z <= xSize; z++)                 {                     float ypn = (Mathf.PerlinNoise(x * seed, z * seed) * 2f);                     float xpn = (Mathf.PerlinNoise(y * seed, z * seed) * 2f);                     float zpn = (Mathf.PerlinNoise(x * seed, y * seed) * 2f);                      if (ypn + xpn + zpn >= SurfaceLevel)                     {                         interest[i] = new Vector3(x, y, z);                     }                      i++;                 }             }         }     }      void SolveFaces()     {         triangles = new int[xSize * ySize * zSize * 9];      }     void UpdateMesh()     {         mesh.Clear();          mesh.vertices = interest;         mesh.triangles = triangles;           mesh.RecalculateNormals();         MeshCollider meshc = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;         meshc.sharedMesh = mesh;      }     private void OnDrawGizmos()     {         if (interest == null)             return;         for (int i = 0; i < interest.Length; i++)         {             if (ShowVert == true)             {                 Gizmos.color = new Color (0.286f, 0.486f, 0.812f);                 Gizmos.DrawSphere(interest[i], 0.2f);             }             if(ShowAlg == true)             {                 Gizmos.color = Color.green;                 Gizmos.DrawLine(old, interest[i]);                 old = interest[i];               }         }     } } 

This script is placed on a empty Game Object with a Mesh Filter, Renderer, and a collider. Note they do nothing without the faces. I have set it up so the face array goes on the triangles variable and missing part of the script should go in the SolveFaces() function. Thanks in advance.

Is it possible to find a seed based on 10,000 generated random numbers?

I’m currently entertaining an idea I’ve had about procedurally generating a world. I would like the entire world to be procedurally generated on the fly. So when a chunk is loaded, it uses a seeded random number generator to create the terrain and objects. It is seeded to maintain persistence. This is nothing new.

Next, I want the player to be able to come in and manipulate the environment (destroy blocks, place blocks; I’m using a minecraft type recreation right now to test the idea because the blocky environment is simple to work with). If we simply used a seeded random number generator, the player’s changes would get overwritten once the chunk is discarded and reloaded. So what if we use the new block locations in the scene to generate a seed for a random number generator that will generate the environment. We know the exact order that it will generate blocks, so each time a number will be generated, we know what that number should be. I’ve looked around the cybersecurity forums a bit but haven’t found a good explanation of retrieving seeds given ordered generated numbers. If this works you could save a large scene in only the seed it takes to generate it.

Please let me know if this idea is stupid and should be thrown away, thanks!

Program language in which every every string generated by its grammar is a nicely running program?

Was wondering if there is a programming language out there such that every string generated by its grammar (the grammar is given as well) is a program that does not crash.

This is so that the set of all possible programs (that don’t crash) on the machine, in that language, is generated by the grammar and the grammar generates exactly those programs.

Error messages generated in a table calculation prevent “good” elements of that table being accessed

If I make a batch fitting routine, something like:

FitResultsData =      Table[              SpectrumData = Import[SpectrumList[[i]]];                SpectrumFit = NonlinearModelFit[SpectrumData, Model, {a, b, c}, x];                  aFitOut = a /. SpectrumFit["BestFitParameters"];                  bFitOut = b /. SpectrumFit["BestFitParameters"];                     cFitOut = c /. SpectrumFit["BestFitParameters"];               {i, aFitOut , bFitOut, cFitOut},              {i, 1, Length[SpectrumList]}             ] 

and a fit fails completely, e.g. I get a Power::infy: Infinite expression 1/0.^2 encountered. error or something, I find that when it comes to going on to use FitResultsData after all Table[..] has finished fitting and executing no matter which row I select for example FitResultsData[[1]] the error Power::infy: Infinite expression 1/0.^2 encountered. will be returned. This happens even say the original source of the error was in spectrum i = 99.

Is there a method of escaping such errors, such that even though one spectrum fit might be bad, it doesn’t stop be accessing the 99% successful

Simple Java Question: How to print a random int in one class that was generated in another?

Say that I have two classes, A and B, that are in the package Sample.

In class B, I have generated a random int b that is either a 0 or 1. I want to print int b in class A. What code should I use to do this?

Here is class B:

  package Sample;   import java.util.Random;      public class B {         Random random = new Random();         int b = random.nextInt(2); //b is either 0 or 1     } 

And I need code to go in class A here:

package Sample;   public class A {  //How do I print out the int b here?  } 

How safe is a password generated from words?

I loathe passwords with completely random letters and digits. It’s so much nicer to have a password made up of proper words. Even if the total length is much longer, it’s easier to memorize, transcribe, etc.

So I thought of this password generation scheme:

result = ""  while (result.length < 12)   result += randomWord()  if (result.length < 16)   result += shortRandomWord()  result += randomInteger(1000, 9999) 

In this example, assume that randomWord() returns an English dictionary word of length 4 to 10, and shortRandomWord() returns one of length 4 to 5. This is sure to give you a password of length 16 to 21, made up of 2 to 5 words, plus the 4 random integers.

Is this a good password generator? How does its entropy compare to a function that generates a password of length 8 with random letters and digits?