javascript – Extract string list as array from an array of objects

Having the following array of objects of ingredients used by cooks

images = ({id:1, cook:"jim",   ingredients:"chicken salsa mayo ketchup tomato"},
          {id:2, cook:"steve", ingredients:"pasta mozzarela chicken"},
          {id:3, cook:"jim",   ingredients:"bread lettuce tomato onions"},
          {id:4, cook:"jim",   ingredients:"ketchup sausage bread"},
          {id:5, cook:"jim",   ingredients:"avocado ground_meat chili"},
          {id:6, cook:"jim",   ingredients:"ground_meat guacamole tomato parsley"},
          {id:7, cook:"steve", ingredients:"chicken tomato broccoli"})

I have to extract an array of ingredients used by a specific cook so that each ingredient appears only once, return only 25 ingredients unless a specific limit is provided.

extractIngredients(array, cook, limit=25)

e.g:
extractIngredients(images, "jim", 10) ==> ("chicken", "salsa", "mayo", "ketchup", "tomato", "bread", "lettuce", "onions", "hotdog", "avocado")

BONUS POINTS:

Return an ingredient array sorted by the number of occurrences, and then alphabetically, showing the most popular ingredients first.
e.g:
extractIngredients(images, "jim", 10) ==> ("tomato", "bread", "ground_meat", "ketchup", "avocado", "chicken", "chili", "guacamole", "lettuce", "mayo")

My solution:

extractIngredients(images, username, limit){
  return (...new Set(images.filter(images => images.cook == username)
       .map(a => a.keywords.split(" ")).flat())).slice(0, limit);
}

My solution has an issue with an extremely large input as it would still process all of the objects and then slice the resulting array. It would be better to just process objects until the limit is reached.

java – Efficient way to store “item” objects in a simple game

I am developing a simple text-based game. In this game, the user is able to collect items and store them in an inventory.

My question is: how should I organize the internal structure of my game so that I can load these items in an efficient way?

I need to be able to create fresh instances of an item whenever the user acquires an item of that type, or when instantiating any feature in the game that contains items. In order to do so, I feel like I need some sort of “master list” of all items that I can just copy out of by indexing into the correct location in the list.

I’ve come up with two potential solutions:

  • Hard-code this entire giant list into a data structure within my game

  • Somehow load these items from an XML file at startup and then populate the “master list” of items on the fly

Pros of option 1:

  • Relatively easy
  • No IO time
  • Allows me maximum efficiency in designing the actual item objects

Cons of option 1:

  • Hard to maintain
  • Bloats source code
  • Very tedious to implement

Pros of option 2:

  • Easy to add/remove/modify items
  • Allows the user to customize the game if they want to

Cons of option 2:

  • Requires that I design my objects much more carefully so that they can be built on the fly and stored

  • Requires that I perform a deep copy from the master list each time I need a new copy of a specific item

  • I have to write an “item-builder” that is capable of translating the XML input into an actual item object in memory.

Neither of these ideas feels very good to me. Is there something obvious I’ve missed?

java – Efficient way to store “item” objects in a simple game

I am developing a simple text-based game from scratch in Java. In this game, the user is able to collect items and store them in an inventory.

My question is: how should I organize the internal structure of my game so that I can load these items in an efficient way?

I need to be able to create fresh instances of an item whenever the user acquires an item of that type, or when instantiating any feature in the game that contains items. In order to do so, I feel like I need some sort of “master list” of all items that I can just copy out of by indexing into the correct location in the list.

I’ve come up with two potential solutions:

  • Hard-code this entire giant list into a data structure within my game

  • Somehow load these items from an XML file at startup and then populate the “master list” of items on the fly

Pros of option 1:

  • Relatively easy
  • No IO time
  • Allows me maximum efficiency in designing the actual item objects

Cons of option 1:

  • Hard to maintain
  • Bloats source code
  • Very tedious to implement

Pros of option 2:

  • Easy to add/remove/modify items
  • Allows the user to customize the game if they want to

Cons of option 2:

  • Requires that I design my objects much more carefully so that they can be built on the fly and stored

  • Requires that I perform a deep copy from the master list each time I need a new copy of a specific item

  • I have to write an “item-builder” that is capable of translating the XML input into an actual item object in memory.

Neither of these ideas feels very good to me. Is there something obvious I’ve missed?

MVC Patterns: Is There a Design Pattern For Returning Lists (Arrays) of Complex Entity Objects?

I’m struggling with how I should build out my entities, services, and DAOs in an MVC web application when it comes to returning a list (array) of data. On one hand, returning an array of entity objects keeps the code lean and easy to maintain, however, there’s a performance hit for building and returning complex entity objects when my view(s) may not need all that data at once.

For this example, let’s say I was creating a service to work with campgrounds (you know, those places with tents, lots of dirt, and mosquitoes). Campground entities, in this project, are rather complex objects because they have many properties, nested value objects, and a few behaviors.

My CampgroundService is going to have some pretty standard methods like getById() and list().

UML Diagram

The getById() method is mostly straightforward and will primarily be used when displaying detailed information on a single campground. Having CampgroundService return a single Campground entity here is the perfect solution.

Things get tricky with the CampgroundService list() method. The list() method accepts a filter object argument that contains criteria to filter by. For example, there may be times when I need to grab a list of campgrounds for an entire US state or a list of campgrounds based on a bounding box of geospatial coordinates (i.e. latitude and longitude).

The views that display the list (array) generally only need a small subset of the data contained in the full Campground entity. For example, most of the time when listing I only need the name, state, altitude, latitude, and longitude. It feels like overkill to have to build out the full Campground entity with all the nested objects every time I want to get a simple list of campgrounds and there is most certainly a measurable performance hit for doing so.

Hence my question: Is there a best-practice or design pattern handling listing data in an MVC app?

Here are some possible solutions I have been considering:

1. Caching to the Rescue?
Caching would handle the speed problem on subsequent requests for data, however, storing potentially large arrays of entities in memory seems like a bit of a waste. Additionally, there may be times where I cannot really use caching because one of the views in the app sorts campgrounds by the geographic data type. I have MSSQL (via my DAO) doing the heavy lifting here for geo spacial sorting since it does it very quickly and the reference point for sorting could change rapidly (when the user moves the map around). Caching doesn’t feel right for this use case.

2. Create a new, smaller “Summary” Campground entity
I could create a new entity object called CampgroundSummary and a new service called CampgroundSummaryService which would only hold the most basic fields for listing campgrounds. I expect this model would be much more lightweight and faster to assemble than the primary Campground model. However, the downside is that I feel like I’m violating the DRY (don’t repeat yourself) principle by creating similar (albeit abbreviated) entity objects and services.

3. Return a Basic Array Instead
I could forget about returning an array of entities altogether when listing data, and instead, just return an array of simple key/value objects. This feels very “noobish” to me, but the performance advantage could make it worthwhile. The downside of this approach is that I lose the advantages of using entities that enforce data integrity and behaviors (assuming I need them someday).

4. A Hybrid of Options 2 and 3
Simplifying the model into a CampgroundSummary might be ideal in cases where I need to show a list of campgrounds by state, but only need a small subset of properties. I could even cache that data too to make it load lightning fast. However, for other cases where performance is the top priority, I could create a separate method in my CampgroundService like getSimpleList() which would return a simple array of key/value objects.

I would very much be interested in your insight on this subject.

postgresql – Query to find hierarchical relationship between objects

I want to execute a SQL query in PostgreSQL 10.6. I have two tables, A and B, that contain a common field, which contains a code. Each code has an inherited code and I want to build a hierarchical classification of these codes.

TableA

id | code
---------
1  | A
2  | B
3  | C
4  | D
5  | E

TableB

id | code | origin | change_date
--------------------------
1  |  A   |   B    | 2020/01/01
2  |  B   |   C    | 2019/01/01
3  |  C   |   D    | 2018/01/01
4  |  D   |   E    | 2017/01/01

I want to get origin values for a defined code in a chronological order. For example with tableA.code = A :

code A origin is B, code B origin is C, code C origin is D, code D origin is E

In other words, for a code A :

id | code | source
------------------------------
1  | A    |  B -> C -> D -> E

I can write a basic query to find value(s) but how can I execute this query each time there is a result and with a dynamic variable for the where clause (= the result of my previous query) ?

SELECT b.origin
FROM tableB b
JOIN tableA a USING (code)
WHERE table a.code LIKE 'A' 

SELECT b.origin
FROM tableB b
JOIN tableA a USING (code)
WHERE table a.code LIKE 'B' 

...

I have seen examples with functions, DO, DECLARE, IF, LOOP, RETURN QUERY EXECUTE but I don’t know what the best way to write this query.

json – Python arbitrary objects Serialization and Deserialization

I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code.

import json

Here is the first class

class Foo():
    def __init__(self,x,y,bar):
        self.x =x
        self.y = y
        self.bar = bar #Second class object is here

    def toJson(self):
        return json.dumps(Foo(self.x,self.y,self.bar).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Foo(
            x = data('x'),
            y = data('y'),
            bar = Bar.fromJson(data('bar'))
        )

Here is the second class

class Bar():
    def __init__(self, z):
        self.z = z


    def toJson(self):
        return json.dumps(Bar(self.z).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Bar(
            z = data('z'),
        )

Convert to Json

jsonData = Foo(100,500,Bar(900).toJson()).toJson()

Retrieve the Json and convert to Object

foo = Foo.fromJson(jsonData)

Print the Object attributes

print(foo.bar.z)

It works actually. But is there any memory leakage? Any security issue?

winforms – Questions about class objects and its new initializations, static (c#)

I’m new to programming and for last couple of weeks I’m working a project. In this project I stumbled on a problem and questions related to it, because i couldn’t find the right answer (most of them were close to it and so on).
In this program you can search for a movie, save it to MySQL database, view its info and so on. So my problems and questions are:

  1. Initial problem was class objects. At the start user logins in the program and I give the username to DBConnection class in which it determines what userID it has and saves to a variable (it is needed to correctly save, delete the new movie for that specific user), but from courses and so on I learned and everyone showed that in new classes or forms in order to access other classes you have to create a new instance of it, but because of that a new problem occurred – every time I made a new instance then the saved userID would be 0
    ( 1.1) I assume its because new instance creates the same class but without new variable, so if I create new class object, with it change values then create new instance, then the values will be the default ones, not like the ones created from previous instance? -> Did I understand the new class initializing correctly or does it work differently? ) to ecape that problem (if I understood it correctly) I made the variable userID static and from basic tests I understood that it saved and had the new value in it even if later on in program I made new instance of that class in different UserControl. (It should work like that, correct? Or did I not understand it..
  2. second question is related to the previous. Because of this problem I made some methods static (later I realized I don’t need it, but this raised some misunderstandings too) so I could access like DBConnection.MyMethod but does this mean that with this type of access I never initialize constructor, correct? This question is important because in the constructor I have the basic info and set the values to variable with which I have necessary data to connect to my MySQL database. So for example, if I do the DBConnection.MyMethod in a different class and within that method I need the information which is set in Constructor does that mean that the method won’t work because the values are not set or it will if the class is initialized sometime previously within the program but from different class?
  3. When does one would want to use class object and initializing it as a new instead of just using the example of DBConnection.MyMethod and using static? Like at what point would I really want/need class objects? Whenever I have anything in the constructor within there are needed values for some methods? Or other aspects (I know it is a broad question and have seen some abstract answers, but maybe you could give some examples)

I know the post is long, but as I said these are more of clarification questions more than anything so I could finally wrap my head around, because for the last hours, even a day, I tried to solve this problem and had these questions.

P.S.
I know I didn’t post any code, because it’s really long and messy in my program, but if anyone wants to see it to understand more it’s available at https://github.com/KarlisAG/Movie-Project/tree/master/Project_Movie/Project_Movie (the following DBConnection is in Database folder in the said .cs). Only when I finish the program and it works like I want it, then I will make it a lot shorter and hopefully cleaner (atm it repeats a lot and many parts are probably un-needed, but this is a first big project that’s why it is really messy).

P.S.S.
Additional question to a problem I’m trying to solve now. I have a listview and when user clicks on columns it sorts it, but the problem is it only does it for the title and not other parameters if the user clicks on different columns ( ) and whenever user opens different UserControl and returns to the one with listview then the table is still sorted (by title) but the other columns are shown as blank spaces -> how and why does this happen?

private void SortColumn(object sender, ColumnClickEventArgs e)
        {
            if (asc)
            {
                listView1.Sorting = SortOrder.Descending;
                asc = !asc;
            }
            else
            {
                listView1.Sorting = SortOrder.Ascending;
                asc = !asc;
            }

(asc is a bool with which the program knows if it is in ascending order at that time or now)

Thank you to anyone in advance!

unity – How to move objects across a canvas with consistent speed on different screen resolutions?

If you want to linearly interpolate between two values, the jargon for that is “lerp“. The basic idea is you pass a lerp function two values and a number between 0 and 1 that specifies how far between the two you want the current position to be. In this way you can control when a moving object hits the target by controlling when the value between 0 and 1 hits 1.

Here’s an official Unity article on lerping.

After adapting examples from there to your particular use case where at least two notes need to hit the same place at the same time I get this:

Vector3 noteAStart = new Vector3 (...); 
Vector3 noteBStart = new Vector3 (...); // choose these however you like
Vector3 center = new Vector3 (...); // calculate the center of the screen here.

Vector3 noteACurrent = Vector3.Lerp (noteAStart, center, progress);
Vector3 noteBCurrent = Vector3.Lerp (noteBStart, center, progress);

You can then set your notes’ positions directly to noteACurrent and noteBCurrent, which will be change based on the current value of progress. So, if we can figure out what to set progress to each frame, then we’re set. But how do we do that?

First, we need to know how long we want the animation to take. Let’s assume we want it to take half a second.

Well, assuming the game runs at exactly 60 frames per second, the most straight-forward way would be to just increment progress by 1/30th each time, so we get to 1 after exactly 30 frames.

const float PROGRESS_PER_UPDATE = 1.0 / 30.0;
//...
progress += PROGRESS_PER_UPDATE;

However, Update does not necessarily get called exactly 60 frames per second, depending on the system load. Depending on your timing needs the occasional lag may be both noticeable and highly undesirable.

One way to deal with this is to factor in the time that the last frame took, (the Time.deltaTime,) into the interpolation, by doing something like this:

progress += Time.deltaTime / DESIRED_DURATION_IN_SECONDS;

But this approach can produce undesirable results if Time.deltaTime is ever significantly larger than it usually is, depending on what other code is triggered by progress reaching or exceeding 1.0. You also may want to clamp progress to be at most 1.0, depending on how far things move in a frame.

Another method which Unity has built-in for you, is to use FixedUpdate instead which attempts to provide a more consistent time step, allowing you to just use a constant amount of progress per frame. It is still true that ultimately a system with sufficiently heavy load, (say several other heavy programs are running in the background besides just your game,) will need to skip some frames, and/or call the method at a different frequency, some of the time. In practice this is likely not an issue.

If the way Unity deals with the an overloaded machine ever does become an issue, it would be possible to keep track of the actual elapsed time yourself, and react accordingly. You could even set up your own loop that handles heavy load the way you want to, but this is much more complicated, particularly making such a loop play nice with Unity’s expectations.

kotlin – java.lang.ExceptionInInitializerError in self-referential objects?

I’m having problems with the jvm compiler.

I’m trying to write a factory method for classes. The factory method has an init() block that helps to define behaviour for the new object. While this method compiles for JVM, I encounter a problem when running it:

java.lang.ExceptionInInitializerError

Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method type.ProblematicKt.nullable, parameter $this$nullable

Apparently, the object isn’t yet defined when I attempt to run the problematicInit() block. How do I fix this?

Seems to be a JVM problem. It seems to work for Javascript compilations. My understanding was that getProblematic would be hoisted, but what’s inside the scope would be deferred until it’s run designed to be run later – after the factory method is completed.

interface ProblematicBuilderScope {
  fun problematicInit(getX: () -> ProblematicInterface)
}

fun getProblematic() = X
class Problematic(...): ProblematicInterface

// Factory method with init() block
val X = Problematic.factory(...) {
  problematicInit{ getProblematic() }
} 

fun factory(init: ProblematicBuilderScope.() -> Unit): Problematic {
  val newObject = Problematic(...)
  val scope = ProblematicBuilderScope(newObject)
  scope.init()
  return newObject
}

list manipulation – Thread::tdlen: Objects of unequal length in {{a,b,e},{c,d,f}} {x,y,z} cannot be combined

When I do the Times operation among list like this {{a, b, e}, {c, d, f}}*{x, y, z}, the error message is given as Thread::tdlen: Objects of unequal length in {{a,b,e},{c,d,f}} {x,y,z} cannot be combined. Actually, the desired result should be {{a x, b y, e z}, {c x, d y, f z}}. Are there any bugs?