diff --git "a/stack_exchange/SE/SE 2020.csv" "b/stack_exchange/SE/SE 2020.csv" new file mode 100644--- /dev/null +++ "b/stack_exchange/SE/SE 2020.csv" @@ -0,0 +1,80951 @@ +Id,PostTypeId,AcceptedAnswerId,ParentId,CreationDate,DeletionDate,Score,ViewCount,Body,OwnerUserId,OwnerDisplayName,LastEditorUserId,LastEditorDisplayName,LastEditDate,LastActivityDate,Title,Tags,AnswerCount,CommentCount,FavoriteCount,ClosedDate,CommunityOwnedDate,ContentLicense, +403167,1,403168,,1/1/2020 17:03,,-2,71,"
I'm not sure if this question belongs to Stack Overflow or somewhere else. Sorry if it doesn't belong here.
+ +My question is, in an IDE, does its linter, check the whole source code every time (whenever a user update the code or periodically), or does it check only the code that has been added/removed?
+",354077,,354077,,43833.75069,43833.75069,Working of linters in an IDE,I maintain a small (tiny!) .NET library.
+ +It has a few ill-defined edge cases, which I call out explicitly in the docs. +Places, where the ""correct"" behaviour is not self-evidently well-defined, so I explicitly said
+ +++ +For invocations like this, the method may return any of the viable outputs.
+ +Note that in all of these 'may return any' cases, I suspect that it will always return the top-most value, but that will be dependant on .NET's implementation of various methods and is not in anyway guaranteed by this library! Frankly, any of these would be a mis-use of the library and could arguably throw instead.
+
I think that I could release this as a patch, and still be honouring SemVer. Because even though the in-practice functionality has changed, it is functionality which the docs explicitly instructed users not to rely upon.
+ +Have I correctly interpretted SemVer?
+",277850,Reinstate Monica --Brondahl--,,,,43832.56667,"In SemVer, am I allowed to change the in-practice behaviour of undefined behaviour usages",I am making a website that requires a secure area for the website owner to easily upload new content to. Because this is a relatively simple website there is no account system. I just have a URL for them to go to and enter a password (in a form with a ReCaptcha) to enter the secure area. My issue is, how do I allow access only after they are verified. Here are the options I've considered:
+ +.php the file where they are sent by the form. Then check for the session every time that page loads..php file as the secure area (Not ideal, but it's by far the most secure way I can think of)Are there any options that I am missing? I couldn't find anything related to this at all online. This site doesn't have to be super secure, but I really don't want the wrong person getting in. I'm also asking this question for best practices later on.
+",354092,,1204,,43832.69583,43832.69583,Securely allow access to a secure area of a website with PHP,I'm doing a project in PHP and I'm implementing Aggregates and Event Sourcing. In order to avoid coding up all the logic related with ES myself I've decided to use a third party library called EventSauce.
+ +I would want to avoid coupling my code, specially my domain, with an external library. However, from what I have seen in the docs I need to use classes that implement the EventSauce interfaces. I would like to use my own interfaces in order to have control of the possible changes made to the library or if I would like to change to another library in the future. I would illustrate this with an example.
+ +I have a repository with the following interface:
+ +interface ItemRepository
+{
+ public function itemOfSku(Sku $sku): Item;
+
+ public function nextSku(): Sku;
+
+ public function save(Item $item): void;
+}
+
+
+And the library needs an interface, which is kind of equivalent, like:
+ +interface MessageRepository
+{
+ public function persist(Message ... $messages);
+ public function retrieveAll(AggregateRootId $id): Generator;
+}
+
+
+Other parts of the library depend on this MessageRepository so I am forced to implement this interface. If this restriction doesn't exist it would be much easier.
I would like to know if there is any design pattern that would allow me to decople from the third party interface and not pollute my domain.
+",354102,,,,,43832.41597,Decoupling from third party library,I have a Foo service that, among other things, retrieves data from a table called Widget. This table has about 50 columns. This service is called by a request from a browser.
+ +Now, I have another service, Bar, that wants to call Foo. This is a Windows Service that we can trust because there is no end user. Bar also needs data from the Widget table. However, Bar only needs 3 columns of data. Bar needs this before calling Foo.
+ +My concern is the inefficiency of Bar getting Widget, only for Foo to also do the same thing. I can think of three options:
+ +Number 1 is inefficient because Bar and Foo will get the same data.
+ +Number 2 works, but Foo has to trust the caller. Foo can't trust the caller in one case, because it's from a web request. But Foo can trust the service call.
+ +Number 3 also works, but it's slightly inefficient because it's getting Widget data, although it's a much slimmer version. And we would need DTO just for this Bar process, and the DTO would just have the three fields.
+ +I'm leaning towards #3, but would love some input, especially if there is another approach that I'm not considering.
+",29526,,,,,43832.66597,Is it ok to have a DTO for each process/app/service in a system?,In a php project that I maintain I have a database structure without migrations, hence no way to reproduce it or make on the fly a test database.
+ +And the queries used to be performed on them are rather complex ones. The pattern in code used with them is (I try to show a generelized preview of the problem):
+ +public function someMethod(PDO $connection, string $param) {
+
+ $sql=""^some complex sql query^"";
+ $pdo->prepare($sql);
+ $pdo->bindParam('param',$param);
+ $stmt->execute();
+
+ return $stmt->fetchAll();
+}
+
+
+
+In order to test this function I created a duplicate database and from that I deleted all the production data keeping the least minimal. I use the following testing approach when I write phphunit test
+ +Did this approach creates a Unit test for my application or an Integration one. Keep in mind that the whole logic is implemented in an SQL query instead on the php layer.
+ +For example a query like that:
+ +Select
+ value,
+ CASE
+ WHEN ""time""::time < '12:00' and ""time""::time > '00:00' then true
+ ELSE
+ false end as observed_in_morning
+from
+ observations
+
+
+The example above the logic that indicates whether an observation happened in me morning or not is written on the sql statement, clearly a business logic.
+ +So a test testing whether an observation happened in the morning is a unit test or an integration one?
+",249660,,249660,,43833.37778,43833.37778,Testing Queries Themselves with Test data is a Unit test or an Integration test?,Consider something like....
+ +(Pseudocode Javascript like)
+ +var capitalizeWord: function(word){
+ word.toAllCaps();
+}
+
+
+What if now I need to do multiple words, but still sometimes only do one still. Is it better to do...
+ +var capitalizeWords: function(words){
+ _.forEach(words, function(word){
+ capitalizeWord(word);
+ }
+}
+
+var capitalizeWord: function(word){
+ word.toAllCaps();
+}
+
+
+OR just have one function
+ +var capitalizeWords: function(words){
+ _.forEach(words, function(word){
+ word.toAllCaps();
+ }
+}
+
+
+And when I need to just capitalize one word....cast it to an array before calling capitalizeWords?
+ +capitalizeWords([word]);
+
+",354132,,,,,43833.65903,"When a function can take a single item or multiple, is it better to have more than one function or just one function that takes arrays?",I'm a great fan of refactoring but I've been wondering about the issues raised by refactoring.
+Fowler advises refactoring
To this end he dislikes temps and long lists of parameters in methods. He sees a lot of temps or parameters as symptoms of more fundamental problems with the code structure. But getting rid of temps can itself raise other issues. Obviously if a temp is brought in to hold the output of one method before it's input to another method, you lose code readability if you just pipeline the two methods on a single statement and eliminate that temp. So we can't eliminate all temps if we want to maintain code readability.
+ +But we should try to remove as many as possible. The crudest way to eliminate a share of temps is to use global variables. But with this you are making mere utility objects into class-wide fields (attributes). This would lead to a lot of fields with few of them having a claim to be germane to the definition, or working essence, of the class per se. This is hardly in the spirit of good OO design.
+ +Often we see the input parameters to a class made into that class' fields. +However, if the input parameters are simply containers (e.g. input files, collections or aggregates) for the data vital to a class, then it makes no sense to make such things into class fields. It would make more sense for the constructor to extract the essential data from these inputs and make those objects/collections the class fields. Likewise if a class is a data processor of some kind - think of a text processor which has file inputs for raw text and 'noise' words and which produces data structures for 'noise' and non-noise words - then I think it's arguable to have the output data structures of the process also defined as class fields. This especially so when the output objects will be used as inputs to, say, some stat analysis or graphic display classes. Here we clearly need some methods to getOutputCollection1(), getOutputCollection2(), etc. Having those output collections stored as class fields with their predefined getters facilitates this retrieval without re-running the processing to produce them. Other types of class (model classes for real-world objects, e.g. HotelRoom) may not require such judicious consideration of field data as the attributes would be more obvious.
+ +I have seen very little focus on selection or use of class fields. It's hard enough to find anything but a short discussion on this matter. There's no mention at all on their potential for eliminating temps in Fowler's or other books on refactoring.
+ +If any other SO members have views on this question then I would like to receive them.
+ +I attach a code example that is small enough and big enough, I think. +This program takes a load of pre-formatted messages from a file holding a large block of messages from a free email service (""gPost"") and takes another file of noise words. It imports into suitable data structures both the message text and the noise words. It then creates a LinkedList of all non-noise words in the messages from each mailbox user and outputs all users' top 10 most frequently used non-noise words.
+ +public class GPostProcessor
+{
+ private List<GPost> gPosts = new ArrayList<>(); // GPost ArrayList holding ALL contents of input file
+ private Set<String> noiseWords; // HashSet buffer for noise words
+ private Set<MyString> mailboxHandles = new TreeSet<>(); // TreeSet for holding mailbox handles alphabetically
+ private Map<MyString, List<WordCount>> wordUsages = new HashMap<>(); // HashMap collection for vocab list of all mailboxes
+
+
+ // CONSTRUCTORS ...
+ /** Parameterless constructor.<br>
+ * The system cannot operate without input file parameters.<br>
+ * So the parameterless constructor essentially displays an error message <br>
+ * before conducting an orderly shut down of the program.
+ */
+ GPostProcessor()
+ {
+ System.out.println(""ERROR at GPostProcessor - no parameters in constructor !""
+ + ""\nThe system will now shut down in 5 seconds."");
+ try
+ {
+ TimeUnit.SECONDS.sleep(5);
+ }
+ catch(Exception e)
+ {
+ e.printStackTrace();
+ }
+ System.exit(0);
+ System.out.println();
+ throw new IllegalArgumentException(""No parameters for GPostProcessor instance ! ""
+ + ""\nSystem shutdown follows."");
+ }
+
+ /** Parametered constructor.<br>
+ * Input messages and noise-words files are applied to input parameters.<br>
+ * @param messagesFile A String holding the name of the messages file.
+ * @param noiseWordsFile A String holding the name of the noise words file.
+ */
+ GPostProcessor(String messagesFile, String noiseWordsFile)
+ {
+ if (messagesFile == null)
+ {
+ System.out.println(""ERROR at GPostProcessor parametered constructor !""
+ + ""\nNull parameter for messages file.""
+ + ""\nThe system will now shut down in 5 seconds . . ."");
+ try
+ {
+ TimeUnit.SECONDS.sleep(5);
+ }
+ catch(Exception e)
+ {
+ e.printStackTrace();
+ }
+ System.exit(0);
+ }
+ else if (noiseWordsFile.equals(null))
+ {
+ System.out.println(""ERROR at GPostProcessor parametered constructor !""
+ + ""\nNull parameter for noise-words file.\n""
+ + ""\nThe system will now shut down in 5 seconds . . ."");
+ try
+ {
+ TimeUnit.SECONDS.sleep(5);
+ }
+ catch(Exception e)
+ {
+ e.printStackTrace();
+ }
+ System.exit(0);
+ }
+ else // Fill in primary data structures ...
+ {
+ this.gPosts = parseToGPosts(loadGPostMessages(messagesFile)); // Extract all gPosts from input file to one big string
+ this.noiseWords = loadNoiseWords(noiseWordsFile); // Load noise words from their file into a HashSet
+ }
+ }
+
+ // GETTERS & SETTERS - mainly used for the JUnit tests.
+
+
+
+ /******************************************************************
+ ***** This is the MAIN class for the gPostProcessor package. *****
+ *
+ * @param args A String array into which arguments may be put.
+ *****************************************************************/
+ public static void main(String[] args)
+ {
+ final Instant startTime = Instant.now();
+ new GPostProcessor(""messages3.txt"", ""noiseWords.txt"").processGPosts();
+ final Instant endTime = Instant.now();
+ final long duration = Duration.between(startTime, endTime).toNanos();
+ System.out.printf(""\n%-10s%12s%1s%2s"", ""Duration: "", duration, "" "", ""ns"");
+ }
+
+
+ // DATA MANIPULATION METHODS ...
+ /** Processes the file of gPosts, <i>messagesFile</i>, excluding words in the
+ * noise words file, <i>noiseWordsFile</i>.
+ * Each gPost message is drawn from an ArrayList<String> buffer generated
+ * by method <i>loadGPostMessages(.)</i>, converted into GPost objects and analysed
+ * before adding its mailbox handle and WordCount list to a HashMap collection, <i>wordUsages</i>.
+ * Finally, a report is generated showing the 10 most used words for each gPost
+ * user whose emails are listed in <i>messagesFile</i>.
+ */
+ void processGPosts()
+ {
+ GPost gPost; // Temp GPost object
+ MyString mHandle; // Temp gPost address handle
+ List<WordCount> messageList; // Temp WordCount list got from a GPost
+
+ for(int p = 0; p < gPosts.size(); p++) // Analyse each gPost in the input file
+ {
+ System.out.println(""Processing gPost #"" + (p + 1) + "" ...""); // Display email # being processed
+ gPost = gPosts.get(p);
+ mHandle = getMailboxHandle(gPost); // Extract the user's mailbox handle
+ mailboxHandles.add(mHandle); // Add mailbox handle to TreeSet of handles
+ messageList = getMessageList(gPost); // Extract the wordCountList from the gPost
+ mergeInUserVocab(mHandle, messageList); // Merge wordCountList with existing vocabList
+ }
+ Map<MyString, List<WordCount>> wordUsagesTop10 = prepareDataForReport(); // Prepare data for report ...
+ generateReport(wordUsagesTop10, ""report.txt""); // ... and generate report for mailbox user
+ }
+
+ // FILE BUFFERING METHODS ...
+
+ /** Reads in gPost items line by line from the text file, <i>messagesFile</i> and puts
+ * its contents immediately into a single big String object.<br>
+ * This ensures minimal delay at the slowest stage of the system, i.e. reading input.
+ * Parsing and analysing of gPost items from the input file is done by other non-I/O methods.
+ * @param messagesFile A String holding the name of a file holding all gPosts.
+ * @return A String object holding all the input file contents..
+ */
+ String loadGPostMessages(String messagesFile)
+ {
+ final Instant startTime = Instant.now();
+ StringBuilder contents = new StringBuilder(),
+ textLine = new StringBuilder(); // Output gPosts as a single StringBuilder
+
+ if (messagesFile == null)
+ { // Check for null filename
+ contents = null;
+ System.out.println(""ERROR ! No or null filename for messages file.""
+ + ""\nPlease check messages file and ensure valid name entered."");
+ }
+ else
+ {
+ try
+ {
+ BufferedReader buffReader = new BufferedReader(new FileReader(messagesFile));
+ while ( !textLine.append(buffReader.readLine() ).toString().equals(""null"") ) // While file has content in next line ...
+ {
+ contents = contents.append(textLine); // ... add line to file contents StringBuilder
+ textLine.setLength(0); // ... then clear textLine for next read.
+ }
+ buffReader.close();
+ }
+ catch(IOException re)
+ {
+ contents = null;
+ System.out.println(""\nReading of "" + messagesFile + "" failed."");
+ re.printStackTrace();
+ }
+ }
+ final Instant endTime = Instant.now();
+ final long duration = Duration.between(startTime, endTime).toNanos();
+ System.out.printf(""\n%-10s%12s%1s%2s"", ""Load Duration: "", duration, "" "", ""ns"");
+ return contents.toString();
+ }
+
+
+ /** Reads in noise words from the text file, <i>noiseWordsFile</i>, and puts
+ * them into a HashSet<String>. <br>
+ * Noise words are assumed to be on separate lines of the text file to
+ * facilitate rapid reading of the input.
+ *
+ * @param noiseWordsFile A String object giving the name of the file
+ * that holds all the noise words.
+ * @return A HashSet<String> holding all the noise words.
+ */
+ Set<String> loadNoiseWords(String noiseWordsFile)
+ {
+ Set<String> noiseWords = new HashSet<>();
+ String textLine;
+
+ try // Read in noise words from textfile, ""noiseWordsFile""
+ {
+ BufferedReader buffReader = new BufferedReader(new FileReader(noiseWordsFile));
+ textLine = buffReader.readLine();
+ while (textLine != null)
+ {
+ noiseWords.add(textLine.toLowerCase().trim());
+ textLine = buffReader.readLine();
+ }
+ buffReader.close();
+ }
+ catch(IOException re)
+ {
+ System.out.println(""Read of "" + noiseWordsFile + "" failed.\n"");
+ re.printStackTrace();
+ }
+ return noiseWords;
+ }
+
+ // PROCESSING METHODS ...
+ // ==================
+ /** Check each block of the gPost string to see if it is in valid gPost format.
+ * @return A String value that holds the error message if the gPostsText is not validly
+ * formatted or a null string otherwise.
+ * */
+ String validGPost(StringBuilder gPostsText)
+ {
+ int mHandle = gPostsText.substring(0, 254).indexOf(""@gPost.com""), // Find index of first email handle
+ start = gPostsText.indexOf(""gPostBegin""), // ... next gPostBegin ...
+ end = gPostsText.indexOf(""gPostEnd""); // ... and next gPostEnd
+ if (mHandle < 0)
+ {
+ return ""ERROR in input text: missing sender address."";
+ }
+ else if (start < 0)
+ {
+ return ""ERROR in input text: missing message preamble."";
+ }
+ else if (end < 0)
+ {
+ return ""ERROR in input text: missing message epilogue."";
+ }
+ else if (start < mHandle)
+ {
+ return ""ERROR in input file: message preamble before sender."";
+ }
+ else if (end < mHandle)
+ {
+ return ""ERROR in input file: message epilogue before sender."";
+ }
+ else if (end < start)
+ {
+ return ""ERROR in input file: message epilogue before preamble."";
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ /** Converts a large string containing many gPosts into a ArrayList<GPost> collection.
+ *
+ * @param gPostsString A String object that carries the important contents of a gPosts' file.
+ * @return An ArrayList<GPost> collection holding sender and message text for the input gPosts.
+ */
+ ArrayList<GPost> parseToGPosts(String gPostsString)
+ {
+ ArrayList<GPost> result = new ArrayList<>(); // Copy input file String to a StringBuilder
+ StringBuilder sender = new StringBuilder(""""),
+ message = new StringBuilder("""");
+ String error;
+ int postNum = 0, // gPost index
+ iHandle, // Email handle index
+ start, // Start index of message
+ end = 0; // End index of message
+
+ if (!gPostsString.equals(null))
+ {
+ StringBuilder gPostsText = new StringBuilder(gPostsString.replaceAll(""\\r\\n|\\r|\\n"", "" "")); // Turn line breaks to spaces
+ while (gPostsText.length() != 0)
+ {
+ if ((error = validGPost(gPostsText)) != null) // Invalid gPost formatting ?
+ {
+ System.out.println(""\n Post #"" + postNum + "" - "" + error); // => Output error
+ }
+ else // Valid gPost format ...
+ {
+ iHandle = gPostsText.indexOf(""@gPost.com""); // Find index of handle
+ sender.append(gPostsText.substring(0, iHandle + 10).trim()); // Store sender handle
+ start = gPostsText.indexOf(""gPostBegin"") + 10; // Start of gPost message is after preamble
+ end = gPostsText.indexOf(""gPostEnd""); // End of gPost message is before epilogue
+ message.append(gPostsText.substring(start, end).trim()); // Strip out gPost message
+ if (message.equals(null))
+ {
+ System.out.println(""\n Post #"" + postNum + "": Empty message.""); // Empty message warning
+ break;
+ }
+ else
+ {
+ result.add(postNum, new GPost(sender.toString(), message.toString())); // Add to gPost ArrayList
+ start = end + 8; // Reset start index for remainder of gPostsString
+ sender.setLength(0); // Clear sender ...
+ message.setLength(0); // ... and message StringBuilders
+ }
+ }
+ gPostsText = gPostsText.delete(0, end + 8);
+ postNum++;
+ }
+ }
+ else
+ {
+ result = null;
+ System.out.println(""No gPosts produced. \nPlease check input file"");
+ }
+ return result;
+ }
+
+
+ /** Returns the mailbox handle for the sender of a gPost message.<br>
+ * The mailbox handle for a sender with an email address of <i>john.west@gPost.com</i>
+ * is simply the email with the <i>{@literal @}</i> character and the domain name removed,
+ * i.e. <i>john.west</i>. <br>
+ *
+ * @param gPost A GPost object holding the contents of a gPost message.
+ * @return Returns the handle of the email address sending a GPost message.
+ */
+ MyString getMailboxHandle(GPost gPost)
+ {
+ return new MyString(gPost.getSender().substring(0, gPost.getSender().indexOf(""@"")));
+ }
+
+
+ /** Analyses the input gPost to generate the list of non-noise words in it.
+ * Noise words are drawn from the class attribute, <i>noiseWords</i>.<br>
+ * @param gPost A GPost object holding the contents of a gPost message. .
+ * @return Returns the unsorted WordCount list extracted from a GPost message.
+ */
+ List<WordCount> getMessageList(GPost gPost)
+ {
+ List<WordCount> result = new LinkedList<>(); // Returned List of non-noise words
+ List<String> wordList; // List for words extracted from gPost message
+ WordCount newWordCount; // A WordCount object for additions to messageList
+ String word; // Any word in wordList
+ int i = 0, // Iteration indices
+ j = 0;
+
+ String message = gPost.getMessageText().toLowerCase(); // Extract message text from gPost & lowercase it
+ message = message.replaceAll(""[\\p{P}&&[^\u0027]]"", "" ""); // Replace punctuations bar apostrophes by space
+ wordList = new LinkedList<>(Arrays.asList(message.split("" +""))); // Split message into words then put these into a LinkedList
+ while (i < wordList.size()) // Remove noise & non-alphabetic words
+ {
+ word = wordList.get(i).trim();
+ if ( (noiseWords.contains(word)) || (!word.matches(""[a-z]+$"")) ) // Remove noisewords & non-alphabetic char words ...
+ {
+ wordList.remove(i); // ... this includes words with apostrophes
+ }
+ else // CARE! Don't increment iterator index after removal !
+ {
+ for(j = 0; j < result.size() && !result.get(j).getWord().equals(word); j++); // Check each word in the message ...
+ {
+ if (j < result.size()) // Already on messageList ?
+ result.get(j).setCount(result.get(j).getCount() + 1); // => increment its count
+ else // Not on messageList ...
+ {
+ newWordCount = new WordCount(word, 1); // => create WordCount object for that word with count = 1 ...
+ result.add(newWordCount); // Increment wordList iterator
+ }
+ i++;
+ }
+ }
+ }
+ return result;
+ }
+
+
+ /** Merges a WordCount list (<i>messageList</i>) got from a gPost message with the
+ * WordCount list for the entire message vocabulary (<i> vocabList</i>) already held
+ * for that same gPost user.
+ * To make subsequent mergings as efficient as possible, we exploit the fact that the
+ * word use frequency by a person follows a Zipf distribution - the discrete variable
+ * version of the Pareto or 80/20 distribution. Basically, the vast majority of the words
+ * a person uses comes from a small minority of their vocabulary. So by keeping <i>vocabList</i>
+ * sorted in order of frequency and the most frequent word at the head of the list, we
+ * can sharply reduce the average search time for words in subsequent messages.
+ *
+ * @param messageList A LinkedList<WordCount> object holding WordCount data from
+ * a single message.
+ * @return A LinkedList<WordCount> collection showing a given user's WordCount data.
+ */
+ void mergeInUserVocab(MyString mHandle, List<WordCount> messageList)
+ {
+ int j, // Indices for list items
+ mark;
+ WordCount wordCount;
+ List<WordCount> vocabList = wordUsages.get(mHandle); // Temp for mailbox WordCount list
+
+ if (vocabList == null) // When existing vocabList for that handle is empty ...
+ {
+ messageList.sort(WordCount::compareByCount); // ... sort the messageList by COUNT and assign it to vocabList
+ wordUsages.put(mHandle, messageList);
+ }
+ else // When the existing vocabList for that handle is NOT empty ...
+ { // ... check if each word in messageList exists in vocabList
+ for(int i = 0; i < messageList.size(); i++)
+ {
+ wordCount = messageList.get(i);
+ for(j = 0; j < vocabList.size(); j++) // Check vocabList for each word in messageList
+ {
+ if(wordCount.getWord().equals(vocabList.get(j).getWord())) // When a word match is found ...
+ {
+ vocabList.get(j).setCount(vocabList.get(j).getCount() + wordCount.getCount()); // .. update vocabList count accordingly
+ break; // ... and stop searching vocabList
+ }
+ } // NOTE: j is closing index of vocabList search loop
+ mark = j; // Set insertion index at either vocabList match index or list tail
+ while (mark > 0 && vocabList.get(mark - 1).getCount() < wordCount.getCount()) // Find correct count location for updated or new word
+ {
+ mark--;
+ }
+ if (j == vocabList.size()) // When the messageList item is not in the vocabList ...
+ {
+ vocabList.add(mark, wordCount); // .. insert the new item at the correct index ...
+ }
+ }
+ }
+ wordUsages.put(mHandle, vocabList); // wordUsages now updated & re-sorted by count.
+ }
+
+
+ /** Prepares the processed WordCount lists for each user so that the 10 most frequently used words
+ * are stored against email address for each mailbox owner. <br/>
+ * Since wordUsages contains lists of words that are SORTED BY FREQUENCY ALONE and have not yet
+ * been sorted alphabetically, we have to look at words on each list after the tenth word in case
+ * some of these have the same count as the latter.
+ * After all of these are identified and added to the top 10 words, the resulting list can
+ * be sorted by firstly count and then alphabetically for words on equal count.
+ * @return A HashMap collection of the most frequently used words in all gPost users hashed by
+ * the user's email handle.
+ * */
+ Map<MyString, List<WordCount>> prepareDataForReport()
+ {
+ Map<MyString, List<WordCount>> result = new HashMap<>(); // Temp to hold top 10 words for each user
+ List<WordCount> wordUsage = new LinkedList<>(); // Temp for user vocab
+
+ System.out.println(""Preparing data for report ...""); // Log system status
+ for(MyString mHandle : mailboxHandles) // Find each user's mailbox address
+ { // Locate associated user's vocab list
+ int i = 0;
+ wordUsage = wordUsages.get(mHandle);
+ for(i = 0; i < 10; i++) // ... fill its first 10 words
+ {
+ wordUsage.set(i, wordUsages.get(mHandle).get(i));
+ }
+ while (wordUsage.get(i).getCount() == wordUsage.get(9).getCount()) // ... get words with same count as 10th word ...
+ {
+ result.get(mHandle).set(i, wordUsage.get(i)); // ... then add any such word to the sub-list
+ i++;
+ }
+ wordUsage.sort(WordCount::compareByCountThenWord); // Finally re-sort wordUsageTops by count and then word ...
+ wordUsage.subList(10, wordUsage.size()).clear(); // Trim list to first 10 elements
+ result.put(mHandle, wordUsage); // ... and update
+ }
+ return result;",,,,,,,,,,,,,,,
+403211,1,,,1/2/2020 19:47,,5,4172,"I wanted to know what fellow developers follow while designing rest API error responses.
+
+For all the not-found get resources, do you also send the some sort of body indicating that resource was not found or some more detailed level error messages or only error code with null or blank response?
+",254574,,,,,44207.89028,Should 404 response include body,,4,7,2,,,CC BY-SA 4.0,
+403213,1,403276,,1/2/2020 20:03,,1,90,"I have an external data model framework with frequent updates to the names of fields. Say for an iteration I implement on
+
+- EnterpriseModelObject
+-- EnterpriseDomainContentList
+--- EnterpriseDomainContent
+-- ContentDeliveryResult
+--- ErrorList
+---- Error
+--- WarningList
+---- Warning
+
+
+Another iteration this will become
+
+- EnterpriseModelObject
+-- EnterpriseContentList
+--- EnterpriseContent
+-- DeliveryResult
+--- EnterpriseErrorList
+---- EnterpriseError
+--- EnterpriseWarningList
+---- EnterpriseWarning
+
+
+I have a number of microservices that require converting a variety of bean types to this model and back. For this I have a library that does the common work but I am still struggling with updates when my bean model changes.
+
+The microservices are implemented to directly use the object names in the model and the library simply provides common conversion methods. So when I start updating the conversion library this breaks the unit tests in the service APIs. Ideally I want to be able to localize all object name changes to my library and the services will return the correct fields without requiring micromanagement.
+
+What kind of approach should I take with the services so that they automatically use the updates without compilation or unit test issues?
+",,user313675,,user313675,43832.85694,43833.90139,API design for data model with frequent field name updates,,1,7,,,,CC BY-SA 4.0,
+403219,1,,,1/3/2020 0:09,,-1,57,"Curious how containers are portable across development/testing/cloud environments with no worry needed about the underlying infrastructure. Does the Docker Engine essentially standardize operating systems to the point where the engine is able to launch the same container from the different operating systems? Or does a cloud deployment environment for the container(s) need to be running Linux if the development environment was also running Linux? Thanks!
+",354158,,,,,43833.07569,Containers Across Operating systems,,1,0,,,,CC BY-SA 4.0,
+403226,1,,,1/3/2020 2:34,,0,93,"I'm starting a project to build an instant messaging application for mobile devices.
+Although not the complete list of components these are the main data flows I'm concerned about:
+
+
+Mobile app conencted to WebSocket -*for message analysis (abusive language / etc) and persistence.
+Mobile app connected to MQTT broker -*for message publishing and message receiving
+Mobile app connected to RESTful API -* for businness handling (balance check, token expiring, purchases, friend lists, user profile) **the different APIS can be distributed
+
+
+Let me explain my concern:
+I want to save as much bandwidth as possible. Obviously I would prefer to have the least amount of channels but at the same time I can't just have an open connection to the message broker I need business logic in place for each message.
+
+Because I don't want to sacrifice delivery speed I decided to have a separate channel for analysis and for message publishing (WebSocket and MQTT over TCP) instead of sending everything through websocket, and another one for business, like blocking a user, purchases, etc. (RESTful API), so based on the response from the REST API every so often I would apply some logic for sending messages.
+
+What do you think of this approach? Do you have any suggestions?
+",354160,,,,,43833.28681,Architecture question about Instant Messaging Platform with MQTT,,1,0,,,,CC BY-SA 4.0,
+403227,1,403249,,1/3/2020 3:16,,3,398,"Gang of Four’s Flyweight design pattern introduces the concept of intrinsic and extrinsic states:
+
+
+ The key concept here is the distinction between intrinsic and extrinsic state. Intrinsic state is stored in the flyweight; it consists of information that’s independent of the flyweight’s context, thereby making it sharable. Extrinsic state depends on and varies with the flyweight’s context and therefore can’t be shared. Client objects are responsible for passing extrinsic state to the flyweight when it needs it.
+
+
+In other words, the state of an object can be decomposed with respect to a group of objects as an intrinsic state and an extrinsic state, where the intrinsic state is the intersection of the states of all objects of the group and the extrinsic state is the difference of the state of the object and the intrinsic state. Since the intrinsic state is duplicated in each object of the group, space can be saved by replacing the group of objects by a single flyweight object storing a single intrinsic state. The flyweight object cannot however store the multiple extrinsic states of the objects of the group, so the extrinsic states are stored outside and passed to the flyweight object in each request from client objects. Such an optimised communication protocol is often called a stateless protocol since the flyweight object does not store extrinsic state. Examples of stateless protocols include IP and HTTP (and more generally any REST protocols, where intrinsic state is called resource state and extrinsic state is called application state).
+
+For instance, let’s take three objects with their respective clients:
+
+
+ o1 ← c1
+ o2 ← c2
+ o3 ← c3
+
+
+We can decompose the state of each object with respect to the three objects:
+
+
+ state 1 = intrinsic state ∪ extrinsic state 1
+ state 2 = intrinsic state ∪ extrinsic state 2
+ state 3 = intrinsic state ∪ extrinsic state 3
+
+ where:
+
+ intrinsic state = state 1 ∩ state 2 ∩ state 3
+ extrinsic state 1 = state 1 \ intrinsic state
+ extrinsic state 2 = state 2 \ intrinsic state
+ extrinsic state 3 = state 3 \ intrinsic state
+
+
+Here the intrinsic state is duplicated. So storing it in a single flyweight object (and moving the extrinsic states into clients) saves space:
+
+
+ o ← c1, c2, c3
+
+
+So far so good. Now I have been wondering if it is possible to classify attributes as intrinsic state or extrinsic state from the definition of an unshared class, in order to derive a flyweight class.
+
+Is the following syntactic characterisation of intrinsic and extrinsic state for unshared classes correct?
+
+
+- intrinsic state = immutable instance variables ∪ class variables;
+- extrinsic state = mutable instance variables.
+
+
+For instance, let’s define the following unshared class:
+
+class Unshared:
+ __z = 0
+
+ def __init__(self):
+ self.__x = 0
+ self.__y = 0
+
+ def f(self):
+ return self.__x + self.__y
+
+ def g(self):
+ self.__y += 1
+
+ @classmethod
+ def h(cls):
+ cls.__z += 1
+
+
+The proposed characterisation would yield:
+
+
+- intrinsic state = {
__x, __z};
+- extrinsic state = {
__y}.
+
+
+which seems correct. That unshared class can then be transformed into a flyweight class for saving space:
+
+class Flyweight:
+ __z = 0
+
+ def __init__(self):
+ self.__x = 0
+
+ def f(self, y):
+ return self.__x + y
+
+ @classmethod
+ def h(cls):
+ cls.__z += 1
+
+
+Edit
+
+My characterisation was incomplete, as noted by @DocBrown, because it prevented mutable flyweight objects, by excluding mutable instance variables that are instance or class specific from the intrinsic state. And it also incorrectly included immutable instance variables that are instance specific in the intrinsic state.
+
+Let’s define the following terms:
+
+
+- A group is a set of unshared objects from which a single flyweight object is derived.
+- An instance-scope instance variable is an instance variable that is specific to an individual object.
+- A lesser-group-scope instance variable is an instance variable that is common to a smaller group of unshared objects than the group under consideration.
+- A group-scope instance variable is an instance variable that is common to the group of unshared objects under consideration.
+- An greater-group-scope instance variable is an instance variable that is common to a larger group of unshared objects than the group under consideration.
+- A class-scope instance variable is an instance variable that is common to all objects.
+
+
+An instance-scope instance variable and a lesser-group-scope instance variable are not sharable by the group of unshared objects under consideration, while a group-scope instance variable, greater-group-scope instance variable, a class-scope instance variable and a class variable are sharable by the group of unshared objects under consideration.
+
+We can conclude that the complete characterisation of intrinsic and extrinsic state for unshared classes is the following:
+
+
+- intrinsic state = group-scope instance variables ∪ greater-group-scope instance variables ∪ class-scope instance variables ∪ class variables;
+- extrinsic state = instance-scope instance variables ∪ lesser-group-scope instance variables.
+
+
+However as @DocBrown rightly pointed, this characterisation is not purely syntactic. Class variables, class-scope instance variables and some mutable instance-scope instance variables can be identified syntactically just by looking at the unshared class definition. But greater-group-scope instance variables, group-scope instance variables, lesser-group-scope instance variables, immutable instance-scope instance variables and mutable instance-scope instance variables can only be identified semantically.
+
+When deriving a flyweight class from an unshared class, its instance-scope instance variables and lesser-group-scope instance variables are moved outside of the flyweight class, its group-scope instance variables become instance-scope instance variables of the flyweight class, its greater-group-scope instance variables are moved outside of the flyweight class, its class-scope instance variables remain class-scope instance variables of the flyweight class, and its class variables remain class variables of the flyweight class.
+
+For instance, let’s define the following unshared class:
+
+import collections
+
+class Unshared:
+ __L = 0 # immutable class variable
+ __instances = collections.defaultdict(list) # mutable class variable
+
+ def __init__(self, GROUP, I, i, j, k):
+ self.__instances[GROUP].append(self)
+ self.__GROUP = GROUP # immutable group-scope instance variable
+ self.__I = I # immutable instance-scope instance variable
+ self.__i = i # mutable instance-scope instance variable
+ for instance in self.__instances[GROUP]:
+ instance.__j = j # mutable group-scope instance variable
+ self.__K = 0 # immutable class-scope instance variable
+ for instances in self.__instances.values():
+ for instance in instances:
+ instance.__k = k # mutable class-scope instance variable
+
+ def query(self):
+ return {
+ ""instance"": [self.__I, self.__i],
+ ""group"": [self.__GROUP, self.__j],
+ ""class"": [self.__K, self.__k, self.__L, tuple(self.__instances)]
+ }
+
+ def manipulate(self):
+ # Update the mutable instance-scope variables.
+ self.__i = None
+ # Update the mutable group-scope variables.
+ for instance in self.__instances[self.__GROUP]:
+ instance.__j = None
+ # Update the mutable class-scope variables.
+ for instances in self.__instances.values():
+ for instance in instances:
+ instance.__k = None
+ self.__instances[None] = []
+
+
+The new characterisation yields:
+
+
+- intrinsic state = {
__GROUP, __j, __K, __k, __L, __instances};
+- extrinsic state = {
__I, __i}.
+
+
+That unshared class can then be transformed into a flyweight class for saving space:
+
+class Flyweight:
+ __L = 0
+ __instances = {}
+
+ def __init__(self, GROUP, j, k):
+ self.__instances[GROUP] = self
+ self.__GROUP = GROUP
+ self.__j = j
+ self.__K = 0
+ for instance in self.__instances.values():
+ instance.__k = k
+
+ def query(self, I, i):
+ return {
+ ""instance"": [I, i],
+ ""group"": [self.__GROUP, self.__j],
+ ""class"": [self.__K, self.__k, self.__L, tuple(self.__instances)]
+ }
+
+ def manipulate(self):
+ # Update the mutable group-scope variables.
+ self.__j = None
+ # Update the mutable class-scope variables.
+ for instance in self.__instances.values():
+ instance.__k = None
+ self.__instances[None] = []
+
+
+Unshared class usage:
+
+ra1 = Unshared(""a"", 1, 1, 1, 0) # unshared instance of group ""a""
+ra2 = Unshared(""a"", 2, 2, 1, 0) # unshared instance of group ""a""
+rb1 = Unshared(""b"", 1, 1, 2, 0) # unshared instance of group ""b""
+rb2 = Unshared(""b"", 2, 2, 2, 0) # unshared instance of group ""b""
+
+print(ra1.query()) # {""instance"": [1, 1], ""group"": [""a"", 1], ""class"": [0, 0, 0, (""a"", ""b"")]}
+print(ra2.query()) # {""instance"": [2, 2], ""group"": [""a"", 1], ""class"": [0, 0, 0, (""a"", ""b"")]}
+print(rb1.query()) # {""instance"": [1, 1], ""group"": [""b"", 2], ""class"": [0, 0, 0, (""a"", ""b"")]}
+print(rb2.query()) # {""instance"": [2, 2], ""group"": [""b"", 2], ""class"": [0, 0, 0, (""a"", ""b"")]}
+ra1.manipulate()
+print(ra1.query()) # {""instance"": [1, None], ""group"": [""a"", None], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+print(ra2.query()) # {""instance"": [2, 2], ""group"": [""a"", None], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+print(rb1.query()) # {""instance"": [1, 1], ""group"": [""b"", 2], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+print(rb2.query()) # {""instance"": [2, 2], ""group"": [""b"", 2], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+
+
+Flyweight class usage:
+
+fa = Flyweight(""a"", 1, 0) # shared instance of group ""a""
+fb = Flyweight(""b"", 2, 0) # shared instance of group ""b""
+
+print(fa.query(1, 1)) # {""instance"": [1, 1], ""group"": [""a"", 1], ""class"": [0, 0, 0, (""a"", ""b"")]}
+print(fa.query(2, 2)) # {""instance"": [2, 2], ""group"": [""a"", 1], ""class"": [0, 0, 0, (""a"", ""b"")]}
+print(fb.query(1, 1)) # {""instance"": [1, 1], ""group"": [""b"", 2], ""class"": [0, 0, 0, (""a"", ""b"")]}
+print(fb.query(2, 2)) # {""instance"": [2, 2], ""group"": [""b"", 2], ""class"": [0, 0, 0, (""a"", ""b"")]}
+fa.manipulate()
+print(fa.query(1, None)) # {""instance"": [1, None], ""group"": [""a"", None], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+print(fa.query(2, 2)) # {""instance"": [2, 2], ""group"": [""a"", None], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+print(fb.query(1, 1)) # {""instance"": [1, 1], ""group"": [""b"", 2], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+print(fb.query(2, 2)) # {""instance"": [2, 2], ""group"": [""b"", 2], ""class"": [0, None, 0, (""a"", ""b"", None)]}
+
+",184279,,184279,,43954.49792,43954.49792,Syntactic characterisation of intrinsic and extrinsic states,,2,6,0,,,CC BY-SA 4.0,
+403228,1,,,1/3/2020 4:03,,21,7918,"I am making a full-stack web application for a professor. At his request, the passwords and usernames are generated programmatically, and they cannot be changed or reset by the students. (If you forget your password, you ask the professor, who can look it up.) Does this tightly-controlled system eliminate the need to do all of the normal best practices with regard to storing passwords in a database?
+
+In case it's relevant, the app does not contain any association or identifiers between the student's identifying information (name, gender, etc.) and their username and password.
+
+
+
+EDIT 1: Thank you for the many responses. This is very helpful to me as I didn't take the traditional route to this career and have some holes in my knowledge that probably seem fundamental to you. Here are a few points of clarification:
+
+
+- I am a freelancer on my first-ever freelancing project, and the client/customer is a professor. I am not his student, and this is not an assignment.
+- My task is to replace an existing application that is very old and for which the source code is lost.
+- The application is used in a class taught by several professors in different schools in the US. Much of the content is just static, like a textbook. However you can also take some questionnaires/instruments developed by the professors to get insight into the topic of the course relative to a real-world example of your choosing (i.e., the information you supply is not about yourself or other people).
+- My original goals in having username/passwords was to identify users so that I could enforce expiration of access to the content, and also control permissions. Permissions matter because in addition to students, there is the concept of administrator users (who have a dashboard where they can view lists of username/passwords they have created, and create more) and a super-admin (who in addition to what admins can do, can create other admin users).
+- The primary reason I started down the path of username and login is because that is what the old app had. But, the old app stored (lots!) of student information. The professor in charge now does not want to go afoul of FERPA laws so he has changed the requirements there.
+- A professor can create another username/password set and add it to the current class if needed. But they aren't forced to currently. (They can just give out the original password.) This was the professor's decision when I asked him if he wanted a ""reset password"" button on the list.
+
+",241967,,241967,,43836.85,43836.85,Is this scenario an exception to the rule of never storing passwords in plaintext?,,9,10,4,,,CC BY-SA 4.0,
+403234,1,,,1/3/2020 7:35,,-1,90,"I have googled enough for days but i cant find a clear intuitive document about this embedding technique.
+In their paper they say : We present StarSpace, a general-purpose neural embedding model that can solve a wide variety of problems.
+But they don't explain how. Thanks in advance.
+",354178,,,,,43833.37292,Can somone explain facebook starspace?,,1,0,,,,CC BY-SA 4.0,
+403238,1,,,1/3/2020 9:55,,6,476,"Tennis is played as singles or doubles. I considered making my tennis scoring model logic refer to ""teams"" throughout its naming since ""player"" wouldn't take into account doubles. However, seeing teamOne and teamTwo throughout the code to accommodate both modes seems awkward since a team of one person doesn't make sense and the sport is usually played as singles.
+
+What would be a good way to reconcile this? I try to adhere to the Swift API Design Guidelines since it's the language I'm using. Maybe I'm bikeshedding and I should just go with teamOne and teamTwo even if it's imprecise?
+",267972,,267972,,44089.02222,44095.82361,What is a good approach to naming when modeling a sport that can be between either individuals or teams?,,5,9,,,,CC BY-SA 4.0,
+403239,1,,,1/3/2020 10:19,,0,55,"I'm working with a project that uses ASP.NET Core 2.2. The main solution contains different projects, including APIs for a mobile application, APIs to integrate the system with third parties, a web application, etc.
+
+
+- Mobile API - For internal application
+- Public API - To integrate our system with others
+- Web - Website
+
+
+We're using token-based authentication for mobile API project. However, to expose our Public APIs for third parties, we don't want to use token-based authentication, instead, we decided to use the key - secret.
+
+But the issue is that another project (integration to use our system internally) has its registered users and they don't want to create an account in our system. I suspect that, in this case, key-secret things wouldn't work. We currently use api-key for every project(tenant), and they have to keep api-key for their users. However, this could create security issues if we expose API endpoints publicly.
+
+Along with this, we'd like to track request per user too.
+
+What type of authentication solves this problem? and how can we handle such a scenario?
+",241751,,241751,,43833.43611,43833.43611,Which authentication should be used for external users (not registered with the system),,0,11,,,,CC BY-SA 4.0,
+403248,1,403290,,1/3/2020 14:56,,0,560,"I have queue of MoveableItems in a class BackgroundTaskQueue (based on example from Microsoft here). Clients call BackgroundTaskQueue.QueueBackgroundWorkItem to add a MoveableItem to the queue.
+
+An instance of BackgroundTaskQueue is passed to a class QueuedHostedService (which is also based on this). QueuedHostedService processes the queue on a separate thread to the enqueue action.
+
+The BackgroundTaskQueue.DequeueAsync method blocks on a SemaphoreSlim (due to async).
+When a client calls BackgroundTaskQueue.QueueBackgroundWorkItem method it queues the MoveableItem and signals (releases) the semaphore. QueuedHostedService then processes the MoveableItem
+
+Clients of would like to know all MoveableItem that are incomplete (defined as all items remaining in the queue and the currently processing item).
+
+What suggested approaches exist to ensure Clients get an accurate audit of the incomplete items while Clients could be concurrently enqueuing items and asking for IncompleteItems, while Bar is concurrently dequeuing?
+
+Problem I found is if I use another SemaphoreSlim in Bar as a mutex to ensure thread-safety of the Incomplete-Items list, then I get a deadlock race-condition - this happens when Bar is in the processing loop, its thread would claim the mutex-semaphore for protecting Incomplete-Items, then Bar calls Foo.Dequeue and blocks Foo's signalling-semaphore while it is waiting for a new item. At this point Bar has claimed the mutex and is blocked waiting for the enqueue signal. If a Client thread asks for the list of Incomplete Items it would attempt to claim Bar's mutex-semaphore and can't because it is held by Bar's queue processing thread.
+
+public interface IBackgroundTaskQueue
+{
+ IList<MoveableItem> Items { get; }
+
+ void QueueBackgroundWorkItem(MoveableItem moveableItem);
+
+ Task<MoveableItem> DequeueAsync(
+ CancellationToken cancellationToken);
+}
+
+public class BackgroundTaskQueue : IBackgroundTaskQueue
+{
+ private ConcurrentQueue<MoveableItem> _workItems =
+ new ConcurrentQueue<MoveableItem>();
+ private SemaphoreSlim _signal = new SemaphoreSlim(0);
+ private readonly ILogger _log;
+
+ public BackgroundTaskQueue(ILogger<BackgroundTaskQueue> logger)
+ {
+ _log = logger;
+ }
+
+ public void QueueBackgroundWorkItem(MoveableItem moveableItem)
+ {
+ if (moveableItem == null)
+ {
+ throw new ArgumentNullException(nameof(moveableItem));
+ }
+
+ _workItems.Enqueue(moveableItem);
+ _signal.Release();
+ _log.LogDebug($""{nameof(_signal)} release {nameof(QueueBackgroundWorkItem)}"");
+ }
+
+ public async Task<MoveableItem> DequeueAsync(
+ CancellationToken cancellationToken)
+ {
+ _log.LogDebug($""{nameof(_signal)} waiting async {nameof(QueueBackgroundWorkItem)}"");
+
+ await _signal.WaitAsync(cancellationToken);
+
+ _log.LogDebug($""{nameof(_signal)} running {nameof(QueueBackgroundWorkItem)}"");
+
+ _workItems.TryDequeue(out var workItem);
+
+ return workItem;
+ }
+
+ public bool IsEmpty()
+ {
+ return _workItems.IsEmpty;
+ }
+
+ public IList<MoveableItem> Items { get => _workItems.ToList(); }
+}
+
+
+public class QueuedHostedService : BackgroundService
+{
+ private readonly ILogger _logger;
+ private volatile MoveableItem _inProgressItem;
+ private volatile IList<MoveableItem> _incompleteItems = new List<MoveableItem>();
+ private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
+ private readonly IBackgroundTaskQueue _taskQueue;
+
+ public QueuedHostedService(IBackgroundTaskQueue taskQueue,
+ ILogger<QueuedHostedService> logger)
+ {
+ _taskQueue = taskQueue;
+ _logger = logger;
+ }
+
+ public override void Dispose()
+ {
+ _semaphore?.Dispose();
+ base.Dispose();
+ }
+
+ public MoveableItem InProgressItem { get => _inProgressItem; private set => _inProgressItem = value; }
+
+ public IList<MoveableItem> GetItems()
+ {
+ _logger.LogDebug($""{nameof(_semaphore)} waiting GetItems"");
+ _semaphore.Wait();
+ _logger.LogDebug($""{nameof(_semaphore)} running GetItems"");
+
+ try
+ {
+ return _incompleteItems;
+ }
+ finally
+ {
+ _semaphore.Release(1);
+ _logger.LogDebug($""{nameof(_semaphore)} release GetItems"");
+ }
+
+ }
+
+ protected async override Task ExecuteAsync(
+ CancellationToken cancellationToken)
+ {
+ _logger.LogInformation(""Queued Hosted Service is starting."");
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ MoveableItem moveableItem;
+
+ moveableItem = await _taskQueue.DequeueAsync(cancellationToken);
+ InProgressItem = moveableItem;
+
+ _logger.LogDebug($""{nameof(_semaphore)} waiting ExecuteAsync StoreList"");
+ _semaphore.Wait();
+ _logger.LogDebug($""{nameof(_semaphore)} running ExecuteAsync StoreList"");
+
+ try
+ {
+ var items = new List<MoveableItem>();
+ if (InProgressItem != null)
+ {
+ items.Add(InProgressItem);
+ }
+ items.AddRange(_taskQueue.Items);
+ _incompleteItems = items;
+
+ }
+ finally
+ {
+ _semaphore.Release();
+ _logger.LogDebug($""{nameof(_semaphore)} release ExecuteAsync StoreList"");
+ }
+
+ try
+ {
+ // Do Stuff
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex,
+ $""Error occurred moviing {moveableItem}."");
+ }
+ finally
+ {
+ _logger.LogDebug($""{nameof(_semaphore)} waiting ExecuteAsync null"");
+ _semaphore.Wait();
+ _logger.LogDebug($""{nameof(_semaphore)} running ExecuteAsync null"");
+
+ try
+ {
+ InProgressItem = null;
+ }
+ finally
+ {
+ _semaphore.Release();
+ _logger.LogDebug($""{nameof(_semaphore)} release ExecuteAsync null"");
+ }
+ }
+ }
+
+
+ _logger.LogInformation(""Queued Hosted Service is stopping."");
+ }
+}
+
+",297242,,297242,,43834.15833,43834.17986,How to avoid deadlock,,2,4,,,,CC BY-SA 4.0,
+403250,1,403254,,1/3/2020 15:21,,1,574,"public class B { }
+public class C { }
+public class D { }
+public class E { }
+
+public class A :
+ IRetrievable<B, C>,
+ IRetrievable<D, E>
+{
+ public TValue Retrieve<TKey, TValue>(TKey input)
+ {
+ throw new NotImplementedException();
+ }
+}
+
+
+What is the reason I can't do this? Visual Studio is telling me that the interfaces aren't being implemented, even though they could be via putting types B, C and D, E in TKey, TValue, respectively.
+",354214,,,,,43833.66458,Why can't I use a generic method to implement multiple typed interfaces in C#?,,2,4,1,,,CC BY-SA 4.0,
+403251,1,403252,,1/3/2020 15:23,,8,8091,"I'm building an API endpoint for a UI grid to search, filter, and display a list of domain objects, let's call them ""widgets."" In the past, I would have built this with a list of named query string parameters, like this:
+
+GET /api/v1/widgets?type=2&name=what&from=2019-12-31&to=2020-01-03&pagesize=25&page=2&sort=name,-createdate
+
+
+This would result in SQL something like
+
+SELECT <selectlist>
+FROM widget
+WHERE type = 2
+ AND name LIKE 'what%'
+ AND createdate >= '2019-12-31'
+ AND createdate <= '2020-01-03'
+ORDER BY name ASC, createdate DESC
+LIMIT 25, 25;
+
+
+I've had a co-worker propose that instead of a long list of parameters, we pass a couple of JSON objects on the query string, like this:
+
+""filters"": {
+ { ""column"": ""type"", ""operator"": ""="", ""value"": 2 },
+ { ""column"": ""name"", ""operator"": ""like"", ""value"": ""what"" },
+ { ""column"": ""createdate"", ""operator"": "">="", ""value"": ""2019-12-31"" },
+ { ""column"": ""createdate"", ""operator"": ""<="", ""value"": ""2020-01-03"" }
+},
+""pagination"": {
+ ""page"": ""2"",
+ ""pagesize"": ""25"",
+ ""sort"": [ ""name"", ""createdate"" ],
+ ""sortdirection"": [ ""asc"", ""desc"" ]
+}
+
+
+Which, after encoding, looks something like this as a URL (sorry if I messed up the encoding, I made this up as an example):
+
+GET /api/v1/widgets?filters=[%7B%22column%22:%22type%22,%22operator%22:%22%3D%22,%22value%22:2%7D,%7B%22column%22:%22name%22,%22operator%22:%22like%22,%22value%22:%22what%22%7D,%7B%22column%22:%22createdate%22,%22operator%22:%22%3E%3D%22,%22value%22:%222019-12-31%22%7D,%7B%22column%22:%22createdate%22,%22operator%22:%22%3C%3D%22,%22value%22:%222020-01-03%22%7D]&pagination=%7B%22page%22:%222%22,%22pagesize%22:%2225%22,%22sort%22:[%22name%22,%22createdate%22],%22sortdirection%22:[%22asc%22,%22desc%22]%7D
+
+
+We are in JavaScript on both client and server, so parsing the JSON object is not a difficult task. And I realize that the structure of the JSON object for querying would have to be altered, as it does not account for some things. Disregarding that, the basic question is:
+
+Is this a bad/good idea? I see advantages and disadvantages, but I'm trying to look past my personal bias.
+",3266,,3266,,43833.72708,43836.14236,"Is it a bad idea to pass JSON objects on the query string for an API ""search"" operation?",,4,6,1,,,CC BY-SA 4.0,
+403258,1,403266,,1/3/2020 17:04,,3,177,"I’ve been trying to get a firm understanding of the MVC design pattern so that I can write my own framework for implementing the back-end of a forum web application using Slim 3. In particular, after reading this, and asking this and this question myself I’m now at a point where I think I understand how the model should be a layer composed of data mappers, services and domain objects. However I have some more questions regarding domain objects.
+
+At the moment with a very similar structure from an answer given to this question I asked. I have a basic model layer structure for registering a user to my forum application. However it seems to me that my User ‘domain object’ isn’t really doing anything at the moment, it only has getters and setters and I could probably do without it.
+
+User domain object:
+
+class User
+{
+ private $id;
+ private $email;
+ private $username;
+ private $password;
+
+ public function __construct(Email $email, Username $username, Password $password)
+ {
+ $this->email = $email;
+ $this->username = $username;
+ $this->password = $password;
+ }
+
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ public function setId(int $id)
+ {
+ $this->id = $id;
+ }
+
+ public function getEmail()
+ {
+ return $this->email;
+ }
+
+ public function setEmail(Email $email)
+ {
+ $this->email = $email;
+ }
+
+ public function getUsername()
+ {
+ return $this->username;
+ }
+
+ public function setUsername(Username $username)
+ {
+ $this->username = $username;
+ }
+
+ public function getPassword()
+ {
+ return $this->password;
+ }
+
+ public function setPassword(Password $password)
+ {
+ $this->password = $password;
+ }
+}
+
+
+This user domain object directly mirrors that of my ‘user’ SQL table that is populated when a user registers. In fact this created user domain object is passed to my data mapper then the fields of the passed in user object are extracted and inserted into the database.
+
+Inserting a user object into my ‘user’ table:
+
+ private function insertUser(User $user)
+ {
+ $sql = 'INSERT INTO users (email, username, password)
+ VALUES (:email, :username, :password)';
+
+ $statement = $this->connection->prepare($sql);
+ $statement->execute([':email' => $user->getEmail(),
+ ':username' => $user->getUsername(),
+ ':password' => $user->getPassword()]);
+
+ $user->setId($this->connection->lastInsertId());
+
+ return $user;
+ }
+
+
+Could I not just directly pass in the strings that the user typed into the form (after validation and sanitation) instead of having to create this user domain object. It just seems unnecessary at the moment.
+
+This is where I’m confused as to what exactly a domain object should be. I understand they should encompass business logic, but identifying what business logic I would need for a forum application is proving difficult. For example I would like each user to have their own profile page that is publicly visible, that they can only edit and update when the user in question is logged in.
+
+Would I need to create a ‘profile’ domain object together with a new profile table that links to my original user table and user domain object? Or could I simply extend my existing user table and user domain object to have properties and methods that can allow a user to display and update their profile?
+
+I understand this is a matter of design and can be subjective, but some advice on what should be in a domain object (especially for the previous example with a profile) and if they need to marry up to a table or not would be helpful.
+
+A lot of the tutorials I see such as this, simply have a single model object that has data mappers methods in them which doesn’t seem right. A lot of tutorials also use frameworks that utilise ORM which is something I’m trying to avoid using as I want to write everything from scratch, although I’m fine with using Slim 3 / 4 PHP.
+",354228,,354228,,43833.72569,43833.80694,What domain objects might I need to represent a user and users profile in a forum web application,,1,0,,,,CC BY-SA 4.0,
+403264,1,403270,,1/3/2020 18:53,,8,217,"I am trying to draw diagrams that show the difference between system virtual machines and Java virtual machines.
+
+The first two images looks correct to me. But I don't know how to draw the third.
+
+Image 1:
+
+
+
+Image 2:
+
+
+
+Image 3:
+
+
+
+As you see, both red blocks and gray frames have the same captions: ""JVM"". I don't think it is correct. I'm sure that caption should be different: ""JVM"" for gray frames and ""something different"" for red blocks.
+
+How the third diagram should be fixed?
+",215211,,215211,,43833.79583,43834.6375,To show the difference between system VMs and JVMs,,1,2,,,,CC BY-SA 4.0,
+403271,1,403272,,1/3/2020 20:03,,1,368,"My questions are regarding the use of mysqli::rollback.
+
+If not used in a declared transaction but used in a try...catch will rollback do anything at all? (autocommit on)
+
+If it does work without a transaction being declared is rollback necessary for single query statements? See example below...
+
+try{
+ $sql = ""DELETE FROM users WHERE user_id=?"";
+ $row = run($mysqli, $sql, [$user_id]);
+}catch(exception $e){
+ $mysqli->rollback();
+ error($mysqli);
+}
+
+
+If I have a transaction declared with multiple queries and all queries in the transaction fail, will rollback affect an older transaction? What is the scope of rollback?
+",352360,,1204,,43833.84792,43857.42431,If not used in a declared transaction but used in a try...catch will rollback do anything at all?,,2,0,,,,CC BY-SA 4.0,
+403273,1,,,1/3/2020 20:43,,1,63,"A site I'm working on tracks users before they sign up or log in to determine things like which pages drive the most users to sign up for the service, etc.
+
+Currently we make use of a browser fingerprinting library. We fingerprint the browser, save the result in a cookie, and use this cookie to uniquely determine users. However, many browsers end up computing the same fingerprint as other browsers. eg. We see a lot of the same fingerprint from Safari on an iPad, even though it's distinct iPads.
+
+We only use the fingerprint on our own first-party site, so I'm thinking that perhaps fingerprinting wasn't even the correct approach to begin with. I'm thinking of switching to a system where the server hands out unique tokens to each client. The client would store the received token as a cookie in place of the old fingerprint, and if it already has one of these server-side created tokens, then it ignores the new one, or maybe doesn't request it in the first place.
+
+Does this plan make sense? Am I overlooking anything obvious?
+
+I'm aware that inclined users can read though our client side code and change the values of their cookies to mess with us. I'm not worried about that small percentage of users, this is to get a broad picture of what's going on with the site.
+",39699,,,,,43833.925,Tracking non-logged-in users,,2,1,,,,CC BY-SA 4.0,
+403274,1,,,1/3/2020 20:49,,0,584,"We currently have a requirement to build a multi-tenant application that has cross-tenant users. That is the business data is separated by tenant but users can belong to multiple tenants and should have access to all of the data for each of their tenants. My question is does this even make sense? And if so, how can we handle login for this scenario using OpenID Connect? When I've done multi-tenancy using OpenID Connect in the past, the tenantId has been part of the login. The given requirement complicates things significantly. Should I push back? The reason for the requirement is primarily to prevent users belonging to multiple tenants from having to have multiple logins. Thoughts?
+",307498,,209774,,43833.95556,43834.02708,Multitenancy with Cross-Tenant Users,,2,22,,,,CC BY-SA 4.0,
+403280,1,403284,,1/3/2020 22:30,,-5,40,"How can I discover and master the technical system of an ERP and/or a framework published by the company that has just hired me?
+
+For example: is it useful to draw UML diagrams on paper (and if so, which ones?)? What notes on paper to take?
+",310712,,,,,43833.97014,How can I discover and master the technical system of an ERP and/or a framework published by the company that has just hired me?,,1,3,,43834.41806,,CC BY-SA 4.0,
+403283,1,403286,,1/3/2020 23:07,,1,47,"Consider the following Activity Diagram :
+
+
+
+First of all the activity a22 is confusing me through this configuration .If we need to list all the possible activity sequences that can take place in this activity diagram. My answer is as follows :
+
+Sequence one : a11 ; parallel combination of a22 , a33 and a44 ;a77.
+
+Sequence two : a11 ;parallel combination of a22 , a33 and a44 ; parallel combination of a55 and a66.
+
+Is this a right answer ?
+",331812,,331812,,43833.96944,43834.025,Fork and Join in Activity Diagram,,1,0,0,,,CC BY-SA 4.0,
+403285,1,,,1/3/2020 23:26,,-1,113,"I usually do Javascript and I like putting console.assert liberally in my application. It throws an error if the first argument is falsey. E.g.:
+
+console.assert(price > 0, 'Price isn\'t above 0')
+
+It's easy to automatically remove this for production builds. When developing, I often accidentally break an assertion. I think this is better than unit tests, at least during the early stages of development, because:
+
+
+development application state is more realistic than test states
+assertions are easier to write, so developers will write more of them
+
+
+Also, for a big enough application, I think it'll be good to keep the assertions in production for 1% of users. It's better to have it fail for 1% of users than to have silent errors for everyone.
+
+However, I've never seen any tech companies do this. Why is that?
+",315965,,,,,43834.21875,Why don't people usually use asserts throughout their application?,,2,3,,,,CC BY-SA 4.0,
+403289,1,403302,,1/4/2020 4:16,,0,199,"Probably the answer is you can't. However, I would like to have a work-around to solve my problem.
+
+Objective
+
+I am trying to create a program in which I try to avoid nulls as much as possible.
+
+Problem
+
+I am using the empty object pattern in places where null could have been returned. Like this:
+
+public User GetByEmail(string email){
+ //search user on database given unique email
+ if(!WasFound())
+ return User.Empty;
+}
+
+
+and here is the User Domain model.
+
+//User has more fields but for simplicity I omitted them
+public class User {
+ public User(string username,string email){
+ this.Username = username;
+ this.Email = email;
+ }
+
+ //...
+
+ //probaly not the best default values but I trivially chose them for explanation.
+ private static readonly User _empty = new User(""*"",""na@empty.com"");
+ public static User Empty{
+ get{return _empty;}
+ }
+}
+
+
+So far so good. However, I am planning that the static Empty function be implemented by the majority of my domain models. Also, Someone else might create a domain and I want to force them to implement the Empty function. So I created a DataModel class that will be the base of all domain Models.
+
+public abstract class DataModel<TModel>: BaseEntity, IEmptiable<TModel> where TModel : new()
+ {
+ private bool _isEmpty = false;
+
+ public virtual static TModel Empty {
+ get {
+ _isEmpty = true;
+ return CreateEmpty();
+ }
+ }
+
+ public virtual bool IsEmpty() => _isEmpty;
+
+ protected abstract TModel CreateEmpty();
+ }
+
+
+And my new User class would look like this.
+
+public class User: DataModel<User> {
+ public User(string username,string email){
+ this.Username = username;
+ this.Email = email;
+ }
+
+ //...
+
+ private readonly User _empty = new User(""*"",na@empty.com);
+ protected User CreateEmpty(){
+ return _empty;
+ }
+}
+
+
+In that way I am forcing the developer to implement a CreateEmpty() class and the Empty function will be present in the domain if you extend the DataModel abstract class.
+My problem is that Empty function is static and is giving me many problems.
+Is there a work-around to this problem? My vision is to be able to execute something like:
+
+Account.Empty
+//and to check if is empty with
+if(Account.IsEmpty())
+ //Plan B
+
+
+Keep in mind that this is pseudocode. (I know that static function can't user non-static variables declared outside of the function.)
+
+Any help will be much appreciated.
+",353845,,,,,43851.90139,How to inherit a static function in a class?,,3,7,,,,CC BY-SA 4.0,
+403292,1,,,1/4/2020 4:50,,0,257,"im trying to create a sequence diagram for login , but i dont know if its true or not , maybe the community can help me check , because i see many way to create sequence diagram and its not the same at all ..![]()
+
+Thank you for the help and explanations
+",354264,,,,,43864.45694,Is this right way to create sequence diagram?,,3,3,1,,,CC BY-SA 4.0,
+403294,1,,,1/4/2020 5:38,,0,97,"Linux Onlyoffice Docker scripts are available for download. Are docker containers tied to a particular CPU architecture (IA64 vs ARM)? I would like to run Onlyoffice on an ARM platform (Raspbery Pi 4 or similar SBC computer).
+",251599,,,,,43834.42431,Are Docker images tied to CPU architectures?,,1,3,,,,CC BY-SA 4.0,
+403296,1,,,1/4/2020 5:47,,-1,100,"What do you think about using interfaces just for the sake of enforcing certain naming and patterns across your team? Other than that, it doesn't hold any practical value programmatically.
+
+I'm on the fence on this one because I tend to minimize abstraction whenever possible, but this seems a bit unnecessary. However, it does have some value when it comes to creating variations of certain classes which aren't necessarily related.
+",204609,,110531,,43835.57847,43835.57847,Is it encouraged or discouraged to use interfaces simply to enforce consistency?,,1,2,,,,CC BY-SA 4.0,
+403297,1,403950,,1/4/2020 8:24,,0,785,"We have a set of micro-services that are functionally dependent and have intertwined validation logic. e.g. consider 'Credit-Card' service and 'Loan' service. When user has a credit card then loan shouldn't be given and vice versa. Hence when processing a request we validate across these services using API calls and consider approval of the request. How to handle scenarios when both are initiated simultaneously in distributed systems.
+
+How do we prevent a customer from getting both loan and a credit card at the same time. I am considering using distributed locks to implement a solution. Would like to know if there are other possibilities apart from locks.
+",262713,,262713,,43847.58819,43847.74167,Race condition in Distributed Systems,,2,2,1,,,CC BY-SA 4.0,
+403307,1,403314,,1/4/2020 11:54,,-1,77,"https://docs.microsoft.com/en-us/dotnet/core/tutorials/publishing-with-visual-studio
+
+
+ In Create a Hello World application with .NET Core in Visual Studio, you built a Hello World console application. In
+ Debug your Hello World application with Visual Studio, you tested it using the Visual Studio debugger. Now that
+ you're sure that it works as expected, you can publish it so that other users can run it. Publishing creates the set of
+ files that are needed to run your application. To deploy the files, copy them to the target machine.
+
+
+What do publishing and deployment mean?
+
+
+Is it correct that deployment means that after building/compiling programs in development machines, and packaging, copy the package to the production machine?
+Is it correct that deployment does not include building and packaging?
+Does publishing mean building/compiling programs and packaging on development machines? (I was once asked to ""publish"" (or ""deploy"", I forget which word) created by others. It was
+actually to click a few buttons (I forgot which) in Visual Studio IDE, maybe related
+to the web server, but all this was done on a development machine. It seemed to me to build and package the program.)
+Does publishing not include deployment?
+Do publishing and deployment mean the same?
+
+The above quote seems to say no.
+
+But Publish .NET Core apps with the CLI being a subsection of .NET Core application deployment seems to say yes.
+
+Literally doesn't publishing mean move something to a publicly accessible place? Isn't that the same as deployment?
+
+
+Are the two words standard (or generally used) in software engineering, including outside dotnet e.g. Java, C++, Python, ...? What other standard or popular words that are used instead, if any?
+
+Thanks.
+",699,,699,,43834.54028,43834.70972,Do publishing and deployment mean the same?,,1,12,,,,CC BY-SA 4.0,
+403308,1,403311,,1/4/2020 13:20,,-1,135,"I am creating a small project that implements an interface in Java. I am not allowed to modify the interface, which means I can't change the functions in my class that implements the interface.
+
+However, one of the methods in the class (from the interface) requires a different behaviour in some cases. How do I implement this, in a way that it allows me to adapt the behaviour and make changes to the method without changing the interface?
+",354290,,326536,,43834.74097,43834.74097,How to implement a different behaviour for a method without changing the interface?,,2,7,0,,,CC BY-SA 4.0,
+403310,1,,,1/4/2020 13:34,,2,63,"Assume the flow graph of a function is below (sorry I have forgotten the code of the function):![]()
+
+And when I try to calculate the cyclomatic complexity:
+
+When I use the edge and node to calculate it, V(G)= 9 - 8 + 2 = 3; when I use the branch node to calculate it, V(G) = 3 + 1 = 4. However, when I try to find the independent paths, I think I can find 4 paths:
+
+Path 1: 1 -> 2 -> 6 -> 7
+Path 2: 1 -> 2 -> 6 -> 8
+Path 3: 1 -> 2 -> 3 -> 5 -> 2 -> ...
+Path 4: 1 -> 2 -> 3 -> 4 -> 5 -> 2 -> ...
+
+
+And I wonder which one is correct and what is my mistake? Thanks a lot.
+",354291,,,,,43834.56528,A question about cyclomatic complexity,,0,2,,,,CC BY-SA 4.0,
+403315,1,403321,,1/4/2020 17:08,,2,3863,"We know that the primary actor is the one that initiates a use case and a secondary actor is the one that helps completion of the use case through his specific support. The Primary actor is usually placed at the left side to the boundary of the system and the secondary actor is placed to the right of the boundary of the system. But lets consider a library system where we have two actors , librarian and the reader . Lets consider some specific use cases here :
+
+1) A use case where the library can add books to the library system. In this case the librarian is a primary actor.
+
+2) A use case where the reader borrows a book . More specifically , the reader gives the book that he needs to borrow to the librarian and the librarian scan the book using bar code and enters all the needed info in this system ( reader ID , load time ,....etc ) . In this case the librarian is a secondary actor .
+
+So my question is where to put the librarian in the use case diagram? Right or left to the boundary of the system ? Because in some use cases he is a primary actor and secondary actor in others .
+",331812,,,,,43837.05903,Primary and secondary actors in use case,,3,7,,,,CC BY-SA 4.0,
+403316,1,,,1/4/2020 17:16,,2,389,"I have a Customer which can have sereval address.
+Sereval customers can possibily live at the same address.
+So in my relational database a classic many to many relationship.
+
+As :
+
+
+- An address can not change (a customer can change address);
+- It does not involve any logic with side effect.
+- And the equility between two adress is determine only with the values in it.
+
+
+I argue address is a good candidate to be a value object.
+
+However I need (or maybe not) to persist my customers address and to do so I need to add an Id.
+
+I am a little bit confused and struggled, I think pure domain logic and common sens tell me is a value object but the technology constraint makes that an address has an Id.
+
+Is it fine to store value object?
+",41032,,,,,43834.87014,Is putting an Id to a value object a bad id?,,2,0,,,,CC BY-SA 4.0,
+403318,1,,,1/4/2020 17:46,,105,19541,"I am confused because in quite a few places I've already read that the so-called 'boneheaded' exceptions (ones that result from bugs in code) are not supposed to be caught. Instead, they must be allowed to crash the application:
+
+
+- Vexing exceptions, by Eric Lippert
+- A comment under Eliding Async and Await, by Stephen Cleary
+- Answer below Is it a good practice to use self-defined exception?, by Draco18s no longer trusts SE
+
+
+At least two of the three above people are established authorities.
+
+I am surprised. Especially for some (important!) use cases, like server side code, I simply can't see why is catching such an exception suboptimal and why the application must be allowed to crash.
+
+As far as I'm aware, the typical solution in such a case is to catch the exception, return HTTP 500 to the client, have an automatic system that sends an emergency e-mail to the development team so that they can fix the problem ASAP - but do not crash the application (one request must fail, there's nothing we can do here, but why take the whole service down and make everyone else unable to use our website? Downtime is costly!). Am I incorrect?
+
+Why am I asking - I'm perpetually trying to finish a hobby project, which is a browser based game in .net core. As far as I'm aware, in many cases the framework does for me out of the box the precise thing Eric Lippert and Stephen Cleary are recommending against! - that is, if handling a request throws, the framework automatically catches the exception and prevents the server from crashing. In a few places, however, the framework does not do this. In such places, I am wrapping my own code with try {...} catch {...} to catch all possible 'boneheaded' exceptions.
+
+One of such places, AFAIK, is background tasks. For example, I am now implementing a background ban clearing service that is supposed to clear all expired temporary bans every few minutes. Here, I'm even using a few layers of all-catching try blocks:
+
+try // prevent server from crashing if boneheaded exception occurs here
+{
+ var expiredBans = GetExpiredBans();
+ foreach(var ban in expiredBans)
+ {
+ try // If removing one ban fails, eg because of a boneheaded problem,
+ { // still try to remove other bans
+ RemoveBan(ban);
+ }
+ catch
+ {
+
+ }
+ }
+}
+catch
+{
+
+}
+
+
+(Yes, my catch blocks are empty right now - I am aware that ignoring these exceptions is unacceptable, adding some logging is perpetually on my TODO list)
+
+Having read the articles I linked to above, I can no longer continue doing this without some serious doubt... Am I not shooting myself in the foot? Why / Why not?
+
+If and why should boneheaded exceptions never be caught?
+",212639,,,,,44197.07778,"Why should 'boneheaded' exceptions not be caught, especially in server code?",,17,30,44,,,CC BY-SA 4.0,
+403324,1,,,1/4/2020 20:41,,-1,63,"Here is part of an ASP.NET MVC program, from https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/controller-methods-views?view=aspnetcore-3.1 :
+
+A model class Movie:
+
+public class Movie
+{
+ public int Id { get; set; }
+ public string Title { get; set; }
+ [Display(Name = ""Release Date"")]
+ [DataType(DataType.Date)]
+ public DateTime ReleaseDate { get; set; }
+ public string Genre { get; set; }
+ [Column(TypeName = ""decimal(18, 2)"")]
+ public decimal Price { get; set; }
+}
+
+
+and a method from a controller class MoviesController is:
+
+// GET: Movies/Edit/5
+public async Task<IActionResult> Edit(int? id)
+{
+ if (id == null)
+ {
+ return NotFound();
+ }
+ var movie = await _context.Movie.FindAsync(id);
+ if (movie == null)
+ {
+ return NotFound();
+ }
+ return View(movie);
+}
+
+
+If I want to write an ASP.NET MVC program into three layers: presentation, business logic and data access layers,
+
+
+Since presentation layer is responsible to provides output to users and interact with users, should both view and controller belong to the presentation layer?
+Should the business layer be implemented by the model Movie?
+
+""The Model in an MVC application represents the state of the application and any business logic or operations that should be performed by it"" seems to say so.
+
+Does the business layer need to be implemented as some method, whereas the model doesn't have any method? (I guess the model class is used as an entity class by the Entity Framework. Does EF require every entity class have no method?)
+In the method of the controller, _context.Movie.FindAsync(id) is using Entity Framework (ORM) to make a query. So does the controller also implement the data access layer, besides implementing part of the presentation layer?
+How shall I separate presentation, business logic and data access layers?
+
+
+Thanks.
+",699,,699,,43834.93611,43834.95694,"How shall I implement a MVC program into presentation, business logic and data access layers?",,1,0,1,,,CC BY-SA 4.0,
+403326,1,,,1/4/2020 20:55,,0,110,"I am quite confused about the responsibility-driven design concept. Mainly because of ever so slightly changing definitions depending on the source.
+Quoting BlueJ (the book I am learning that teaches Java):
+
+Responsibility-driven design expresses the idea that each class should be responsible for handling its own data. Often, when we need to add some new functionality to an application, we need to ask ourselves in which class we should add a method to implement this new function. Which class should be responsible for the task? The answer is that the class that is responsible for storing some data should also be responsible for manipulating it.
+
+Later, in a "concept box" in the BlueJ book:
+
+Reponsibility-driven design is the process of designing classes by assigning well-defined responsibilites to each class. This process can be used to determine which class should implement which part of an application function.
+
+This second definition confuses me, as I don't see how that correlates to the first "definition"; the one saying that "it expresses the idea that each class should be responsible for handling its own data".
+Will someone please shed some light on the concept of responsibility-driven design?
+",258273,,-1,,43998.41736,43835.50417,Responsibility-driven design,,1,1,,,,CC BY-SA 4.0,
+403328,1,,,1/4/2020 21:19,,-4,163,"List is implemented in C# exactly as Stack, see:
+
+- https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.push?view=netframework-4.8#remarks
+- https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.8#remarks
+
+Given that:
+Why should developers choose, List or Stack, while in fact they can have "2 in 1".
+(Implementing Pop for List, would make it 2-in-1! ).
+Coming from more flexible languages, I don't want to commit to a limiting-collection-type. Starting with Stack, maybe later as problem changes, I'll need to access an [index], alternatively w/Lists, maybe later need Pop or List1.Add (List2.Pop()) often.
+
+Why doesn't RemoveAt() return a value? What damage would happen if it returned a value (as actually done in Java ArrayList)?
+
+Why no Pop()?
+
+
+Looking at Python, Perl, Ruby and 'e', one does wonder how come a C# List doesn't have Pop(). I want the "Swiss army knife" of arrays. i.e. List! It's convenient to use just one language construct, and avoid conversions, etc. As List is implemented using array and supports Add in O(1) (Add is just a different name for Push), why wasn't Pop added as well?
+
+Why do we need a C# Stack when List could easily do all Stack does, and more?
+Easy way to pop 'd make me always use List, hence saving the need of conversions/casting between List and Stack.
+
+
+Am i the only C# dude, that wants a (slightly) more powerful List ? ( instead of having 2 weaker concepts and having to convert between them ).
+( other than that c# is really good).
+Update : Wow !! Thanks to this thread Microsoft had decided to add Pop to C# list !! https://github.com/dotnet/runtime/issues/31828.
+many thanks to the community, especially to user @Theraot.
+",354317,,354317,,44112.61875,44112.61875,C# Why should i limit myself to List or Stack ? ( instead of having both),,4,10,1,,,CC BY-SA 4.0,
+403329,1,,,1/4/2020 21:33,,-1,387,"to summarize a bit my current situation: I am building a backend based on microservices using spring boot.
+These are aggregated behind an api-gateway.
+My intention is to consume these api's from both a mobile app and a webapp.
+
+However, I'm constantly wondering what kind of technology I should use to build my webapp frontend?
+
+This is a project I'm doing on my own and I currently don't have any knowledge of javascript frameworks like react, angular or vue.
+
+Basically, I can not find a valid reason for investing the time in learning a javascript framework to build a SPA-frontend. I am still convinced that server-side should be the first option, client-side the second option. I also rather see an MPA as a valid option for my app instead of a SPA.
+
+I have knowledge however of thymeleaf and spring mvc. Basically I would like to keep all my logic on the server side as much as possible. I was looking into using the non-blocking reactive webclient feature of spring mvc to call my REST-api's server side and send the data on to the client.
+
+Anyone have any experience with this kind of setup? Any reason why you shouldn't do this?
+As I understand it, using the webclient feature is async and non-blocking, which is already a step up from the classic resttemplate feature.
+Difference with e.g. jquery or any other javascript technology is that the api is called serverside instead of clientside, so this means full reloads of the page (e.g. also the header, footer, menu, ...) instead of a partial reload like when using javascript?
+
+A huge advantage I'm seeing however is that even if a user does not have javascript enabled, the webapp will still just work by using this setup.
+
+I don't know if this is a valid option in context of microservices to build a frontend? Anyone here also using this setup and has some more insight in drawbacks/issues with this?
+
+Thanks in advance for any feedback!
+",354318,,,,,43834.99444,building a frontend for a microservice backend: architectures? (spring boot stack),,1,0,,,,CC BY-SA 4.0,
+403332,1,,,1/4/2020 22:45,,1,923,"
+
+
+ The first thing to realize is that Server-side Web MVC (e.g. ASP.NET MVC & similar where controllers handle requests and views render to HTML) is not the same as client-side/desktop MVC/MVP UI pattern. In the UI pattern, generally the View component is the view (it doesn't create one). Also modern view widgets have the capability to detect user input, back when MVC was first created, widgets had no such capability (they were just pictures on the screen), so every widget had it's own MVC, where C handled the input - in modern MVC, C implements the nontrivial behavior of a larger view.
+
+
+I was wondering why and how ""Server-side Web MVC (e.g. ASP.NET MVC & similar where controllers handle requests and views render to HTML) is not the same as client-side/desktop MVC/MVP UI pattern""?
+
+Are they different variants of MVC pattern?
+
+Thanks.
+",699,,,,,43835.78333,Why and how are Server-side Web MVC and client-side/desktop MVC not the same?,,2,0,,,,CC BY-SA 4.0,
+403334,1,403335,,1/4/2020 22:59,,0,145,"I am letting users change their password after a reset, by following a link containing hashes of the password and user name (e-mail address). The link can look like this:
+
+
+ www.example.domain/login?h1=8tGecrXvKJBOhtzvyDmJNjpLF5RF3Ed+QSkimxlJaFo=&h2=Bv2WmO4uzgrDIRj9scKtMz0Ek0KpyJ3M00wJrMU7oeA=
+
+
+Note the presence of a ""+"" in one of the hashes. This will be translated to "" "", so in the login-method below, I'm replacing "" "" with ""+"":
+
+public async Task<IActionResult> Login(string h1, string h2, Uri returnUrl = null)
+{
+ // h1 = password
+ // h2 = e-mail address
+ if (h1 != null && h2 != null)
+ {
+ h1 = h1.Replace("" "", ""+"");
+ h2 = h2.Replace("" "", ""+"");
+ AdminUser au = await db.AdminUsers
+ .Include(p => p.Person)
+ .Where(u =>
+ u.PasswordHash == h1 &&
+ HashPassword(u.Person.Email1, Convert.FromBase64String(u.PasswordSalt)) == h2)
+ .FirstOrDefaultAsync().ConfigureAwait(false);
+ if (au != null)
+ {
+ return RedirectToAction(""ChangePassword"", ""Admin"", new { id = au.PersonId, userType = ""au"" });
+ }
+ // Some unfinished business here (if (au == null))
+ }
+ LoginFormViewModel vm = new LoginFormViewModel
+ {
+ ReturnUrl = returnUrl
+ };
+ return View(vm);
+}
+
+
+This has worked so far in my tests, but I don't know if I might run into problems because of the .Replace() in some scenario. If a hash contains ""/"" or ""="", there is no problem.
+",320898,,,,,43835.54583,"Is it ok to use .Replace("" "", ""+"") when reading hashes in a querystring?",,2,0,,,,CC BY-SA 4.0,
+403346,1,,,1/5/2020 5:49,,5,1399,"What's the difference between reactive programming and event driven architecture?
+
+Is reactive programming a way of implementing event driven programming?
+",150418,,,,,43891.76736,What's the difference between reactive programming and event driven architecture?,,2,0,1,,,CC BY-SA 4.0,
+403349,1,403353,,1/5/2020 10:06,,1,69,"You have a video game in which upon killing final boss you get coins that get distributed based on whether you are:
+
+
+- Person(individual)
+- Group(consists of individuals or groups)
+
+
+If reward for killing monster is 100. And the Fighters that killed monster together are:
+
+ var joe = new Person(""Joe"");//Person
+ var jake = new Person(""jake"");//Person
+ var emily = new Person(""emily"");//Person
+
+ var oldBob = new Person(""oldBob"");//Person that belongs to a group
+var newBob = new Person(""newBob"");//Person that belongs to a group
+ var familyGroup = new Group(""familyGroup"", new List<IFighter>() { newBob, oldBob });
+
+
+The output will be:
+
+OUTPUT:
+
+You have killed the Giant IE6 Monster and gained 100 gold!
+MegaParty has 100 gold coins.
+familyGroup has 25 gold coins.
+--newBob has 13 gold coins.
+--oldBob has 12 gold coins.
+--Joe has 25 gold coins.
+--jake has 25 gold coins.
+--emily has 25 gold coins.
+
+
+with the below code:
+
+Interface:
+
+public interface IFighter
+{
+ string Name { get; }
+ int Gold { get; set; }
+ void Stats();
+}
+**CLIENT:**
+
+class Program
+{
+ static void Main(string[] args)
+ {
+ int goldForKill = 100;
+ Console.WriteLine(""You have killed the Giant IE6 Monster and gained {0} gold!"", goldForKill);
+ var joe = new Person(""Joe"");
+ var jake = new Person(""jake"");
+ var emily = new Person(""emily"");
+ var oldBob = new Person(""oldBob"");
+ var newBob = new Person(""newBob"");
+ var familyGroup = new Group(""familyGroup"", new List<IFighter>() { newBob, oldBob });
+ var parties = new Group(""MegaParty"", new List<IFighter> { familyGroup, joe, jake, emily });
+ parties.Gold += goldForKill;
+ parties.Stats();
+ Console.ReadKey();
+ }
+
+
+Person:
+
+public class Person : IFighter
+{
+ public string Name { get; }
+ public int Gold { get; set; }
+
+ public Person(string name)
+ {
+ this.Name = name;
+ }
+
+ public void Stats()
+ {
+ Console.WriteLine(""--{0} has {1} gold coins."", Name, Gold);
+ }
+}
+
+
+Group:
+
+public class Group : IFighter
+{
+ public string Name { get; set; }
+ public List<IFighter> Members { get; set; }
+ public int Gold
+ {
+ get
+ {
+ int totalGold=0;
+ foreach (var member in Members)
+ {
+ totalGold += member.Gold;
+ }
+ return totalGold;
+ }
+ set
+ {
+ var eachSplit = value /this.Members.Count;;
+ var leftOver = value % this.Members.Count;;
+ foreach (var member in Members)
+ {
+ member.Gold = eachSplit +leftOver;
+ leftOver = 0;
+ }
+ }
+ }
+
+ public Group(string name, List<IFighter> members)
+ {
+ Name = name;
+ Members = members;
+ }
+
+ public void Stats()
+ {
+ Console.WriteLine(""{0} has {1} gold coins."", this.Name, Gold);
+ foreach (var member in Members)
+ {
+ member.Stats();
+ }
+ }
+ }
+
+
+But, what if we were to give 10% extra weightage to those Person who belong to a group or a certain group?
+I could create class such as:
+
+Female:IFighter, SeniorCitizen:IFighter to whom I want to give extra weightage.
+
+How do you go about it?
+",96641,,,,,43835.77986,Composite Design Pattern with unequal weightage,,2,0,,,,CC BY-SA 4.0,
+403357,1,,,1/5/2020 13:18,,2,227,"I am currently developing a wrapper API for a translation service that should provide multiple methods for translating strings,
+
+Task<string> ITranslator.TranslateAsync(string phrase, Language from, Language to)
+
+
+an ICollection<string>,
+
+Task<ICollection<string>> ITranslator.TranslateAsync(ICollection<string> phrases, Language from, Language to)
+
+
+and entire documents:
+
+Task<Stream> ITranslator.TranslateDocumentAsync(string file, Language from, Language to)
+
+
+The Language class looks as follows
+
+public sealed class Language
+{
+ [JsonProperty(""language"")]
+ public string TwoLetterISOLanguageName { get; internal set; }
+
+ [JsonProperty(""name"")]
+ public string NativeName { get; internal set; }
+
+ internal Language()
+ {
+ }
+
+ /* Provided in case users want to display these in a ComboBox or similar. */
+ public override string ToString() => NativeName;
+}
+
+
+and instances of the class can only be acquired by a call to ITranslator.GetSupportedLanguagesAsync.
+
+However, I don't want to force users of the API to query the supported languages and additionally provide a less verbose way of making translation requests with methods that take from and to parameters of type string instead of Language, where the provided string would be a language code such as ""de"".
+
+My issue with that solution is that it would lead to the doubling of Translate* methods and thus unnecessarily clutter the API and duplicate most of the documentation regarding these methods.
+
+I finally thought about introducing an implicit operator function to the Language class which would convert instances to their TwoLetterISOLanguageCode and remove the need for method overloads, but I am unsure if it would be bad design, as the Language class already has the ToString method yielding NativeName instead.
+
+Would this addition of the implicit operator be bad design?
+",,user354327,,user354327,43835.64028,43838.92361,Is having different implementations for ToString and the implicit operator bad design?,,4,2,,,,CC BY-SA 4.0,
+403359,1,403362,,1/5/2020 15:13,,-1,317,"As the title implies I am trying to understand the difference between boundary, controller and logical class types, which are used in the MVC pattern.
+
+I will do so using an example. Please consider the following Class Diagram :
+
+
+I have to add the needed analyse classes of type boundary and controller to account for the two use-cases : borrow a book and reserves book. The following is my answer ( sorry for my hand-writing ) :
+![]()
+
+So is this a right answer? Also, the logical classes in this case are book, student copy ( the classes that do the business process analysis ) ?
+",331812,,209774,,43835.72569,43836.33542,"Needs to understand the difference between boundary, controller, logical class types",,2,0,,,,CC BY-SA 4.0,
+403361,1,403363,,1/5/2020 17:04,,-4,266,"Why are FLASH memories considered to be EEPROMS? EEPROM has ""Read Only"" in its name, so by definition you cannot rewrite it, yet FLASH memories are used for USBs and many other technologies which are constantly rewritten.
+
+I understand that EEPROMS are ""Erasable"" which means I can modify their contents by erasing and re-writing entire blocks but how come a USB works exactly like an HDD when I read and write things?
+
+Also, what is the point in calling it Read-Only and at the same time Erasable?
+Isn't it like saying ""This is unbreakable metal that can be broken""?
+",354335,,326536,,43835.76528,43835.84931,"Why is FLASH memory considered ""Read Only"" by definition?",,2,0,,,,CC BY-SA 4.0,
+403364,1,,,1/5/2020 18:32,,0,201,"The usual workflow for my team looks something like this: features are planned by product management and then collectively broken down to business requirements. Then the developers start working separately through those requirements one by one until the next feature comes around.
+
+One issue I noticed is since the stories are implemented in an incremental way the associated code tends to be slapped on the existing code. Initially it is easy to make sure the new code somehow fits with the old code. But over time portions of the codebase begin to diverge and the whole thing turns into patchwork.
+
+I have been thinking an initial design story to put down method and test stubs, discuss the development strategy to follow etc. for the rest of the stories can help with this although I am not sure how exactly it would work.
+
+Alternatively or alongside this I want to propose switching our code review system from a single peer review by a tech lead to a consensus system, but not sure how the alternative would look like as far as what everyone would review for, how much effort would go into it, what kind of standards we would follow or how I would go about proving it would bring value.
+",,user313675,,user313675,43835.77639,43836.53542,Preventing the codebase from turning into patchwork as more stories are implemented,,4,4,,,,CC BY-SA 4.0,
+403370,1,,,1/5/2020 20:35,,3,1315,"How does one service get the data from another service? I will give few examples:
+
+1) Let's say we have two services which need to share the data: User Service and Order Service. Order Service pretty much will want to get some data User Service's database has like address, bonus points to cut the price, but all Order Service receives about a user is its userId, it doesn't have a direct access to the User DB.
+
+2) An app has a user balance system with some internal coins used as base currency. The app provides different kind of services to buy which user can spend those internal coins for. The service responsible for fulfilling user's request should be somehow able to tell User Service or Balance Service (if it was decided to split balance from users to a different service) to reduce its balance depending on how much it costed or check the balance and then return a error if it's insufficient.
+
+3) An app from #2 situation doesn't have predetermined price anymore, tasks got so complicated that now we need to run Analyze Service and now the task will go to that service to determinate the price of a task, what service should handle the task and only then the service which is able to fulfill user's request will do it.
+
+So, I will give my thoughts about these after reading numerous articles about microservice architecture:
+
+1) I see few ways to do it:
+
+
+- direct synchronous HTTP request from one service to another to get the necessary data (slow, most importantly services are now coupled and I loose benefits of microservice architecture)
+- client app has all necessary data in its global store (if it's a SPA app e.g.) and will just send them in the request (but we still need a mean to check if the data we got is valid...)
+- saving necessary data in JWT (weird..?)
+
+
+2) I guess here is a good example where message brokers come in handy. I could send a message about the task being done with its price and userId to User Service or Balance Service and callback will reduce user's balance.
+
+3) Message broker again. Analyze Service sends a message, bound performing task service will start doing a task after analyze is finished, which task service will do that depends on the queue Analyze Service will send a message in.
+
+I'm not sure about any of solutions here so here is my question. What are common ways to deal with those kind of problems?
+",342857,,,,,43838.71736,Data from one microservice to another,,2,1,,,,CC BY-SA 4.0,
+403374,1,,,1/5/2020 21:39,,0,69,"
+
+Do you use connection strings to instantiate your adapter services or just always configure it through IoC? I think that connection strings could provide a way more flexibility, especially while being combined with IoC container. Here are my two helper classes which I defined to handle URI based connection string syntax:
+
+clr://assembly-name/full-class-name?param1=arg1¶m2=arg2
+ioc://assembly-name/full-class-name?param1=arg1¶m2=arg2
+
+
+How would you evaluate this approach from an architectural standpoint?
+
+I have this to support clr://:
+
+namespace System
+{
+ public static class Activator<T>
+ {
+ public static T CreateInstance(string uri) =>
+ CreateInstance(new Uri(uri));
+
+ public static T CreateInstance(Uri uri) =>
+ uri.Scheme != ""clr""
+ ? throw new NotSupportedException()
+ : (T)Activator.CreateInstance(GetReturnType(uri), GetArguments(uri));
+
+ static object[] GetArguments(Uri uri)
+ {
+ var arguments = uri.Query
+ .TrimStart('?')
+ .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(p => p.Split('='))
+ .ToDictionary(nv => nv[0], nv => Uri.UnescapeDataString(nv[1]));
+
+ return GetParameters(uri)
+ .Select(p => Convert.ChangeType(arguments[p.Name], p.ParameterType))
+ .ToArray();
+ }
+
+ static ParameterInfo[] GetParameters(Uri uri) =>
+ GetReturnType(uri)
+ .GetConstructors()
+ .First()
+ .GetParameters();
+
+ static Type GetReturnType(Uri uri) =>
+ Type.GetType($""{uri.Segments[1]}, {uri.Host}"");
+ }
+}
+
+
+So:
+
+using (var reader = Activator<TextReader>.CreateInstance(
+ ""clr://mscorlib/System.IO.StringReader?s=Hello%20World""))
+ Assert.AreEqual(""Hello World"", reader.ReadToEnd());
+
+
+And the following is for ioc:// (works perfect with AutofacServiceProvider, etc.):
+
+namespace System
+{
+ public static class ServiceLocator
+ {
+ public static T GetService<T>(this IServiceProvider provider, string uri) =>
+ provider.GetService<T>(new Uri(uri));
+
+ public static object GetService(this IServiceProvider provider, string uri) =>
+ provider.GetService(new Uri(uri));
+
+ public static T GetService<T>(this IServiceProvider provider, Uri uri) =>
+ (T)provider.GetService(uri);
+
+ public static object GetService(this IServiceProvider provider, Uri uri)
+ {
+ if (uri.Scheme != ""ioc"")
+ throw new NotSupportedException(""Schema not supported."");
+
+ var factory = (Delegate)provider.GetService(GetFactory(uri));
+ return factory.DynamicInvoke(GetArguments(uri));
+ }
+
+ static Type GetFactory(Uri uri)
+ {
+ Func<Type[], Type> getType = Expression.GetFuncType;
+ var types = GetParameters(uri)
+ .Select(p => p.ParameterType)
+ .Append(GetReturnType(uri));
+
+ return getType(types.ToArray());
+ }
+
+ static object[] GetArguments(Uri uri)
+ {
+ var query = GetQuery(uri);
+ return GetParameters(uri)
+ .Select(p => Convert.ChangeType(query[p.Name], p.ParameterType))
+ .ToArray();
+ }
+
+ static Dictionary<string, string> GetQuery(Uri uri) =>
+ uri.Query
+ .TrimStart('?')
+ .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(p => p.Split('='))
+ .ToDictionary(nv => nv[0], nv => Uri.UnescapeDataString(nv[1]));
+
+ static ParameterInfo[] GetParameters(Uri uri)
+ {
+ var query = GetQuery(uri);
+ return GetReturnType(uri)
+ .GetConstructors()
+ .First()
+ .GetParameters()
+ .Where(p => query.ContainsKey(p.Name))
+ .ToArray();
+ }
+
+ static Type GetReturnType(Uri uri) =>
+ Type.GetType($""{uri.Segments[1]}, {uri.Host}"");
+ }
+}
+
+
+Where missing parameters are supposed to be provided by IoC container.
+",126611,,126611,,43836.02986,43836.02986,Instantiating adapters in onion architecture,,0,3,,,,CC BY-SA 4.0,
+403377,1,403379,,1/5/2020 22:38,,-2,142,"So, recently I have been doing a lot of programming in Python.
+I have noticed that my programs can be somewhat hard to read. I usually have one main class which does everything, sort of like this:
+
+class main:
+ def __init__(self, *args, **kwargs):
+ # Make baseline variables here
+ self.foo = ""bar""
+ self.hello = 12345
+ # Get starting input.
+ self.inputted = self.get_input()
+
+ def get_input(self):
+ inputted = input(""Hello, world!"")
+ return inputted
+
+ def do_something(self):
+ # Do data processing, make stuff, call other functions within the class.
+ pass
+
+main()
+
+
+I have been doing this for purposes of making variable access easy. Considering how it messes with code readability, should I be using another approach? If so, what?
+",349829,,,,,43835.99444,Proper program structuring in Python,,1,4,1,,,CC BY-SA 4.0,
+403382,1,,,1/6/2020 2:27,,1,170,"I've got 2 near-identical functions (NodeJS). One of them queries DB for shop information by its phone number, while the other one queries by its id. I'd like to know if there's a clean way to merge these 2 together.
+
+async getShopInfo (phone) {
+ try {
+ let shopInfo = await shopConfigModel.getShopInfo(phone)
+ if (shopInfo && shopInfo.length > 0) {
+ return shopInfo
+ }
+ } catch (error) {
+ logger.error('error on getShopInfo %s', error.message)
+ }
+
+ return null
+}
+
+async getShopInfoById (shopId) {
+ try {
+ let shopInfo = await shopConfigModel.getShopInfoById(shopId)
+ if (shopInfo && shopInfo.length > 0) {
+ return shopInfo
+ }
+ } catch (error) {
+ logger.error('error on getShopInfo %s', error.message)
+ }
+
+ return null
+}
+
+",212887,,,,,43877.25694,How to refactor duplicated functions with only one difference in parameter list,,2,2,,,,CC BY-SA 4.0,
+403383,1,,,1/6/2020 2:42,,2,138,"I have a eCommerce like system which produces 5000 user events (of different kind like product search/product view/profile view) per second
+
+Now for reporting business users would like to view the different dimensions like
+
+ 1. Find user session(say of 30 mins) in any given x days..
+ 2. Find number of searches/product/profile views happened in any given x
+ days.
+
+
+There are two parts involved in above use case
+
+ 1. Computation/Aggregation of events data
+ 2. How to store the data efficiently.
+
+
+First thoughts and question on storage part as this will decide how to compute/aggregate the data
+
+
+- I believe i should store the data per day as this is the most granular unit data can be asked for. It can be stored in elastic so that it is searchable and can aggregated for x days.
+- Should I store the each dimension(session/searches/product views) separately or session should be the top level object which should internally(nested) contain the other related data(like searches/product view etc) in that session. Now if product views query is asked , it can be served from here itself.
+
+
+Second how to design the aggregation/computation part. Here are my thoughts about
+
+
+- Collector(say java based) will put it scalable messaging system like partitioned kafka queue.
+- Multiple spark consumer will process the events from queue so that computation can be done in parallel and near to real time
+- Now multiple spark consumers process the events for aggregation of events per user per 30 mins and store it in elastic which can be searched through kibana dashboard.
+Aggregation can be computed like this.
+
+4a. Get the event from queue , get the user_id, create the in memory map till you get the event for
+30 mins where key will be user_id and value will be session object containing session object which internally contains search/product view/profile view for that session.
+
+4b. Once next event is after 30 event, push the object in map to elastic.
+
+
+Is my design for storage and aggregation on right path ?
+",85226,,85226,,43836.42569,44106.50486,Aggregation and storage system design for user event processing?,,2,0,,,,CC BY-SA 4.0,
+403387,1,403392,,1/6/2020 8:01,,2,172,"We are using Entity Framework with SqlServer Database. Business program needs to create many columns which are not in the Database, due to storage, high querying cost etc. Currently, the team is Copying the whole DB Entity Layer (from scaffolding), and Creating whole another layer adding computed members in new entities. Currently taking EF layer and applying AutoMapper to new layer. For some reason, not sure if this is optimal, however architect wants it this way.
+
+Is it general practice in Software industry to copy the Database layer into another Copy layer with Computed Members? I'm aware of DDD Domain Driven Design, however we are not creating Aggregate Roots, Value Objects, Clusters, etc.
+
+What is an alternate solution if this is not good practice?
+
+*I started software programming two years ago from college, curious if this is good industry practice, or alternative exists. Searched all over google and stack, and did not cite this strategy.
+
+So basically
+
+SQL Database ---> EF Layer ---> Another Copy Layer (with EF and computer members in the class) ---> Application Service ---> Dto ---> Controller APIs
+
+I agree with every layer, excepted this EF copy layer with computed members. Couldn't we just utilize partial classes?
+
+Example: New class layer would contain all existing members, plus these added in a class, etc.
+
+FullName => FirstName + LastName
+
+AccountValue => Quantity * StockPrice
+
+
+Update:
+
+Would like to hear from people who think differently also, appreciate answers below,
+",,user354368,,user354368,43836.69236,43836.69236,Copy Database Entities into Another Layer in Software Architecture?,<.net>,2,0,,,,CC BY-SA 4.0,
+403404,1,,,1/6/2020 12:56,,2,174,"We have a set of microservices and would like to expose endpoints from a subset of these for third parties to use. To this end, we will build an API Gateway that acts as the access control mechanism for all our services.
+
+In terms of how access is controlled, I've thought about the following but I'm unable to decide on the appropriate solution among them:
+
+A. API keys aka the standard way this is usually done. The disadvantage being that api keys can be stolen and used without us ever knowing.
+
+B. Oauth2. I don't think this works for our use case as Oauth is the answer to accessing user data on behalf of the user. Our integration will require the third party to update us with periodic updates relating to an item the customer has ordered.
+
+C. Have a db for third party user accounts, with signed JWTs that enable access. I see this as an implementation of the RBAC (role based access control) model. RBAC traditionally acts as a solution where there are a large number of users so with one third party user - this is potentially an overkill for a solution.
+
+D. AWS' API gateway. I don't have personal experience with this to be able to judge how good of an option it would be, and also most of our software is hosted internally so the Gateway would need to route traffic to an internal server that's probably going to increase latency - if Amazon even supports this option.
+
+--
+
+Which option do you think works best? It doesn't have to be A-D. If there's further reading you can suggest, please feel free to do so.
+",345294,,,,,43836.93611,Securing API for third party use,,3,2,,,,CC BY-SA 4.0,
+403405,1,,,1/6/2020 13:14,,1,68,"I'm making an app which is a Django backend and a React frontend (being developed by someone else). The plan currently is to fully decouple the two and have them communicate over API. However, I would like to make use of Django's Authentication features. My understanding is that Django Authentication makes use of Django sessions, which in turn abstracts the sending and receiving of cookies. My suspicion, therefore, is that if the setup looks like this:
+
+User request <-> React app <-> API request <-> Django app
+
+
+It's not going to work. Likely the cookie won't make it all the way to and from the user, and rather the React app itself is going to end up getting authenticated?
+
+Is there a (sane, relatively straight forward) way to 'push' cookies through the react app to and from the user to make use of Django authentication of users in this setup? Or do I have to serve the client directly from the Django app?
+",339042,,205897,,43845.59514,44115.62778,Using Django Sessions when views are accessed by API,,1,1,,,,CC BY-SA 4.0,
+403407,1,,,1/6/2020 14:00,,1,86,"My model classes (business layer/library of ASP .NET core solution) uses a number of services (IOrmService, IEmailService, IFileService, IHtmlToPdfConverter etc.). Different models requires different combinations of the services for CRUD operations. It prevents me to use base class to max extent and forces to repeat code/methods that are very similar. It could be solved by passing not a combination of services to factory methods but a container with all of the services.
+Which solution should I chose:
+- inject IServiceProvider (looks like a bit too tight coupling with ASP);
+- create and inject my own service container (e.g. IBusinessServiceProvider);
+- leave everything as is.
+",353988,,,,,43836.66806,Custom services container for ASP .NET core business layer,,2,4,,,,CC BY-SA 4.0,
+403410,1,,,1/6/2020 14:47,,-4,144,"I want to create a program for the Linux OS in Haskell with multiple .hs files. I don't need help with the code or compiling it, what I don't know how to do is create an application that can be called from the terminal (like how python or ghci is). So:
+
+
+- Where should the files go?
+- What do I need to do to allow it to be called from the command line?
+
+
+I'll appreciate any help/tutorials on this.
+
+Edit: I need to turn my program into whatever it is that you install on your computer. Like Python! How does Python pull this off?
+",354397,,348453,,43974.38472,43974.38472,How to Create an Application on Linux?,,1,3,,43836.86944,,CC BY-SA 4.0,
+403413,1,,,1/6/2020 15:53,,3,444,"In my limited understanding of microservices they seem to focus on quite limited pools of information, leaving it up to the application to bring all the data together in ways which were perhaps not anticipated.
+
+I am working through a simple project in an attempt to get up-to-speed with a number of new concepts for me. The application is for a library consisting of books. A book has an Id, a title and a number of 'can-haves'. For example, 0 or more authors, 0 or more editors, 0 or more translators etc.
+
+The books are in one table, the people in another table and the relationships in a third table.
+
+@IdClass(BookAuthorId.class)
+public class BookAuthor {
+ @Id
+ private char type; //A=Author, E=Editor, T=Trl8r
+
+ @Id
+ @JsonProperty(""BOOK_ID"")
+ private Long bookId;
+
+ @Id
+ @JsonProperty(""AUTH_ID"")
+ private Long authorId;
+}
+
+
+I could put these relationships directly into the book model but I'm thinking of a different approach where the authors are picked up in a separate call.
+
+http://host/api/book/{bookid}
+
+http://host/api/book/{bookid}/author
+http://host/api/book/{bookid}/editor
+http://host/api/book/{bookid}/translator
+
+
+It seems to me that the data returned is kept to a minimum and the queries are kept ultra simple and data contract is probably easier to maintain.
+
+On the downside, the number of calls increases but this might be mitigated by the use of a Backend-for-Frontend layer which would marshal all the information on the server side and not in the client.
+
+For my simple project I'm sure either way will work fine but I'm wondering how these 2 approaches would pan out in the real world.
+
+
+- Is one more scalable?
+- Is one more difficult to maintain?
+- Should one be avoided at all costs?
+
+",598,,353068,,43837.83542,43837.83542,Is it better for a microservice to access database tables individually or to work with joined data?,,4,0,,,,CC BY-SA 4.0,
+403418,1,403432,,1/6/2020 16:51,,-2,186,"I have very little experience in this area, so sorry if I use any incorrect terminology or if this is a stupid/simplistic question in general.
+
+But from what I understand, when a developer wants to push out an update for an app, it has to be approved by Apple/Google which can take up to 2 days. And apparently it even use to be much longer with Apple. So what happens if, for example, a massively popular game on an app store gets found out to have a huge exploit which could lead to players seeing other players credit card details, as an extreme example. Is there a way to bypass these wait times to push out a fix?
+
+And I've heard of server side hotfixes in games before, so I assume these can be done to bypass these approval systems. And if so, doesn't that make the approval system pointless? I understand that hotfixes don't require the user to manually download a new update, but couldn't hotfixes still be used to do malicious things which I assume these approval systems are in place to prevent?
+
+I guess my questions boil down to:
+Why are these approval systems in place?
+What can be done if there's a major exploit within a game that cannot be fixed by a hotfix?
+",354404,,,,,43836.91667,What is done when an urgent fix for an app is needed but updates have to be approved by Apple/Google etc?,,2,7,,,,CC BY-SA 4.0,
+403419,1,403435,,1/6/2020 16:51,,-4,87,"I have a design question and am hoping for some validation. I want to create a 'serverless' web app which will parse a csv file and return an XML file.
+
+I will have a single page react app hosted in AWS S3, where a user can drag and drop a file, and it will be parsed and the contents of the csv file will be sent to a lambda, which will then convert it to an XML file and return this to the user.
+
+I am hoping not to have to use S3 to store the csv and resulting xml file but I can if that is needed.
+
+Is this possible without a server or am I way off?
+",302041,,,,,43836.92778,Use React to parse a file (serverless),,1,4,,,,CC BY-SA 4.0,
+403424,1,,,1/6/2020 17:55,,1,353,"Android uses the modified version of JVM known as Android Runtime to execute android apps.
+
+How do games (with Unity 3d) and Apps (Xamarin) written in C# (which require dot Net's Mono framework) run on Android?
+
+The official website of mono says
+
+
+ The Mono runtime has been ported to the Android OS.
+
+
+What exactly does that mean?
+
+Is Mono Bundled with Android OS?
+
+Is Mono Bundled with each App and Game?
+
+According to this answer on Unity3d forum. It says Mono is similar to Java, in terms of being able to do cross-platform Software development.
+
+This leads back to my initial question,
+
+does android have two runtimes (Mono and ART)?
+",351666,,351666,,43836.82639,43836.88403,"How does .Net's Mono Framework, Work on Android",,1,0,,,,CC BY-SA 4.0,
+403427,1,,,1/6/2020 19:10,,-2,165,"An example of my API is
+
+mydomain.com/v1/update-profile
+
+
+So the user is authenticated and wants to update some stuff in their profile. Should we design the API to expect a POST or a PUT HTTP Method?
+
+From my internet search it seems PUT is idempotent, but at the same time it's usually used for updating a particular resource in a URL with an id at the end. Example:
+
+mydomain.com/v1/questions/{id}
+
+",354422,,110531,,43837.34514,43837.37083,Should you use PUT or POST when an authenticated user is trying to update their own settings?,,2,3,,,,CC BY-SA 4.0,
+403438,1,403439,,1/6/2020 23:39,,1,104,"I'm ingesting 150 objects that each require an user capabilities check, the function isUserAdmin tells me whether or not an user is an admin or not. Inside this function, there's a lot of deeper checks and so on. It'd be really, really nice if I could cache this stuff so I don't have to check for 150 objects.
+
+I'd like to, before anything loads, determine who the user is and set up things that in practice, don't change -- or do they? Assume a super admin changes the privileges of an admin user mid-request but I've already set his privilege information, so, assume this admin has the capability to delete other users, he's running a request to do that, but during that time, the superadmin says ""nope, can't do that anymore"", but because on that request I already set that user's permissions, this will not take effect and the admin will still be able to delete users.
+
+What's the fix here? Setting information pre-emptively is basically dangerous in an async-by-proxy environment (which everything is) but not doing this makes me perform the same check 150 times in a row.
+
+I feel like this is a chicken & egg problem and every time I'm faced with such issue, I'm not seeing a vital angle. What am I missing?
+",353781,,,,,43841.30139,How can I store an user's capabilities to boost performance while allowing real-time updates of said capabilities?,,4,3,,,,CC BY-SA 4.0,
+403441,1,403479,,1/7/2020 1:29,,-3,127,"I am trying to create a season schedule for our Knowledge Bowl league (middle school trivia). I am NOT very mathematical nor a ""techie"". Here are my constraints:
+
+
+- There are seven schools participating; each school has three teams. Example: Tenino Black, Tenino Red, and Tenino White This means there will be 21 teams total.
+- Teams from the same school cannot play each other. So each team will play the other 18 teams.
+- There will be seven meets.
+- Each individual meet is made up of three matches in which three teams compete against each other. Also, each team will complete in 21 matches total.
+- It does not matter if a school is hosting the meet--""Home Advantage"" is not a factor.
+
+
+I know there must be a simple mathematical way to set this up, but I just can't figure it out. I've tried to just do this randomly, but am quickly approaching insanity. Please help! Thank you in advance.
+",354435,,319783,,43837.27569,43837.83542,Help Developing a Season Schedule?,,2,3,,,,CC BY-SA 4.0,
+403442,1,403459,,1/7/2020 2:35,,2,267,"I am designing an application where there will be one column that stores a large amount of text. I'm debating whether the text should be stored in the database itself, or whether the database should store a reference to an object store such as Google Cloud Storage or Amazon S3, and have the application use that reference to pull from those services. My thinking is that the object store offers a significantly cheaper storage cost per GB than the database; but I am uncertain what I am trading off in doing this.
+
+So what tradeoffs are there to storing large binary data in my database as opposed to an object store?
+",283155,,,,,43837.66736,When would I use a database over an object-store for large blobs?,,3,4,,,,CC BY-SA 4.0,
+403446,1,403448,,1/7/2020 7:03,,2,136,"I have different types of posts a user can create:
+
+
+- TextPost
+- ImagePost
+- VideoPost
+
+
+The frontend client needs to retrieve the last 10 posts from a user.
+I am wondering how to model this structure correctly in a relational database and the data structure for sending the data to the frontend.
+
+My proposed solution:
+
+A post table with columns:
+
+
+- user_name
+- create_date
+- text_post_id
+- video_post_id
+- image_post_id
+
+
+A row has only one of the foreign keys _id columns set. To get the last 10 post the backend will do a select on the post table to get the last posts. Next it will do do another select query for each of the post types. Example:
+
+select * from text_post where text_post_id in (?1)
+
+
+The data is then mapped in a List of post object. A post object having the fields textPost, videoPost, imagePost. Again only one of them is set at a time. The list is then ordered by create date for each post. Finally we send the response to the frontend which will iterate over the list and display each post type accordingly:
+
+[
+ {
+ ""videoPost"": null,
+ ""textPost"" : {},
+ ""imagePost"": null
+ },
+ {
+ ""videoPost"": {},
+ ""textPost"" : null,
+ ""imagePost"": null
+ }
+]
+
+
+Is this a good solution that will scale and allow for the possibility of adding more post types in the future?
+",354445,,,,,43837.86597,"Modeling different types of ""Posts""",,3,0,,,,CC BY-SA 4.0,
+403449,1,,,1/7/2020 8:18,,1,67,"Imagine that we have a storage of objects O (can be in SQL, NoSQL, doesn't matter) where the object contains some property P_1 to P_n. Some of these properties are stored in storage S1, some in storage S2, etc. In general, imagine that the full definition of the a single object can only be done by invoking some kind of lookup or join across many storage. You can also think that the object is vertically partitioned across different logical database, and each database is oblivious of other database.
+
+Now, we want to define a way to filter and sort these objects. But the function to filter and sort the objects are dependent on properties that span multiple database. At a glance, that means if we were to perform any kind of sorting or filtering, we have to pull the whole database and join the properties in the caller side, which can quickly get expensive for non-trivial sized database.
+
+How can we implement this efficiently?
+
+Some options come to mind:
+
+
+- Store columns that are used for filtering/sorting together in one storage. In other words, make sure that properties that are used for filtering/sorting stick together, so that we can perform the filtering/sorting in the database server. But this is inflexible, because as and when we need to change the filtering/sorting algorithm we potentially have to change the storage schema. Admittedly not too painful in NoSQL database, but still a change in the implicit schema.
+- Limit any filtering/sorting algorithm only to properties that exist stick together in one database. This is effectively a variant of no. 1, but put the burden of being inflexible on the caller side.
+- Have a storage specifically to store a filtered + sorted list of object. This feels a bit dumb, and totally space-inefficient especially if the filter/sorting algorithm is very generic.
+
+
+While thinking about this problem, it also occurs to me that it is similar problem to how Facebook can give customized News Feed to every user. How does it perform the sorting of the News Feed efficiently when the relevancy score of each News Feed item is specific to the user?
+",147945,,147945,,43837.39792,43837.40278,System design for filtering/sorting objects whose properties are stored in distributed storage,,2,0,,,,CC BY-SA 4.0,
+403454,1,,,1/7/2020 11:54,,1,65,"Here's a simple scenario: a REST API of which you launch multiple, load-balanced replicas of the same service with Gunicorn. Unit and integration tests are run in single-instance cases, but how can you run integration tests that include all instances so you check that they have a single source of truth?
+
+I can think of several ways but I don't know if there's a better one in Python (or in other languages). Maybe I just miss the vocabulary to search for it. Here's what I think
+
+
+Launching the several instances of the server from some external program, and use API requests from the test to check that.
+Use Gunicorn as a module, write a script that works in the same way as the command you used, and run integration tests on that one.
+
+
+Is there any better way to do this?
+",186925,,186925,,43837.57153,43837.62014,How can you do integration tests when launching multiple REST API instances of the same server?,,1,5,,,,CC BY-SA 4.0,
+403455,1,403470,,1/7/2020 13:29,,3,741,"For modelling software implemented with the imperative or procedural programming paradigm we have Flowcharts, process diagrams, etc.
+
+For object oriented we have UML class diagrams, object diagrams, state diagrams, etc.
+
+Is there an UML diagram suitable designing software implemented with functional programming?
+",297840,,209774,,43837.94931,43837.94931,Is there a UML diagram for functional programming?,,1,6,2,,,CC BY-SA 4.0,
+403466,1,,,1/7/2020 16:02,,0,62,"I have a complex PostgreSQL database structure that is consisted with views, materialized views and foreign wrappers.
+
+The database schema is manually updated without any sort of migration script, hence I want to introduce a database migration schemes.
+
+One approach is to generate an initial SINGLE migration that will run only under these conditions:
+
+
+- The environment is not a production or a staging one.
+- There are no tables into the database.
+
+
+This single migration will generate the existing database schema from a database dump. After that each change on the database will be placed upon a new migration script. The framework that will execute the migration scripts is the Laravel and the database layer is the PostgreSQL one.
+
+The reason why I tried this approach is that I want to avoid database corruption on the existing db on production and staging, but to be able to reproduce the database on local development environment.
+
+AFAIK Laravel keeps in the database the last executed migrations as well, so I want to avoid the migrations to be out of sync.
+
+Also, approaches such as this one https://github.com/Xethron/migrations-generator fail to handle the foreign database tables, each foreign table is being generated as normal one.
+
+Would you recommend this approach in my case?
+",249660,,326536,,43837.78403,43837.85278,Should I skip some migrations on production in case of migrating a legacy database that has not been generated via migration script?,,1,2,,,,CC BY-SA 4.0,
+403472,1,403497,,1/7/2020 18:15,,-3,153,"I know that a RESTful would have unified API and it treats everything as a resource (a noun, example a book, a product,...) and it can be applied with CRUD operations using HTTP Verbs (GET, PUT, POST, PATCH, DELETE,...)
+
+I am aware of the fact of nouns & verbs.
+
+Now, I am building a Web API that is managing the books and custom analytics of the books like,
+
+
+- Which books or categories are searched frequently?
+- Demand vs availability
+
+
+ASP.Net Web API
+
+BooksController - GET(Odata), PUT, POST, PATCH, DELETE
+
+PagesController - GET(Odata), PUT, POST, PATCH, DELETE
+
+BookAnalyticsController - GetFrequentBooks, GetFrequentCategories,...
+
+PageAnalyticsController - GetFrequentPages, GetBookmarkedPages,...
+
+I used Odata to query list by properties and select the properties as well. This will save duplicate counter-REST methods like GetBooksByCategory, GetBooksByYear, GetBooksByAuthor,..
+
+Now, you know that BookAnalyticsController and PageAnalyticsController is going to have multiple HTTPGET verbs based on use-cases.
+
+For Books or Pages controller, I can elegantly browse like
+
+
+
+GET https://locahost/api/book/id
+
+POST https://locahost/api/book BODY
+
+PUT https://locahost/api/book/id BODY
+
+PATCH https://locahost/api/book/id PARTIALBODY
+
+For BookAnalytics,
+
+GET https://locahost/api/bookanalytics/GetFrequentBooks
+
+GET https://locahost/api/bookanalytics/GetFrequentCategories
+
+IMO, it is kind of looking ugly. How would you make it pure RESTful API for analytics. Please suggest
+",318937,,,,,43838.42847,A True RESTful API | Help needed,,1,8,,,,CC BY-SA 4.0,
+403478,1,,,1/7/2020 19:11,,1,138,"I am trying to review our current architecture.
+These are the current layers, trying to analyze them, and see if the following three ideas are good practice.
+
+DatabaseSQLStorage ---> Entity Framework Class Layer ----> Generic Repository ---> Entity Framework Copy Model Layer ----> Application Service ---> DTO Layer ----> API Controller
+
+1) One thing I am concerned, the Application layer has tangible method references to Two layers. so if the entity layer breaks, Two layers actually break (Entity and the Copy Model Layer). The Repository should only bring Model layer, and we should Only be working with that at that point, not having two references.
+
+When discussing with architect, he mentioned 'well we have differential functional areas with our 5 application services, so not sure. Was trying to comprehend this.
+
+public async Task<ProductDto> GetProductById(int id)
+{
+ var productData = await IProductRepository.GetAsync(id);
+ ProductModel productModel = mapper.Map<productModel>(productData);
+ var productDto = mapper.Map<ProductModel, ProductDto>(departmentModel);
+ return productDto;
+}
+
+
+2)
+Another thing I am questioning is, we have both a Model Layer, AND a DTO Layer.
+The Model layer, contains computed members, see Article below. We are not doing Domain Driven Design (no aggregate roots, value objects, clusters, etc)
+
+ProductFullName => ProductType + LastName + ProductDescription // Concatenation
+AccountValue => Quantity * ProductCost
+
+
+Copy Database Entities into Another Layer in Software Architecture?
+
+I am fine with DTO Layer, for example, the business contains private account numbers, Social Security, birthdate, etc, that we remove before sending APIs
+
+Just concerned if a DTO layer is needed with the other copy layer.
+
+3) Also, not a fan of the generic repository, since EF DbContext is a Repository and Unit of Work by itself, but that's another point too .
+",,user354368,,user354368,43839.26042,43839.26042,"Application Service Layer referring to two Layers, and Database Entity Copy Layer with DTO Layer?",<.net>,0,7,1,,,CC BY-SA 4.0,
+403481,1,403487,,1/7/2020 21:36,,5,144,"I have a class called D2Array which represents a fixed-size 2D array. It's meant to be generic and it comes with quite its lot of methods: getting an element, setting an element, extract a whole row, column, etc.
+
+Now I want to write MyClass, which contains a D2Array, and in order to use MyClass properly I'll need to manipulate the state of the inner array. A straightforward solution would be having a getter to the array, manipulating it outside MyClass, and then putting it back into it through a setter.
+
+(Instead of the usual Template<Type> notation, I used Template-Type to describe template parameters, which is a bit of a contraption, but StarUML wouldn't let me do otherwise.)
+
+
+
+This way however, any D2Array could be fed to the setter, which would then need some sort of validation to prevent invalid states from happening. This can quickly become expensive in my case and I find it horribly counter-intuitive that the setter may throw, so I think this is clearly not a suitable solution.
+
+
+
+Another straightforward solution which also has the benefit of strongly enforcing encapsulation: in MyClass, write public methods to manipulate the inner array.
+
+
+
+This is actually fine when you need to allow manipulation of the array only in a way that is not trivial. However, when you just want to expose part or whole of the existing methods on the array, it translates to literally writing one-liners which simply forward arguments to the appropriate methods. It already feels dull having to do it for one class, let alone doing it for several classes which all use an inner array in a similar yet different fashion.
+
+Retrospectively, I think this is the essence of my problem: I want to expose only a subset of the interface of my inner array, exactly as-is, having to write the least amount of forwarding methods to do so, and the contents of this subset also depends on the needs of the class which uses an inner array.
+
+
+
+I came up with the following solution, which seems to fit my requirements nicely, but I'm wondering if it's not kind of an anti-pattern:
+
+
+- Write a new class
D2ArrayWrapper (dumb name for the sake of the example), which contains the inner array as a protected member, and publicly declares and defines forwarding methods to all of the inner D2Array methods.
+- Have
MyClass inherit from D2ArrayWrapper. This way, it contains an inner 2D array and already has all of the forwarding methods implemented, saving me the pain of writing them myself. This gain is doubled if I want to write MyClass2 which also manages a D2Array: just have it inherit from D2ArrayWrapper!
+- If I want any array method not to be accessible from outside
MyClass, I just need to re-declare it from MyClass, as a protected or private member.
+
+
+
+
+Reasons I like it:
+
+
+- It kind of achieves what I wanted.
+
+
+Reasons I dislike it:
+
+
+- Instead of re-declaring and re-defining the array methods that I want to be accessible from
MyClass, I re-declare the array methods that I don't want to be accessible from MyClass. My DRY problem is not gone, simply reversed. (Also in C++, a simple using statement does the trick, but in Java, a whole re-definition is needed).
+- It only works in languages which handle multiple inheritance. It would work in languages which only support single inheritance too, but then it simply wastes inheritance possibilities for that class, which I find to be a huge unwanted side-effect.
+- It feels overkill when compared against the simplicity of the original goal.
+
+
+
+
+I'm kind of at loss right now as to which solution I should go with.
+Solution 1 is a no-go because of the complexity a validation would incur.
+Solution 2 is fine, but feels dumb and somewhat inelegant.
+Solution 3 feels like an overcomplication of things that got slightly out of hand, and after having given it some thought, I'm pretty sure that's not something I want to go with.
+
+As a result I'm considering going with solution 2, but is there not another way?
+Thanks.
+",153704,,153704,,43838.34931,43838.34931,Selectively exposing interface of inner members,,1,0,,,,CC BY-SA 4.0,
+403483,1,403485,,1/7/2020 21:51,,82,17449,"Currently I am working on a school project written in C#. Some teammates just started in C# and some are already familiar with C#. Today I had a discussion on whether to use syntactic sugar like this in our code:
+
+private _someClass;
+public SomeClass SomeClass
+{
+ set => _someClass = value;
+}
+
+// Equivalent to:
+
+private _someClass;
+public SomeClass SomeClass
+{
+ set
+ {
+ _someClass = value;
+ }
+}
+
+
+Or this:
+
+random ??= new Random();
+
+// Equivalent to:
+
+if (random == null)
+ random = new Random();
+
+
+Reasons we discussed for not using syntactic sugar like this were:
+
+
+- It is hard to read in general
+- For someone coming from another language e.g. Java, it is harder to see what is going on in the code.
+
+
+Are these valid reasons? Does this happen in other languages? Are there some measures to decide what is the ""cleaner"" way of coding?
+",264451,,-1,,43853.45347,43853.45347,When to use / not use syntactic sugar,,9,29,14,,,CC BY-SA 4.0,
+403490,1,403492,,1/8/2020 7:43,,8,1166,"What is exactly meant when software-engineers talk about ""behaviour"" in contrast to ""state"" (Definition of ""state"")?
+",354523,,,,,44201.58681,"Definition of ""Behaviour""?",,4,2,,,,CC BY-SA 4.0,
+403500,1,403502,,1/8/2020 12:05,,2,197,"I'm developing an application that has a backend (Java, Spring) and a frontend (TypeScript, Angular). The backend application provides with an OpenAPI-compatible API and performs certain operations with different 3rd-party services (Kubernetes cluster, GitLab server and other ones).
+
+The backend service has controllers, they call services, they call repositories, they call clients. So, for example, when a frontend application needs to delete some object (for example, a pod) from a Kubernetes cluster, it sends the following request to the server: DELETE /api/v1/workload/pod/name/blah-blah-blah. the controller has a separate method that proceeds this request and it calls the corresponding service that is responsible for pod-related operations. The service calls the repository that is responsible for pods. The repository calls an internal Kubernetes client (actually a wrapper). The client calls a 3rd-party library (the original Kubernetes client) which performs the actual communication with the Kubernetes cluster.
+
+What do you think, where should I catch the exception from the original Kubernetes client if it's being raised? For example, if there is no object with such a name in the cluster? What layer should handle it - a controller, a service, a repository or a client? Obviously, the application needs to catch this exception to reply with the 404 code instead of replying with 500?
+
+Thanks in advance for any suggestions and sorry if my question is not fully clear.
+",327861,,118878,,43838.58264,43839.52639,Where should I catch exceptions,,2,4,1,,,CC BY-SA 4.0,
+403501,1,403511,,1/8/2020 12:11,,0,127,"I am still quite new on here so I hope I am posting in right forum.
+
+I am currently writing a small library where I realized I could use some kind of design pattern which lets one pass constructor arguments to initialization or allocation functions, and these can be further specialized in inherited classes.
+
+Something like this:
+
+class MyArgs{
+ // basically just a wrapper/container
+ // just a constructor and variables
+ // everything public or friend of MyClassBase
+};
+
+class MyClassBase{
+ MyClassBase(MyArgs a){
+ doAllocation(a);
+ doInitialization(a);
+ }
+ //... defining default doAllocation() and doInitialization() ...
+};
+
+class MyClassDerived : public MyClassBase{
+ MyClassDerived(MyArgs a) : MyClassBase(a){}
+ //... override doAllocation() and doInitialization() ...
+};
+
+
+Does there exist some kind of design pattern which makes this easier?
+",220866,,,,,43838.8625,Design pattern for embedding constructor arguments into classes/structs,,4,2,,,,CC BY-SA 4.0,
+403503,1,403621,,1/8/2020 12:30,,1,62,"I am trying to decide between a NoSQL (MongoDB) or a SQL (Oracle) database for my project. This database will be used to store output files from a set of parameters.
+
+I can model this as a MongoDB document, so that the parameters and their values are stored as a key:value pair. Afterwards, I would query those documents in Java by sending an example HashMap.
+
+I can also model this as a SQL table. In this situation I would create a hash index based on the parameters and their values. I would query those entries of the table in Java by rebuilding the hash and sending it within a SQL Select.
+
+I figured that the NoSQL modeling makes more sense, since the parameters and their values would be stored on a cleaner manner. Also, querying it would make more sense on a maintenance point of view. Rebuilding a hash and making sure the hash is consistent across the board would be a maintenance overhead with SQL.
+
+On the other hand, I have made some testing with both alternatives and the NoSQL one seems to be the slowest to return the queries (double the time of a SQL query by the has index, and it makes sense to be this way).
+
+This seems to me like a common problem someone had before me. Still, I could not find any comparison of this type of modeling on NoSQL and SQL on an article so that I could read from someone else's perspective.
+
+Is this a common problem on database modeling?
+Did I go right about testing it?
+Do my conclusions make sense?
+Is there anywhere I can find an article with a simillar problem? I have searched a lot for it and all I could find were superficial comparisons between NoSQL and SQL. Maybe I have not used proper keywords for it.
+",352971,,,,,43840.33194,Query by NoSQL keys versus SQL hash,,1,5,,,,CC BY-SA 4.0,
+403506,1,403553,,1/8/2020 13:10,,0,135,"I am investigating a good maintainable architecture for GraphQL. In particular we want to migrate a REST app to GraphQL. Specifically I am using .NET.
+
+I am following the tutorial here: https://fullstackmark.com/post/17/building-a-graphql-api-with-aspnet-core-2-and-entity-framework-core
+ which is very similar to most tutorials
+
+It has the following Mutator file:
+
+public class NHLStatsMutation : ObjectGraphType
+{
+ public NHLStatsMutation(IPlayerRepository playerRepository)
+ {
+ Name = ""Mutation"";
+
+ Field<PlayerType>(
+ ""createPlayer"",
+ arguments: new QueryArguments(
+ new QueryArgument<NonNullGraphType<PlayerInputType>> { Name = ""player"" }
+ ),
+ resolve: context =>
+ {
+ var player = context.GetArgument<Player>(""player"");
+ return playerRepository.Add(player);
+ });
+ }
+}
+
+
+This gets assigned in the schema:
+
+public class NHLStatsSchema : Schema
+{
+ public NHLStatsSchema(IDependencyResolver resolver): base(resolver)
+ {
+ Query = resolver.Resolve<NHLStatsQuery>();
+ Mutation = resolver.Resolve<NHLStatsMutation>();
+ }
+}
+
+
+Finally there is a single GraphQLController which handles the API requests and has an instance of the schema:
+
+ [Route(""[controller]"")]
+ public class GraphQLController : Controller
+ {
+ private readonly IDocumentExecuter _documentExecuter;
+ private readonly ISchema _schema;
+
+ public GraphQLController(ISchema schema, IDocumentExecuter documentExecuter)
+ {
+ _schema = schema;
+ _documentExecuter = documentExecuter;
+ }
+
+ [HttpPost]
+ public async Task<IActionResult> Post([FromBody] GraphQLQuery query)
+ {
+ if (query == null) { throw new ArgumentNullException(nameof(query)); }
+ var inputs = query.Variables.ToInputs();
+ var executionOptions = new ExecutionOptions
+ {
+ Schema = _schema,
+ Query = query.Query,
+ Inputs = inputs
+ };
+
+ var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);
+
+ if (result.Errors?.Count > 0)
+ {
+ return BadRequest(result);
+ }
+
+ return Ok(result);
+ }
+ }
+}
+
+
+Having a single schema and API endpoint seems to be ""How GraphQL is done"" according to a few parts of the internet.
+
+However this seems to result in a very very large Query and Mutator file, with many many dependencies injected (repositories, services etc) and many, many methods in the file.
+
+This is an Enterprise applicattion with 300+ database tables and lots of complex backend business rules. The application is a monolith with a layered architecture with a UI layer, Services layer and Data Layer.
+
+How can I architect this to make this more maintainable?
+
+I have read up on Schema Stitching or Federation (https://www.apollographql.com/docs/graphql-tools/schema-stitching/)
+However, I'm not sure if that's the right approach as the examples seem to be using that to address microservices or API endpoints from different apps. (https://blog.apollographql.com/graphql-schema-stitching-8af23354ac37)
+",212678,,212678,,43838.55417,43839.29375,GraphQL results in a very large Query and Mutator file for Enterprise Monolith,<.net>,1,2,1,,,CC BY-SA 4.0,
+403510,1,,,1/8/2020 14:59,,0,123,"So, I was wondering about how Haskell's lists are implemented. I looked it up, and found this:
+
+data [] a = [] | a : [a]
+
+
+So I get that you can write lists like this if you want to:
+
+a:b:c:[] -- instead of [a, b, c]
+
+
+But my question is: How is the list syntax that is usually used (the [a, b, c] syntax) implemented?
+
+Edit: I want to know the implementation, so if anyone could point me to the right standard library file, that would be much appreciated.
+",354397,,354397,,43838.67847,43838.70278,How do Haskell Lists Desugar?,,1,2,,,,CC BY-SA 4.0,
+403513,1,403596,,1/8/2020 15:16,,0,108,"Clarification question on saving entities best practice.
+
+What is the purpose of returning an entity that you might have just saved in a repository? I see the benefit of returning it's Id once it's been created but not the whole entity. Can someone please explain the purpose or benefit in returning the entity.
+",229167,,,,,43839.89792,Create or Update method returning created entity,,1,10,,,,CC BY-SA 4.0,
+403514,1,403529,,1/8/2020 15:33,,2,226,"I understand ""the works"" of event driven systems and I've built simple ones. However I find that I am struggling a bit in efficiently designing one.
+
+E.g., Formulating all the events upfront seems not easy, I find that I'm removing/renaming some events I initially determined later down the road.
+
+Another thing is determining the services that are supposed to care about those events upfront. E.g., ""orderPrepared"" event? Ahh service x,y,z needs that. Catch my drift?
+
+I guess my question is, after determining the business requirements, what's your methodology in designing an event driven system? How does one actually ""lay it all out"" in an effective manner, minimizing changes later on?
+",319317,,,,,43839.86111,Effective methodology in designing event driven systems,