body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>To update parameters in our main.js file, which has a lot of configurable variables, we can do the following</p>
<p>A .</p>
<pre><code> module.exports.setVarA = function(val){
VarA = val;
}
module.exports.setVarB = function(val){
VarB = val;
}
...so on for VarC up to VarZ
</code></pre>
<p>B. </p>
<pre><code>module.exports.setAllVariables = function(valA, valB.... valZ){
VarA = valA;
VarB = valB;
...
VarZ = valZ;
}
</code></pre>
<p>Which one is a better approach to setting up variables in NodeJS? (faster, easier to maintain, not an antipattern)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-24T20:04:08.727",
"Id": "385367",
"Score": "0",
"body": "There's a third option that you pass in an object and whichever properties are present are the values to be set. Which of any of these works out best depends entirely upon how y... | [
{
"body": "<blockquote>\n <p>Which one is a better approach to setting up variables in NodeJS? (faster, easier to maintain, not an antipattern)</p>\n</blockquote>\n\n<p>Evaluating the merit of different options depends upon these factors:</p>\n\n<ol>\n<li>How many total options are there now?</li>\n<li>How lik... | {
"AcceptedAnswerId": "200231",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-24T19:56:55.453",
"Id": "200229",
"Score": "0",
"Tags": [
"node.js"
],
"Title": "NodeJS Module Exports: Export multiple functions vs Exporting a single function"
} | 200229 |
<p>I wrote a quick implementation of an async queue that utilizes a backing <code>ConcurrentQueue</code>. It was pretty much based on an implementation given in <a href="https://stackoverflow.com/a/22938345/451693">this Stack Overflow answer</a>. The only difference is that I got rid of the internal locks that implementation uses.</p>
<p>Since a <code>ConcurrentQueue</code> is already thread safe, I can't figure out why they chose to use a lock in their implementation. Normally I would ask them on Stack Overflow but the question is 4 years old and I would rather post my implementation here and have someone do a peer review to see if I have a potential threading issue.</p>
<pre><code>/// <summary>
/// Asynchronous Queue.
/// </summary>
/// <typeparam name="T">
/// The queue's elements' type.
/// </typeparam>
public sealed class AsyncQueue<T> {
/// <summary>
/// Items.
/// </summary>
private readonly ConcurrentQueue<T> _items;
/// <summary>
/// Promises.
/// </summary>
private readonly ConcurrentQueue<TaskCompletionSource<T>> _promises;
/// <summary>
/// Create an Asynchronous Queue.
/// </summary>
public AsyncQueue() {
this._items = new ConcurrentQueue<T>();
this._promises = new ConcurrentQueue<TaskCompletionSource<T>>();
}
/// <summary>
/// Dequeue an Item Asynchronously.
/// </summary>
/// <returns>
/// A task representing the asynchronous operation.
/// </returns>
public Task<T> DequeueAsync() {
var dequeueTask = this.DequeueAsync(CancellationToken.None);
return dequeueTask;
}
/// <summary>
/// Dequeue an Item Asynchronously.
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token to cancel the asynchronous operation with.
/// </param>
/// <returns>
/// A task representing the asynchronous operation.
/// </returns>
public async Task<T> DequeueAsync(CancellationToken cancellationToken) {
CancellationTokenRegistration? cancellationTokenRegistration = null;
var promise = new TaskCompletionSource<T>();
var itemFound = this._items.TryDequeue(out var item);
if (!itemFound) {
cancellationTokenRegistration = cancellationToken.Register(OnCancellationTokenCanceled, promise);
this._promises.Enqueue(promise);
}
else {
promise.TrySetResult(item);
}
try {
item = await promise.Task;
return item;
}
finally {
cancellationTokenRegistration?.Dispose();
}
// <summary>
// On Cancellation Token Canceled.
// </summary>
void OnCancellationTokenCanceled(object cState) {
var cPromise = (TaskCompletionSource<T>) cState;
cPromise.TrySetCanceled();
}
}
/// <summary>
/// Enqueue an Item.
/// </summary>
/// <param name="item">
/// An item to enqueue.
/// </param>
public void Enqueue(T item) {
while (true) {
var promiseFound = this._promises.TryDequeue(out var promise);
if (!promiseFound) {
this._items.Enqueue(item);
break;
}
var promiseSet = promise.TrySetResult(item);
if (promiseSet) {
break;
}
}
}
}
</code></pre>
<p>I wrote unit tests and it <strong>seems</strong> to work fine. I <strong>think</strong> there might be a rare race condition that happens in the following scenario, but I have not been able to trigger it and I want a second opinion:</p>
<ol>
<li>Thread 1 enqueues an item</li>
<li>Thread 1 does not find an existing promise</li>
<li>Thread 1 is preempted</li>
<li>Thread 2 attempts to dequeue an item</li>
<li>Thread 2 does not find an existing item</li>
<li>Thread 2 is preempted</li>
<li>Thread 1 enqueues item</li>
<li>Thread 2 creates and enqueues a promise</li>
<li>Idle time until another enqueue or dequeue operation occurs</li>
</ol>
| [] | [
{
"body": "<blockquote>\n <p>The only difference is that I got rid of the internal locks that implementation uses.</p>\n \n <p>Since a <code>ConcurrentQueue</code> is already thread safe, I can't figure out why they chose to use a lock in their implementation. </p>\n</blockquote>\n\n<p>From my understanding ... | {
"AcceptedAnswerId": "200450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-24T21:22:29.557",
"Id": "200233",
"Score": "6",
"Tags": [
"c#",
"asynchronous",
"thread-safety",
"queue"
],
"Title": "Async Queue implementation without locking"
} | 200233 |
<p>I'm looking for a better way of doing this code I made. I work for tech support and one of the biggest questions I am asked is: "Hey, how did my disk get so full in my VPS?"</p>
<p>I am aiming for output like:</p>
<blockquote>
<pre><code>home/ is taking up xGB
home/user1 xgb
home/user2 xgb
</code></pre>
</blockquote>
<p>and so on. So far I have this, which does alright, but I am looking for a prettier way of getting this done.</p>
<pre><code>#!/bin/bash
for i in $(ls -d */ | grep -v proc);
do
printf "**** $i has the following breakdown ********\n"
du -h --max-depth=1 $i
done
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-24T23:49:19.430",
"Id": "385397",
"Score": "1",
"body": "Even after you narrow it down to a specific user, you would still need to investigate that home directory. Have you used [`ncdu`](https://dev.yorhel.nl/ncdu)?"
},
{
"Cont... | [
{
"body": "<h1>Use 'shellcheck' to spot common problems</h1>\n\n<pre class=\"lang-none prettyprint-override\"><code>200236.sh:2:12: warning: Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames. [SC2010]\n200236.sh:2:18: note: Use ./*glob* or -- *glob* so names with... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-24T21:59:30.127",
"Id": "200236",
"Score": "2",
"Tags": [
"bash",
"linux",
"shell",
"unix"
],
"Title": "Making a disk usage breakdown"
} | 200236 |
<p>I spent about an hour and a half attempting to complete a problem from W3Resource. Here is what I came up with, which works. How can I shorten it?</p>
<pre><code>function dateGet(){
var newDate = new Date();
var newMonth = newDate.getMonth() + 1;
var newDay = newDate.getDate();
var newYear = newDate.getFullYear();
var twoYear = (""+newYear).split("");
var combinedYear = twoYear[2] + twoYear[3];
var fullDate = 0;
if (newMonth < 10){
fullDate += 0 + newMonth + '/';
} else {
fullDate += newMonth + '/';
}
if (newDay < 10){
fullDate += 0 + newDay + '/';
} else {
fullDate += newDay + '/';
}
if (combinedYear < 10){
fullDate += 0 + combinedYear;
} else {
fullDate += combinedYear;
}
console.log(fullDate);
}
</code></pre>
| [] | [
{
"body": "<p>You are wanting to shorten your code. Your code is meant to format the current date as <code>MM/DD/YY</code>. This can be accomplished by treating it the parts as strings appended to a \"0\" incase they are less than 10 so 7 becomes \"07\" and 27 becomes \"027\". Once this is done, you can use the... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T01:02:56.350",
"Id": "200241",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"datetime",
"formatting"
],
"Title": "Displaying the date in MM/DD/YY format"
} | 200241 |
<p>I come from Java/Swift environment. So, I'm used to show the user of my code only "<strong>what is necessary</strong>".</p>
<p>For JavaScript I use Visual Code. </p>
<p>When I try to use the Intellisense feature, it shows all my functions/methods when I import it.</p>
<p>So, to hide the unnecessary functions, I opted for using nested functions.</p>
<p>Check out this quicksort code:</p>
<pre><code>/**
* Sorts the Array in-place
*
* @param {Array.<Number | String>} array Array to be sorted
*/
function sort(array) {
quickSort(array, 0, array.length - 1);
/**
* Quicksort implementation
*
* @param {Array.<Number | String>} array
* @param {Number} start Start index of the array for quicksort
* @param {Number} end End index of the array for quicksort
*/
function quickSort(array, start, end) {
if (start < end) {
let pivot = partition(array, start, end);
quickSort(array, start, pivot - 1);
quickSort(array, pivot + 1, end);
}
/**
* Partitions the array for Quicksort
*
* @param {Array.<Number | String>} array
* @param {Number} left Starting index of starting of array/sub-array
* @param {Number} right Ending index of starting of array/sub-array
* @returns {Number} Returns pivot index
*/
function partition(array, left, right) {
let pivot = array[right];
let i = left - 1;
for (var j = left; j < right; j++) {
if (array[j] <= pivot) {
i++;
let temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
let temp = array[i + 1];
array[i + 1] = array[right];
array[right] = temp;
return i + 1;
}
}
}
</code></pre>
<p>Is this nesting appropriate? Because I(<strong>beginner</strong>) feel like if the nested functions are big, the readability(I mean like figuring out what the code is doing) is an issue.</p>
<p>Or should I just follow the classic <code>_</code> before the function names to indicate it as a private or not meant to be used by the user?</p>
<p><strong>A simple code breaking example</strong>:</p>
<blockquote>
<p>For the user of the <code>sort()</code>, <code>partition()</code> and <code>quickSort()</code> is an
unnecessary functions. Which in-turn can cause collisions if the user
names their function <code>partition()</code> (because I might not have mentioned
<code>partition()</code> in my API as it is not usable on its own).</p>
</blockquote>
<p>And also any advice to improve the above code is welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T02:54:56.537",
"Id": "385410",
"Score": "0",
"body": "You don't need to nest those functions for them to work: https://jsfiddle.net/xm4ycq5n/. That being said, your question is not exactly clear: what do you mean by *unnecessary fun... | [
{
"body": "<h2>Nesting functions</h2>\n<p>There is nothing wrong with your approch, a few years back and I would have not said so as some browsers would parse functions within functions each time they were call, with the obvious performance hit. That is a thing of the past and functions are parsed then cached f... | {
"AcceptedAnswerId": "200255",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T01:42:12.720",
"Id": "200245",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"functional-programming",
"quick-sort"
],
"Title": "Quicksort in JavaScript, using nested functions"
} | 200245 |
<p>I wrote a function, <code>scan_ps()</code>, for scanning <code>/proc</code>, to replace a combination of <code>popen()</code> and <code>ps(1)</code>.</p>
<p><code>scan_ps()</code> scans /proc, calling <code>filter()</code> on each /proc/[pid]. Entries for which filter() returns nonzero are stored in strings allocated via malloc(3), and collected in array <code>ps_list</code>. If /proc/[pid]/cmdline is empty, the entry will not be stored. And return value is the count of entries.</p>
<p>But I wonder that I have to add or remove some corner-case handlings for <code>read()</code>, <code>malloc()</code>, or <code>realloc()</code>.</p>
<pre><code>int scan_ps(struct my_proc ***ptr, int (*filter)(const struct my_proc *)) {
DIR * dirp;
struct dirent * dp;
int count = 0;
pid_t pid;
char path[MAX_LEN_STR], buf[MAX_LEN_STR];
int fd, n;
unsigned int size = 16;
struct my_proc ** ps_list, ** ps_list2;
struct my_proc * current_ps;
dirp = opendir("/proc");
if (NULL==dirp)
return -1;
ps_list = malloc(sizeof(struct my_proc *)*size);
if (ps_list==NULL) {
printf("%s: malloc failed(ps_list)\n",__func__);
goto failed_closedir;
}
while (NULL != (dp = readdir(dirp))) {
pid = atoi(dp->d_name);
if (0 == pid)
continue;
snprintf(path, sizeof(path), "/proc/%u/cmdline", pid);
fd = open(path, O_RDONLY);
if (fd < 0) {
printf("%s: failed to open() (%d)\n",__func__, errno);
continue;
}
n = read(fd, buf, MAX_LEN_STR);
if (0 == n) {
// cmdline is empty. maybe kernel process.
printf("%s: pid:%u cmdline is empty!\n",__func__, pid);
close(fd);
continue;
}
n = (MAX_LEN_STR - 1) > n ? n : (MAX_LEN_STR - 1);
buf[n] = '\0';
close(fd);
current_ps = malloc(sizeof(struct my_proc));
if (current_ps==NULL) {
printf("%s: malloc failed\n",__func__);
goto failed_ps_list;
}
current_ps->pid = pid;
strncpy_v2(current_ps->cmdline, buf, MAX_LEN_STR);
if ( !filter(current_ps) ) {
printf("%s: let it go. currnet_ps\n", __func__);
free(current_ps);
continue;
}
// prepare ps_list
if (count!=0 && (count%16)==0) {
size += 16;
ps_list2 = realloc(ps_list, sizeof(struct my_proc *)*size);
if (ps_list2==NULL) {
printf("%s: malloc failed(ps_list2)\n",__func__);
goto failed;
}
ps_list = ps_list2;
}
ps_list[count++] = current_ps;
}
closedir(dirp);
*ptr = ps_list;
return count;
failed:
free(current_ps);
failed_ps_list:
while(count--) {
free(ps_list[count]);
}
free(ps_list);
failed_closedir:
closedir(dirp);
return -1;
}
</code></pre>
<p><code>scan_ps()</code> works with below code.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#define FALSE (0)
#define TRUE (!FALSE)
#define MAX_LEN_STR 256
struct my_proc {
pid_t pid;
char cmdline[256];
};
int true_filter(const struct my_proc * a) {
return TRUE;
}
char *strncpy_v2(char *dest, char *src, unsigned int size){
if (size==0) return dest;
dest[--size] = '\0';
return strncpy(dest, src, size);
}
int main(){
int n;
struct my_proc ** ps_list;
n = scan_ps(&ps_list, true_filter);
if (n<0) {
printf("%s: n=%d something wrong!\n", __func__, n);
return -1;
}
printf("%s: n=%d\n", __func__, n);
while (n--) {
printf("%s: %u, %s\n", __func__, ps_list[n]->pid, ps_list[n]->cmdline);
free(ps_list[n]);
}
free(ps_list);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T00:34:48.940",
"Id": "385573",
"Score": "0",
"body": "I updated my question to show `main()`, `struct my_proc`, and etc. Now, there is no uncompleted part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07... | [
{
"body": "<blockquote>\n <p>I wonder that I have to add or remove some corner-case handlings for read(), malloc(), or realloc().</p>\n</blockquote>\n\n<pre><code>int scan_ps(struct my_proc ***ptr, int (*filter)(const struct my_proc *));\n</code></pre>\n\n<p><strong>Make review easier</strong></p>\n\n<p>Alloca... | {
"AcceptedAnswerId": "200448",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T02:58:37.973",
"Id": "200249",
"Score": "3",
"Tags": [
"c",
"linux"
],
"Title": "Function for scanning /proc"
} | 200249 |
<blockquote>
<p>Write a piece of functioning code that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].</p>
</blockquote>
<pre><code>* tests use Jasmine can be found http://jsbin.com/harofo/4/edit?html,js,output
* @input array
* @output array
*/
function flatten(arr) {
// this function is called in recursion mode
let result = [];
if (arr && arr.length > 0) {
arr.forEach(function(value) {
if(Array.isArray(value)) {
result = result.concat(flatten(value));
} else {
result.push(value);
}
});
}
return result;
};
</code></pre>
| [] | [
{
"body": "<p>I cannot figure out better solution than yours, but I can suggest more concise code, though less readable.</p>\n\n<pre><code>function flatten(arr) {\n if (!Array.isArray(arr)) { return []; }\n return arr.reduce(function(acc, x) {\n return acc.concat( Array.isArray(x) ? flatten(x) : [x... | {
"AcceptedAnswerId": "200318",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T05:31:25.093",
"Id": "200254",
"Score": "4",
"Tags": [
"javascript",
"jasmine"
],
"Title": "Flatten an array of arbitrarily nested arrays of integers"
} | 200254 |
<p>Take this:</p>
<pre><code>has_competitors:function(){
var c = false;
_.each(this.competitors, function(obj, index){ // lodash here
if(obj.name && obj.name.trim() !== ''){
c = true;
return false; // to break the loop
}
});
return c;
}
</code></pre>
<p>I don't like the form of this, but till now I didn't find a more concise way. Could you suggest a better way? :) I mean, less lines.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T14:03:38.027",
"Id": "385453",
"Score": "2",
"body": "What does this function do? Please tell us, and make that the title of the question — see [ask]. Also tell us what `_` is — use the [tag:lodash.js] or [tag:underscore.js] tag as ... | [
{
"body": "<p>I assume you are using <a href=\"https://lodash.com/\" rel=\"nofollow noreferrer\">lodash</a> library.</p>\n\n<p>You may use <a href=\"https://lodash.com/docs/#some\" rel=\"nofollow noreferrer\">_.some</a> function.</p>\n\n<blockquote>\n <p>Checks if predicate returns truthy for any element of co... | {
"AcceptedAnswerId": "200258",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T07:35:08.087",
"Id": "200257",
"Score": "1",
"Tags": [
"javascript",
"lodash.js"
],
"Title": "Checking if any competitors have a non-empty name"
} | 200257 |
<p>My function works pretty slowly with big results from the db (420000 records and growing). Can some one give me any proposal to make it faster? </p>
<pre><code> public void GenerateExcelFileWithSPResultData(IEnumerable<Plans_Result> datasource, string excelFile)
{
var excelPackage = new ExcelPackage();
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("Plans");
ws.Cells[1, 1].Value = "ACC_DATE";
ws.Cells[1, 2].Value = "DUE_DATE";
ws.Cells[1, 3].Value = "IDENTIFIER_VALUE";
ws.Cells[1, 4].Value = "INSTALLMENT_NO";
ws.Cells[1, 5].Value = "PRINCIPAL_AMT_DUE";
ws.Cells[1, 6].Value = "SPA";
for (int i = 0; i < datasource.Count(); i++)
{
ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).ACC_DATE;
ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).DUE_DATE;
ws.Cells[i + 2, 3].Value = datasource.ElementAt(i).IDENTIFIER_VALUE;
ws.Cells[i + 2, 4].Value = datasource.ElementAt(i).INSTALLMENT_NO;
ws.Cells[i + 2, 5].Value = datasource.ElementAt(i).PRINCIPAL_AMT_DUE;
ws.Cells[i + 2, 6].Value = datasource.ElementAt(i).SPA;
}
using (ExcelRange rng = ws.Cells["A1:F1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.Yellow);
rng.Style.Font.Color.SetColor(Color.Black);
}
byte[] data = excelPackage.GetAsByteArray();
File.WriteAllBytes(excelFile, data);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T09:55:45.650",
"Id": "385437",
"Score": "1",
"body": "I can recommend taking a look at Excel-OleDb and read/write excel sheets as if they were databases... this is super fast if you don't necessariliy have to do other things."
},
... | [
{
"body": "<p>If you can't use the suggestions in the comments by t3chb0t or tinstaafl, you could maybe use the <strong><a href=\"https://docs.microsoft.com/en-us/office/open-xml/open-xml-sdk\" rel=\"nofollow noreferrer\">Open XML SDK</a></strong>.</p>\n\n<p>In your current code it is rather inefficient that yo... | {
"AcceptedAnswerId": "200270",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T08:35:35.503",
"Id": "200264",
"Score": "3",
"Tags": [
"c#",
"performance",
"excel"
],
"Title": "Export to Excel From DB is too slow"
} | 200264 |
<h1>Intro</h1>
<p>I've decided to learn <a href="/questions/tagged/haskell" class="post-tag" title="show questions tagged 'haskell'" rel="tag">haskell</a>, because I've always enjoyed the functional aspect of Python and want to explore other languages that use this concept. I'm still stumbling in the dark most of the time, so would greatly appreciate <em>any</em> improvements.</p>
<h1>Description</h1>
<p><a href="https://app.codesignal.com/arcade/graphs-arcade/kingdom-roads/" rel="nofollow noreferrer">Challenge source</a></p>
<p>A road system is considered efficient if it is possible to travel from any city to any other city by traversing at most 2 roads.</p>
<p><strong>Example</strong></p>
<p>For <code>n = 6</code> and <code>roads = [[3, 0], [0, 4], [5, 0], [2, 1], [1, 4], [2, 3], [5, 2]]</code></p>
<p>the output should be <code>True</code></p>
<p>Here's how the road system can be represented:</p>
<p><a href="https://i.stack.imgur.com/a7YHW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a7YHW.png" alt="enter image description here"></a></p>
<h1>Code</h1>
<pre><code>middlePoints k n roads = [i | i <- [0..n-1], elem [k,i] roads || elem [i,k] roads]
thoughMiddlePoints k x n roads = or [(elem [points !! i,x] roads || elem [x, points !! i] roads) | i <- [0..(length points - 1)]]
where
points = middlePoints k n roads
reachable k x n roads = elem [k,x] roads || elem [x,k] roads || (thoughMiddlePoints k x n roads)
efficientRoadNetwork n roads = all (==True) [ all (==True)[(reachable i j n roads) | j <- [0..n-1], i /= j] | i <- [0..n-1]]
</code></pre>
| [] | [
{
"body": "<p>I find <code>!!</code> and once-used definitions smelly.</p>\n\n<p>A passed around environment like <code>roads</code> might as well open a scope that spans all uses of it.</p>\n\n<pre><code>efficientRoadNetwork roads n = and\n [ edge i j || any (\\k -> edge i k && edge k j) [0..n-1]\n... | {
"AcceptedAnswerId": "200311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T08:36:49.257",
"Id": "200265",
"Score": "3",
"Tags": [
"beginner",
"programming-challenge",
"haskell",
"graph"
],
"Title": "Efficient Road Network"
} | 200265 |
<p>I have written a simple configuration file reader and writer in D that is intended to parse <code>string[string]</code> associative arrays (the whole file is one array) and everything will either be a string or <code>null</code>. I would love any suggestions to help shorten or optimize the code.</p>
<pre><code>import std.stdio: File;
import std.string: indexOf, strip, stripRight, split, startsWith;
import std.range: enumerate;
import std.algorithm: remove;
/// Read a simple configuration in the format 'key = value' from `std.stdio.File`.
string[string] readConfig(File configFile) {
configFile.rewind();
string[string] configData;
foreach (text; configFile.byLine()) {
text = text.strip();
if (text.length == 0 || text[0] == '#')
continue;
const ptrdiff_t commentIndex = text.indexOf('#');
const ptrdiff_t assignIndex = text.indexOf('=');
if (commentIndex > -1)
text = text[0 .. commentIndex];
const string key = text[0 .. assignIndex].idup.stripRight();
string value = text[assignIndex + 1 .. $].idup.strip();
if (value == "null")
value = null;
configData[key] = value;
}
return configData;
}
// From path
string[string] readConfig(const string configPath) {
File configFile = File(configPath);
const string[string] configData = configFile.readConfig();
configFile.close();
return configData;
}
/// Write a string[string] as configuration data to a file.
void writeConfig(File configFile, const string[string] configData) {
configFile.rewind();
string[] configKeys = configData.keys();
string textBuffer;
foreach (text; configFile.byLine()) {
const char[] stripped = text.strip();
const long varIndex = stripped.startsWithAny(configKeys);
if (varIndex > -1) {
textBuffer ~= configKeys[varIndex] ~ " = " ~ (configData[configKeys[varIndex]] || "null") ~ '\n';
configKeys = configKeys.remove(varIndex);
} else
textBuffer ~= text ~ '\n';
}
foreach (varName; configKeys) {
textBuffer ~= varName ~ " = " ~ (configData[varName] || "null") ~ '\n';
}
configFile.truncate(0);
configFile.write(textBuffer);
}
// From path
void writeConfig(const string configPath, const string[string] configData) {
File configFile = File(configPath, "w+");
configFile.writeConfig(configData);
configFile.close();
}
/// Find and replace a variable value in a configuration file.
void setVariable(File configFile, const string varName, const string varValue) {
configFile.rewind();
string textBuffer;
bool varFound;
foreach (text; configFile.byLine()) {
const char[] stripped = text.strip();
if (stripped.startsWith(varName)) {
textBuffer ~= varName ~ " = " ~ (varValue || "null") ~ '\n';
varFound = true;
} else
textBuffer ~= text ~ '\n';
}
if (!varFound)
textBuffer ~= varName ~ " = " ~ (varValue || "null") ~ '\n';
configFile.truncate(0);
configFile.write(textBuffer);
}
/// From path
void setVariable(const string configPath, const string varName, const string varValue) {
File configFile = File(configPath, "w+");
configFile.setVariable(varName, varValue);
configFile.close();
}
/// Cross-platform function truncate an `std.stdio.File` at an offset position in bytes.
void truncate(File file, long offset) {
version (Windows) {
import core.sys.windows.windows: SetEndOfFile;
file.seek(offset);
SetEndOfFile(file.windowsHandle());
} else version (Posix) {
import core.sys.posix.unistd: ftruncate;
ftruncate(file.fileno(), offset);
} else
static assert(0, "truncate() is not implimented for thos OS version.");
}
private long startsWithAny(const char[] searchString, const char[][] compareStrings) {
foreach (index, compare; compareStrings.enumerate())
if (searchString.startsWith(compare))
return index;
return -1;
}
</code></pre>
<p>An example configuration file can be seen at <a href="https://github.com/spikespaz/windows-tiledwm/blob/master/hotkeys.conf" rel="nofollow noreferrer">https://github.com/spikespaz/windows-tiledwm/blob/master/hotkeys.conf</a>.</p>
| [] | [
{
"body": "<pre><code>string value = text[assignIndex + 1 .. $].idup.strip();\n</code></pre>\n\n<p>Since you're using <code>stripRight</code> on the line above, why not <code>stripLeft</code> here? Also, instead of doing <code>idup.strip</code>, use <code>strip.idup</code> - that way you aren't allocating space... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T09:34:45.200",
"Id": "200266",
"Score": "4",
"Tags": [
"file",
"library",
"configuration",
"d"
],
"Title": "Minimalist config file reader/writer"
} | 200266 |
<p>I am writing a Comparator for my TreeMap. It looks like this:</p>
<pre><code>private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR =
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int cmp = o1.toLowerCase().compareTo(o2.toLowerCase());
if (cmp != 0) return cmp;
return o1.compareTo(o2);
}
};
</code></pre>
<p>My IDE hints me that it could be written in a lambda. I came up with this idea:</p>
<pre><code>private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR_LAMBDA =
(s1, s2) ->
s1.toLowerCase().compareTo(s2.toLowerCase()) == 0 ?
s1.compareTo(s2) : s1.toLowerCase().compareTo(s2.toLowerCase());
</code></pre>
<p>But then I am duplicating the first call <code>s1.toLowerCase().compareTo(s2.toLowerCase()</code>. This is doing two String manipulation and one comparison more than the not lambda expression.</p>
| [] | [
{
"body": "<p>Even in the lambda, the RHS can be a code block with braces. </p>\n\n<pre><code>private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR_LAMBDA = \n(s1, s2) -> {\n int cmp = o1.toLowerCase().compareTo(o2.toLowerCase());\n if (cmp != 0) return cmp;\n\n return o1.compare... | {
"AcceptedAnswerId": "200292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T13:47:35.443",
"Id": "200274",
"Score": "3",
"Tags": [
"java",
"performance",
"sorting",
"comparative-review",
"lambda"
],
"Title": "String comparator as a lambda"
} | 200274 |
<p>I am loading 3000 individual icons at run time one of my controls uses large icons, the other uses small icons. This works however seems terribly inefficient. The only way I can get the icons to be available in the small/large size is to have multiple image lists and have to load the file twice into each list.</p>
<pre><code> public partial class Form1 : Form
{
ImageList imageListSmall = new ImageList();
ImageList imageListLarge = new ImageList();
BackgroundWorker IconLoaderBGWorker = new BackgroundWorker();
DirectoryInfo IconDir = new DirectoryInfo("icons");
FileInfo[] IconFiles;
public Form1()
{
InitializeComponent();
// Setup Icon Lists
imageListSmall.ImageSize = new Size(16, 16);
imageListSmall.ColorDepth = ColorDepth.Depth32Bit;
imageListLarge.ImageSize = new Size(32, 32);
imageListLarge.ColorDepth = ColorDepth.Depth32Bit;
// Setup Progress bar events and Icon Loader
IconLoaderBGWorker.DoWork += new DoWorkEventHandler(bg_DoWork);
IconLoaderBGWorker.WorkerReportsProgress = true;
IconLoaderBGWorker.ProgressChanged += new ProgressChangedEventHandler(bg_ProgressChanged);
IconLoaderBGWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
IconFiles = IconDir.GetFiles("*.png");
int allFiles = IconFiles.Count();
progressBar1.Maximum = allFiles;
}
private void bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void bg_DoWork(object sender, DoWorkEventArgs e)
{
int i = 0;
foreach (FileInfo fileinfo in IconFiles)
{
imageListLarge.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), Image.FromFile(fileinfo.FullName));
imageListSmall.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), Image.FromFile(fileinfo.FullName));
IconLoaderBGWorker.ReportProgress(++i);
Application.DoEvents();
}
}
private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
object result = e.Result;
progressBar1.Dispose();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T14:54:35.453",
"Id": "385459",
"Score": "1",
"body": "You're saying that the process is inefficient. How much time does it take to load the icons? Also plsease include the rest of the code. There are a couple of variables that are u... | [
{
"body": "<p>I guess I was able to figure it out, not sure how I missed it but by simply adjusting the bg_DoWork the application loads twice as fast, as it only creates an Image once instead of twice.</p>\n\n<pre><code> private void bg_DoWork(object sender, DoWorkEventArgs e)\n {\n int i = 0;\n ... | {
"AcceptedAnswerId": "200293",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T14:21:40.393",
"Id": "200276",
"Score": "4",
"Tags": [
"c#",
"performance",
"io",
"winforms"
],
"Title": "Loading icons in two different sizes"
} | 200276 |
<blockquote>
<p>You are given an array of <em>n</em>+2 elements. All elements of the array are in range 1 to <em>n</em>. All elements occur once except two numbers, which occur twice. Your task is to find the two repeating numbers.</p>
</blockquote>
<p>My solution is:</p>
<pre><code>t=int(input()) #number of test cases
for _ in range(t):
n=int(input()) # no. of array elements
l=[int(x) for x in input().split()] #array elements
for i in range(1,n-1):
if l.count(i)==2: # using count function to count the elements
print(i,end=' ')
print()
</code></pre>
<p>How can I improve it? Currently, it shows time limit exceeded on hackerrank.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T14:51:01.953",
"Id": "385458",
"Score": "1",
"body": "You have the challenge source?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T15:16:35.553",
"Id": "385471",
"Score": "2",
"body": "D... | [
{
"body": "<p><strong>Your approach:</strong> Count iterates throuh the whole array for every element. That mean n^2 times. \n<strong>Better solution:</strong> Do not compare numbers that were already compared. You should compare a number only with numbers infront of it.</p>\n\n<pre><code>#list with your number... | {
"AcceptedAnswerId": "200284",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T14:35:59.927",
"Id": "200277",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Find the repeated elements in a list"
} | 200277 |
<p>I've recently answered <a href="https://stackoverflow.com/questions/51515419/task-return-a-streamreader-in-c-sharp/51516742#51516742">a question on Stack Overflow</a> where the asker was wondering how to read from the standard out of a child process he was spawning inside a <code>Task.Run</code>, presumably so as to avoid blocking until it starts up and starts producing output.</p>
<p><a href="https://stackoverflow.com/a/51516742/41655">My answer</a>, cleaned up a bit as per Visual Studio+R#s code analysis suggestions, and having added the usage, was this:</p>
<pre><code>using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace MyDism
{
class Program
{
static async Task Main(string[] args)
{
var dismOutputTask = new Program().WithDismAsync("/?", async sr =>
{
string line;
while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null)
{
if (line.TrimEnd().EndsWith(":"))
{
return line.ToLower();
}
}
return "oopsie-daisy";
});
var dismOutput = await dismOutputTask.ConfigureAwait(false);
await Console.Out.WriteLineAsync(dismOutput).ConfigureAwait(false);
}
static string GetDismPath()
{
var windowsDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
var systemDir = Environment.Is64BitOperatingSystem ? "SysWOW64" : "System32";
var dismExePath = Path.Combine(windowsDir, systemDir, "dism.exe");
return dismExePath;
}
public Task<TResult> WithDismAsync<TResult>(string args, Func<StreamReader, Task<TResult>> func)
{
return Task.Run(async () =>
{
var proc = new Process
{
StartInfo =
{
FileName = GetDismPath(),
Verb = "runas",
Arguments = args,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
}
};
proc.Start();
// do something with the child's stdout
var result = await func(proc.StandardOutput).ConfigureAwait(false);
// try and make sure the process exits cleanly but don't wait for this before returning result
Cleanup(proc);
return result;
});
}
private void Cleanup(Process proc)
{
Task.Run(async () =>
{
proc.StandardInput.Close();
char[] buf = new char[0x1000];
while (await proc.StandardOutput.ReadBlockAsync(buf, 0, buf.Length).ConfigureAwait(false) != 0) { }
while (await proc.StandardError.ReadBlockAsync(buf, 0, buf.Length).ConfigureAwait(false) != 0) { }
proc.WaitForExit();
proc.Dispose();
});
}
}
}
</code></pre>
<p>In brief testing it seemed to work fine, and "dism /?" seems to produce enough output to trigger the possible bug where the child process could block indefinitely on writing to its stdout.</p>
<p>However, I'm not an expert on the details of practical use of <code>async..await</code>, so I figured out this would be a good way to learn through advice on how to do things better.</p>
<hr>
<p>Areas of interest I've thought about until now are:</p>
<ol>
<li><p>I admit I've peppered the code with <code>ConfigureAwait(false)</code> because the R# checker complained I should really do that. That said I don't know precisely what difference using <code>false</code> vs. <code>true</code> as the parameter here means, and what effect would it have.</p>
<p>I'm <em>guessing</em> it means that if I use <code>true</code>, the continuation generated by the compiler will run on the same thread as the code that was running when the <code>await</code> statement that corresponds to the thus-configured task was encountered. But I'm hardly sure.</p></li>
<li><p>Following up on the previous: what would be the appropriate values for the parameter to <code>ConfigureAwait()</code> in this context. My intuition is that the <code>Main()</code> method and the lambdas in it should maybe be using <code>true</code> so as to have all the using code execute on the same thread; but then again, is it necessary if the <code>async..await</code> mechanism should take care of making sure it runs in the sequence in which it is written?</p></li>
<li><p>Assuming it is desirable to have all of the code within <code>Main</code> execute on the same thread, how would I achieve this with the async lambda passed as the <code>func</code> parameter to <code>WithDismAsync()</code>? The call to it is always awaited in the context of a thread grabbed from a pool by <code>Task.Run()</code>, so I'm not sure how to get the right context, or if I do have to bother.</p></li>
<li><p>Does the way the cleanup method punts off code that just consumes the rest of the process' output and waits for it to die make sense? Is there a better way to express "I don't really care what happens to this process but I don't want to keep it hanging around?" Obviously this depends on what said process really does, but assume for now that once it stops getting input, it will at some point in the future cease producing output that's not interesting to the calling code. (To avoid bloating this question more, I'm not expressly concerned with handling the process returning a nonzero exit code or handling its stderr.)</p></li>
</ol>
<p>Some of these might be better suited for SO proper than CR.SE, so let's say the general question I have is "am I doing <code>async..await</code> right here?"</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T08:22:35.270",
"Id": "385818",
"Score": "0",
"body": "I'd suggest starting here: https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html which explains the use of ConfigureAwait(false) nicely. You're also conflating thr... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T15:49:52.717",
"Id": "200287",
"Score": "1",
"Tags": [
"c#",
"async-await",
"child-process"
],
"Title": "An `async..await` based way to handle the output of a child process"
} | 200287 |
<p>I have this C++ code that implements a rectangular numerical integration. It evaluates the \$K\$-dimensional integral </p>
<p>$$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$
where \$F_U\$ is the cdf and \$f_U\$ is the pdf.</p>
<pre><code>#include <iostream>
#include <cmath>
using namespace std;
float pdf(float u){
return (1/(pow(1+u, 2)));
}
float cdf(float u){
return (1 - 1/(u+1));
}
// The main function that implements the numerical integration,
//and it is a recursive function
float integ(float h, int k, float du){
float res = 0;
if (k == 1){
res = cdf(h);
}else{
float u = 0;
while (u < h){
res += integ(h - u, k - 1, du)*pdf(u)*du;
u += du;
}
}
return res;
}
int main(){
float du = 0.0001;
int K = 3;
float gamma[4] = {0.31622777, 0.79432823,
1.99526231, 5.01187234};
int G = 50;
int Q = 2;
for (int i = 0; i < 4; i++){
if ((G-Q*(K-1)) > 0){
float gammath = (gamma[i]/Q)*(G-Q*(K-1));
cout<<1-integ(gammath, K, du)<< endl;
}
}
return 0;
}
</code></pre>
<p>I am facing a speed problem, although I switched to C++ from Python and MATLAB, because C++ is faster. The problem is that I need a small step size <code>du</code> to get an accurate evaluation of the integration. </p>
<p>Basically, I want to evaluate the integral at 4 different points defined by gammath, which is a function of other defined parameters. </p>
<p>Is there anyway I can speed up this program? I already have 25x+ speed factor over the same code in Python, but still the code takes too long (I ran it all night, and it wasn't finished in the morning). And this is only for K=3, and G=50. In other cases I want to test K = 10, and G = 100 or 300.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T17:13:07.590",
"Id": "385500",
"Score": "0",
"body": "Do you compile with -O3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T17:41:00.413",
"Id": "385507",
"Score": "0",
"body": "@JVApen... | [
{
"body": "<p>I see a few things that may help you improve your program.</p>\n\n<h2>Avoid <code>pow</code> for <code>float</code></h2>\n\n<p>The use of <code>pow</code> converts the argument to a <code>double</code> and returns a <code>double</code>. If you're casting the result to a <code>float</code> anyway,... | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T16:42:40.793",
"Id": "200289",
"Score": "7",
"Tags": [
"c++",
"performance",
"c++11",
"numerical-methods"
],
"Title": "Implementing numerical integration"
} | 200289 |
<p>I would like to ask for code review for my Python histogram word counter. </p>
<pre><code># Given a body of text, return a hash table of the frequency of each word.
"""
# I use a hash map as my data structure to create the histogram
# and add words into the dictionary
# if words are not in the dictionary, then I add those word into the dictionary
# final output is that we return the dictionary
"""
# Word Counter
# Given an body of text, return a hash table of the frequency of each word.
# Parameters
# Input: text {String}
# Output: {Hash Table}
# Constraints
# Capital and lower case versions of the same word should be counted is the same word.
# Remove punctuations from all words.
# Time: O(N)
# Space: O(N)
# Where N is the number of characters in the string.
# Examples
# 'The cat and the hat.' --> '{ the: 2, cat: 1, and: 1, hat: 1 }'`
# 'As soon as possible.' --> '{ as: 2, soon: 1, possible: 1 }'`
# 'It's a man, it's a plane, it's superman!' --> '{ its: 3, a: 2, man: 1, plane: 1, superman: 1 }'`
def word_count(sentence):
word_counter = {}
wordlist = sentence.lower().split()
for word in wordlist:
word = re.sub('[.,:*! ]', '', word)
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
return word_counter
example = word_count("It's a man, it's a plane, it's superman!")
</code></pre>
| [] | [
{
"body": "<p>Several things can be improved in your existing code. First and foremost being, replacing your usage of <code>re</code> module. Regex matching is very heavy. You have a defined set of characters being replaced. Use <a href=\"https://devdocs.io/python~2.7/library/stdtypes#str.replace\" rel=\"norefe... | {
"AcceptedAnswerId": "200294",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T17:41:43.833",
"Id": "200291",
"Score": "10",
"Tags": [
"python"
],
"Title": "Histogram word counter in Python"
} | 200291 |
<p>I'm not a scripting expert by any means, but I put together some code that I needed for Google Sheets. The good news is that it actually works! </p>
<p>However, it's noticeably slow to run (about 15 seconds). I'm sure it's not optimized to deal with arrays and other fun things that I don't fully understand...</p>
<pre><code>function ShowHideClosedCards() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var lastRow = sheet.getLastRow();
strVisible = sheet.getRange('N1').getValue(); //Get the value of N1
if (strVisible == '** Closed accounts are visible **') { //If the closed accounts are visible...
for( i=6 ; i<=lastRow ; i++) { // Start with row 6 and continue through the last row: i <= lastRow
var status = sheet.getRange("F"+i).getValue(); //Get the value of the cell.
if (status !== "") { // If there's something in the "Date Closed" cell, then that should mean it's closed
sheet.hideRows(i); // Hide the row
}
}
sheet.getRange('N1').setValue('** Closed accounts are hidden **');
} else { // Otherwise, assume the closed accounts are hidden...
for( i=6 ; i<=lastRow ; i++) { // Start with row 6 and continue through the last row: i <= lastRow
var status = sheet.getRange("F"+i).getValue(); //Get the value of the cell.
if (status !== "") { // If there's something in the "Date Closed" cell, then that should mean it's closed
sheet.showRows(i); // Show the row
}
}
sheet.getRange('N1').setValue('** Closed accounts are visible **');
}
}
</code></pre>
<p>The gist of it is that it should go through each row (from 6 through 500) and if there's anything in column F of that row, hide the row. Then it marks one cell (N1) to let the user know that the closed accounts are hidden.</p>
<p>If the user runs the code again, it should do the same thing, but unhide those rows (and only those rows). Then it marks N1 again to let the user know that the closed accounts are visible.</p>
<p>Any suggestions on how to get it to run faster?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T19:39:04.977",
"Id": "385529",
"Score": "1",
"body": "There is an entire page in the docs about how to improve performance and what DOs and DON'Ts there are. In your case you should not be accessing each cell one by one with`sheet.g... | [
{
"body": "<p>In order to improve the performance of your script you should read cell values from an array that represents the entire range that your are going to scan.</p>\n\n<p>This means that instead of repetedly calling</p>\n\n<blockquote>\n<pre><code>var status = sheet.getRange(\"F\"+i).getValue(); //Get t... | {
"AcceptedAnswerId": "200689",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T19:11:07.023",
"Id": "200296",
"Score": "1",
"Tags": [
"performance",
"google-apps-script",
"google-sheets"
],
"Title": "Hide rows where column F is not empty"
} | 200296 |
<p>I have an initialize method for a class that looks like this:</p>
<pre><code>def initialize(
site:,
name:,
date_online: '-',
date_offline: '-',
date_modified: '-',
date_tagged: '-',
tags: []
)
@site = site
@name = name
@date_online = date_online
@date_offline = date_offline
@date_modified = date_modified
@date_tagged = date_tagged
@tags = tags
end
</code></pre>
<p>However, RuboCop is telling me that I should:</p>
<pre class="lang-none prettyprint-override"><code>Metrics/ParameterLists: Avoid parameter lists longer than 5 parameters. [7/5]
</code></pre>
<p>So, what is the best way to rectify this? It's an initializer, so all those parameters are necessary. Is the desired solution to use a hash?</p>
<pre class="lang-ruby prettyprint-override"><code>def initialize(args)
@site = args[:site]
@name = args[:name]
@date_online = args[:date_online] || '-'
@date_offline = args[:date_offline] || '-'
@date_modified = args[:date_modified] || '-'
@date_tagged = args[:date_tagged] || '-'
@tags = args[:tags] || []
end
</code></pre>
<p>Then how should I manually handle the fact that <code>site</code> and <code>name</code> are required? I could add some code after the assignments that will throw an error if the required fields aren't present:</p>
<pre class="lang-ruby prettyprint-override"><code>raise ArgumentError unless @site && @name
</code></pre>
<p>That makes sense to me. But I assume the makers of RuboCop know what they're talking about, which leads me to suspect that there's a standard for this sort of thing.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T15:51:07.307",
"Id": "385884",
"Score": "0",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code ... | [
{
"body": "<p>An in-between solution for you might be:</p>\n\n<pre><code>def initialize(site:, name:, **options)\n @site = site\n @name = name\n @date_online = options[:date_online] || '-'\n @date_offline = options[:date_offline] || '-'\n @date_modified = options[:date_modified] || ... | {
"AcceptedAnswerId": "200420",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T19:58:08.640",
"Id": "200298",
"Score": "8",
"Tags": [
"ruby"
],
"Title": "Parameter list too long in initialize method"
} | 200298 |
<p>I have been working through the <a href="https://cryptopals.com" rel="nofollow noreferrer">Cryptopals</a> challenges in Ocaml. My interest in Ocaml is to better learn functional programming techniques and effective usage of the type system.</p>
<p><a href="https://cryptopals.com/sets/1/challenges/4" rel="nofollow noreferrer">Set 1 Challenge 4</a> says 'One of the 60-character strings in this file has been encrypted by single-character XOR. Find it.'</p>
<p>My code finds the correct string. I tried using user-defined types (e.g. <code>xor_input</code>, <code>xor_output</code>) to avoid passing around lots of <code>string</code> types that could easily be muddled. However, I am not sure of what is an appropriate level of type annotation. For example:</p>
<ul>
<li>is there any merit in <code>make_ranking</code> specifying a return type of <code>score</code> if it ends in <code>|> Score</code>? My understanding of Haskell is that I could use the function's type annotation to specify that it returns a <code>Score</code> and the <code>int</code> returned from the <code>fold</code> would automatically be wrapped in a <code>score</code> type - is there something similar in Ocaml? <code>|> Score</code> seems a cumbersome way to specify the return type.</li>
<li>I was also unsure how to convert to and from a user-defined type and its unwrapped value (e.g. <code>score</code> and <code>int</code>). My approach in <code>sort_results</code> and <code>output</code> (destructuring) seems inelegant to me.</li>
<li>in <code>sort_results</code> I destructure the arguments to get the scores. Does this not mean that any type with a <code>score</code> field will be accepted?</li>
</ul>
<p>(Note that <code>Hexx</code> is a module I wrote to convert a base64 encoded string to a hex string. Assume the input is a file containing a list of strings.)</p>
<pre><code>open Core
let english = "etaoin srhldcumfpgwybvkxjqzETAOINSRHLDCUMFPGWYBVKXJQZ0123456789.?!"
type score = Score of int
type xor_input = Xor_input of string
type xor_output = Xor_output of string
type result =
{
test_char : char;
score : score;
xor_input : xor_input;
xor_output : xor_output;
}
let xor c (Xor_input input) : xor_output =
String.map input ~f:(fun l -> int_of_char l |> (lxor) c |> char_of_int) |> Xor_output
let make_ranking (Xor_output str) : score =
String.fold str ~init:0 ~f:(fun total c ->
total + match String.index english c with
| Some v -> v
| None -> 100 (* arbitary value for non-letters *)
) |> Score
let make_result (input : xor_input) c : result =
let output = xor c input in
{ test_char = char_of_int c; score = make_ranking output; xor_input = input; xor_output = output }
let sort_results { score = first; _ } { score = second; _ } =
let (Score first_val) = first in
let (Score second_val) = second in
first_val - second_val
let find_best_match results : result =
let best = List.sort ~cmp:sort_results results |> List.hd in
match best with
| Some x -> x
| None -> failwith "No best result found"
let xor_line line =
let decoded = Hexx.decode line in
List.range 0 255
|> List.map ~f:(make_result (Xor_input decoded))
|> find_best_match
let output {test_char; score; xor_input; xor_output} =
let (Score s) = score in
let (Xor_input input) = xor_input in
let (Xor_output out) = xor_output in
fprintf stdout "Char: %c, Score: %d, Original: %s, Output: %s\n" test_char s input out
let () =
In_channel.read_lines "4.txt"
|> List.map ~f:xor_line
|> find_best_match
|> output
</code></pre>
| [] | [
{
"body": "<p>Congrats on tackling cryptopals! These are great exercises and very interesting to learn new languages and techniques.</p>\n\n<h2>Syntax</h2>\n\n<h3>Remove the type annotations</h3>\n\n<p>In most cases in OCaml, you don't need any type annotations. So instead of:</p>\n\n<pre><code>let make_result ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T20:44:26.823",
"Id": "200304",
"Score": "2",
"Tags": [
"type-safety",
"ocaml"
],
"Title": "Detect single-character xor (OCaml)"
} | 200304 |
<p>I am using the Windows API to register system-wide hotkeys. This requires a message loop to be created, and a handler to handle the hotkey messages. I have written two pieces of functioning code. The definitions of some functions have been redacted because they are unnecessary for the example. You just need to know that <code>readConfig()</code>, <code>registerAllHotKeys()</code>, and <code>messageLoop()</code> are functions that I wrote.</p>
<p>The design of <code>messageLoop()</code> is in question. I can either make it take one function to which the hotkey message will be passed, or I can pass an array of <code>void function()[HotKeyID] handlers</code> to call from.</p>
<p>Here is the source of <code>messageLoop()</code> when handling the arrays.</p>
<pre><code>void messageLoop(void function()[HotKeyID] handlers) {
MSG message;
while (GetMessage(&message, null, 0, 0) > 0) {
HotKeyID hkID = to!HotKeyID(message.wParam);
if (hkID in handlers)
handlers[hkID]();
}
}
</code></pre>
<p>This is the code to handle messages by calling functions defined in the array, if present.</p>
<pre><code>void main() {
string[string] hkConfig = readConfig("hotkeys.conf");
registerAllHotKeys(hkConfig);
messageLoop([
HotKeyID.TOGGLETILING: &toggleTiling,
HotKeyID.FOCUSUP: &focusUp,
HotKeyID.FOCUSDOWN: &focusDown,
HotKeyID.FOCUSLEFT: &focusLeft,
HotKeyID.FOCUSRIGHT: &focusRight,
HotKeyID.SELECTUP: &selectUp,
HotKeyID.SELECTDOWN: &selectDown,
HotKeyID.SELECTLEFT: &selectLeft,
HotKeyID.SELECTRIGHT: &selectRight,
HotKeyID.SWAPUP: &swapUp,
HotKeyID.SWAPDOWN: &swapDown,
HotKeyID.SWAPLEFT: &swapLeft,
HotKeyID.SWAPRIGHT: &swapRight,
HotKeyID.MINIMIZE: &minimize,
HotKeyID.MAXIMIZE: &maximize,
HotKeyID.TERMINATE: &terminate,
HotKeyID.FORCEKILL: &forcekill,
HotKeyID.POPOUT: &popout,
HotKeyID.POPIN: &popin,
HotKeyID.MOVEUP: &moveUp,
HotKeyID.MOVEDOWN: &moveDown,
HotKeyID.MOVELEFT: &moveLeft,
HotKeyID.MOVERIGHT: &moveRight,
HotKeyID.INCREASESIZE: &increaseSize,
HotKeyID.DECREASESIZE: &decreaseSize,
HotKeyID.INCREASEGAP: &increaseGap,
HotKeyID.DECREASEGAP: &decreaseGap
]);
}
</code></pre>
<p>Versus the code to handle the message ID directly.</p>
<pre><code>void handleMessage(HotKeyID hkID) {
switch (hkID) {
case HotKeyID.TOGGLETILING:
toggleTiling();
break;
case HotKeyID.FOCUSUP:
focusUp();
break;
case HotKeyID.FOCUSDOWN:
focusDown();
break;
case HotKeyID.FOCUSLEFT:
focusLeft();
break;
case HotKeyID.FOCUSRIGHT:
focusRight();
break;
case HotKeyID.SELECTUP:
selectUp();
break;
case HotKeyID.SELECTDOWN:
selectDown();
break;
case HotKeyID.SELECTLEFT:
selectLeft();
break;
case HotKeyID.SELECTRIGHT:
selectRight();
break;
case HotKeyID.SWAPUP:
swapUp();
break;
case HotKeyID.SWAPDOWN:
swapDown();
break;
case HotKeyID.SWAPLEFT:
swapLeft();
break;
case HotKeyID.SWAPRIGHT:
swapRight();
break;
case HotKeyID.MINIMIZE:
minimize();
break;
case HotKeyID.MAXIMIZE:
maximize();
break;
case HotKeyID.TERMINATE:
terminate();
break;
case HotKeyID.FORCEKILL:
forcekill();
break;
case HotKeyID.POPOUT:
popout();
break;
case HotKeyID.POPIN:
popin();
break;
case HotKeyID.MOVEUP:
moveUp();
break;
case HotKeyID.MOVEDOWN:
moveDown();
break;
case HotKeyID.MOVELEFT:
moveLeft();
break;
case HotKeyID.MOVERIGHT:
moveRight();
break;
case HotKeyID.INCREASESIZE:
increaseSize();
break;
case HotKeyID.DECREASESIZE:
decreaseSize();
break;
case HotKeyID.INCREASEGAP:
increaseGap();
break;
case HotKeyID.DECREASEGAP:
decreaseGap();
break;
default:
break;
}
}
void main() {
string[string] hkConfig = readConfig("hotkeys.conf");
registerAllHotKeys(hkConfig);
messageLoop(&handleMessage);
}
</code></pre>
<p>Which one?</p>
<p>The disadvantage of the array being passed to <code>messageLoop()</code> is that I can't control the arguments of the functions it calls from the pointers. An advantage is that I can programatically modify the array if I need to. Since these functions effectively modify a state machine, I don't need arguments.</p>
<p>An advantage of the switch is that I can control the arguments, however I cannot change the handlers once the <code>messageLoop()</code> has been instantiated. It is also longer, and more breakable. However it does offer more control, as all of the functions could be inline lambdas to the switch.</p>
<p>If I am correct, performance difference between the two should be negligible.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T22:05:19.937",
"Id": "200308",
"Score": "1",
"Tags": [
"comparative-review",
"event-handling",
"d"
],
"Title": "Message loop handler functions, using associative array and using switch"
} | 200308 |
<p>I was wondering if below is the correct convention for combining Wai with a Database pool.</p>
<p>What I basically do is, create a pool, partially apply a function of type <code>Pool -> Application</code> and use it to pass it to Warp's <code>run</code>. Does it look ok, or shall I refactor it?</p>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.HTTP.Types
import Network.Wai.Handler.Warp (run)
import Database.MySQL.Simple
import Data.Pool (Pool, createPool, withResource)
newConn = connect defaultConnectInfo
{ connectHost = "db"
, connectUser = "root"
, connectPassword = "secret"
, connectDatabase = "test" }
getPool = createPool newConn close 1 10 5
app :: Pool Connection -> Application
app pool _ respond = do
withResource pool $ \c -> query_ c "SELECT 1" :: IO [Only Int]
respond $ responseLBS
status200
[("Content-Type", "text/plain")]
"Hello, Web!"
main :: IO ()
main = do
putStrLn $ "http://localhost:8080/"
pool <- getPool
run 8080 $ app $ pool
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T00:20:07.853",
"Id": "385572",
"Score": "1",
"body": "Welcome to Code Review. Asking for advice on code yet to be written or implemented is off-topic for this site. See [What topics can I ask about?](https://codereview.stackexchange... | [
{
"body": "<p>I'm afraid there isn't much to remove. The <code>$</code> after <code>putStrLn</code> and between <code>app</code> and <code>pool</code> are superfluous. You could write the last two lines <code>run 8080 . app <$> getPool</code>. I'd inline <code>getPool</code>. You may be interested in <a h... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T23:28:27.080",
"Id": "200310",
"Score": "1",
"Tags": [
"mysql",
"haskell",
"connection-pool"
],
"Title": "Using MySQL with Wai and Warp"
} | 200310 |
<blockquote>
<p>Have the function ScaleBalancing(int vector, int vector) read vectors
which will contain two elements, the first being the two positive
integer weights on a balance scale (left and right sides) and the
second element being a list of available weights as positive integers.
Your goal is to determine if you can balance the scale by using the
least amount of weights from the list, but using at most only 2
weights. </p>
<p>For example: if vector is ["[5, 9]", "[1, 2, 6, 7]"] then this means
there is a balance scale with a weight of 5 on the left side and 9 on
the right side. It is in fact possible to balance this scale by adding
a 6 to the left side from the list of weights and adding a 2 to the
right side. Both scales will now equal 11 and they are perfectly
balanced. Your program should return a comma separated string of the
weights that were used from the list in ascending order, so for this
example your program should return the string 2,6 </p>
<p>There will only ever be one unique solution and the list of available
weights will not be empty. It is also possible to add two weights to
only one side of the scale to balance it. If it is not possible to
balance the scale then your program should return the string not
possible.</p>
</blockquote>
<p>How can I make improvements to my code? I also want to know if my approach was a good way to solve this problem.</p>
<pre><code>#include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
template <typename T>
bool all_Positive(const T start, const T end) {
T it;
for (it = start; it != end; it++) {
if (*it < 0) return false;
}
return true;
}
bool every_Num_Positive(std::vector<int> &integerWeights, std::vector<int> &availableWeights)
{
if (all_Positive(integerWeights.begin(),integerWeights.end()) && all_Positive(availableWeights.begin(), availableWeights.end()))
{
return true;
}
return false;
}
bool check_Length(std::vector<int> &integerWeights, std::vector<int> &availableWeights)
{
if (integerWeights.size() == 2 && !availableWeights.empty())
{
return true;
}
return false;
}
std::vector<int> find_2_Nums_That_Add_To_Difference(std::vector<int> &availableWeights, int difference)
{
std::vector<int> result;
for (std::size_t i = 0; i < availableWeights.size(); ++i)
{
for (std::size_t j = i + 1; j < availableWeights.size(); ++j)
{
if (availableWeights.at(i) + availableWeights.at(j) == difference)
{
result.push_back(availableWeights.at(i));
result.push_back(availableWeights.at(j));
}
}
}
return result;
}
std::string find_2_Nums_That_Minus_To_Difference(std::vector<int> availableWeights, int difference)
{
std::vector<int> possible;
for (std::size_t i = 0; i < availableWeights.size(); ++i)
{
for (std::size_t j = i + 1; j < availableWeights.size(); ++j)
{
if (abs(availableWeights.at(i) - availableWeights.at(j)) == difference)
{
return std::to_string(availableWeights.at(i)) + "," + std::to_string(availableWeights.at(j));
}
}
}
return "NOT POSSIBLE";
}
std::string scale_Balancing(std::vector<int> integerWeights, std::vector<int> availableWeights)
{
if (check_Length(integerWeights, availableWeights) && every_Num_Positive(integerWeights,availableWeights))
{
int difference = std::abs(integerWeights.at(1) - integerWeights.at(0));
std::vector<int> possibleResults = find_2_Nums_That_Add_To_Difference(availableWeights, difference);
if (std::find(availableWeights.begin(),availableWeights.end(),difference) != availableWeights.end())
{
return std::to_string(difference);
}
else if (!possibleResults.empty())
{
return std::to_string(possibleResults.at(0)) + "," + std::to_string(possibleResults.at(1));
}
else
{
return find_2_Nums_That_Minus_To_Difference(availableWeights, difference);
}
}
return "NOT POSSIBLE";
}
</code></pre>
| [] | [
{
"body": "<p>It looks to me that you're over thinking this a bit.</p>\n\n<p>The problem statement says that each vector will have positive integers. It is very superfluous to check for that.</p>\n\n<p>Always try to avoid using the concatenation operator(<code>+</code>) for joining strings, the <code>stringstr... | {
"AcceptedAnswerId": "200317",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T00:23:06.713",
"Id": "200312",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"programming-challenge"
],
"Title": "Demonstration of Scale Balancing"
} | 200312 |
<p>I tried solving the <a href="https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem" rel="nofollow noreferrer">Hash Tables: Ice Cream Parlor</a> question in javascript:</p>
<pre><code>'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
// Complete the whatFlavors function below.
function whatFlavors(cost, money) {
// Solution starts here
var dict1={};
var len=cost.length;
for(var i=0; i<len; i++) {
if (cost[i]<money) {
if(dict1[cost[i]] !== undefined)
{
if(Array.isArray(dict1[cost[i]]))
{
dict1[cost[i]].push(i);
}
else
{
dict1[cost[i]] = [dict1[cost[i]]];
dict1[cost[i]].push(i);
}
}
else
dict1[cost[i]] = i;
}
}
cost.sort(function(a,b) {return a-b});
for(var j=0; j<len; j++){
var left=0;
var right=len-1;
if(cost[j]<money){
var ser=money-cost[j];
while(left<right){
var mid=Math.floor((left+right)/2);
if(ser===cost[mid]){
var val1=cost[j];
var val2=cost[mid];
break;
}
if(ser<cost[mid]){
right = mid-1;
}
else{
left = mid+1;
}
}
if(val1 !== undefined && val2 !== undefined ){
break;
}
}
}
var index1;
var index2;
if (val1===val2) {
index1 = dict1[val1][0];
index2 = dict1[val2][1];
}
else{
index1 = dict1[val1];
index2 = dict1[val2];
}
if (index2 > index1) {
console.log(index1+1, index2+1);
}
else{
console.log(index2+1, index1+1);
}
// Solution ends here
}
function main() {
const t = parseInt(readLine(), 10);
for (let tItr = 0; tItr < t; tItr++) {
const money = parseInt(readLine(), 10);
const n = parseInt(readLine(), 10);
const cost = readLine().split(' ').map(costTemp => parseInt(costTemp, 10));
whatFlavors(cost, money);
}
}
</code></pre>
<p>It works for all inputs except when it is very large, for example when the input is very large for eg:<br>
<code>30733 39289
12352 19413
448 3955
74 75
12316 34744
2916 4669
1941 6571
2871 17443
34132 42603
1753 9623
7217 8111
3411 17665
3190 16653
1923 14237
6307 22944
10874 22052
967 21913
7562 7948
11038 36319
586 8260
338 1426
17083 37691
11944 15889
10347 13601
643 1653
18754 19595
9561 22822
22521 26308
114 1965
338 412
8423 9497
6371 33551
1292 3705
5634 9563
14043 14669
12566 39425
1149 2638
12664 12939
10217 29104</code><br>
it simply throws <code>Wrong Answer</code>, is there a better way to write the same script?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T15:37:53.183",
"Id": "385700",
"Score": "0",
"body": "The place to go to get help finding problems in your code is https://stackoverflow.com"
}
] | [
{
"body": "<p>The error was because of a silly mistake, in the binary search, it should be <code>while(left<=right)</code>:</p>\n\n<pre><code>'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin =&g... | {
"AcceptedAnswerId": "200314",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T01:32:35.543",
"Id": "200313",
"Score": "0",
"Tags": [
"javascript",
"array",
"hash-map"
],
"Title": "Hash Tables: Ice Cream Parlor solution in javascript"
} | 200313 |
<p>This is the same game code from my <a href="https://codereview.stackexchange.com/questions/195112/android-game-inspired-by-space-invaders-and-moon-patrol">previous question.</a> I split the code into smaller "logical units". The runnable code <a href="https://play.google.com/store/apps/details?id=dev.android.buggy" rel="nofollow noreferrer">"Moon Buggy" is available in beta</a> from the google playstore.</p>
<p>It was previously just a few classes, new I am aiming at producing a dozen classes because the code has become large and need to get split up into smaller units. </p>
<p>The base class MoonSprite.java for sprites i.e. moving objects on the screen. The code is self-explanatory, but there might be too long methods and code in the wrong place. </p>
<pre><code>import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
// This does not extend Bitmap because we might want to extend our own class instead
public class MoonSprite {
public int screenWidth;
public int screenHeight;
private int id;
private int width;
private int height;
private Bitmap bitmap;
public MoonSprite() {
}
public MoonSprite(Context context, String name) {
setId(context.getResources().getIdentifier("object3_hdpi",
"drawable", context.getPackageName()));
setBitmap(BitmapFactory.decodeResource(context.getResources(), this.getId()));
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getWidth() {
if (this.width <= 0) {
return bitmap.getWidth();
}
else {
return this.width;
}
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
</code></pre>
<p>I know that "object3_hdpi" is not a very good name for an object for several reasons and I am going to change that. Otherwise I think that the class above contains logically data that should be together (cohesion) and it has interfaces to communicate with its surroundings (coupling). And it is easy to understand. </p>
<p>But maybe I should put collision detection already in this class? Because I have put collision detection in lower sub-classes maybe duplicating code. </p>
<p>The following is a sub-class of MoonSprite: EnemyTank.java</p>
<pre><code>import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import java.util.ArrayList;
import java.util.List;
import static dev.android.jamie.MoonUtils.randomize;
public class EnemyTank extends MoonSprite {
private ArrayList<Missile> missiles;
private int tankY = 0;
public int getTankY() {
return tankY;
}
public void setTankY(int tankY) {
this.tankY = tankY;
}
public int getTankX() {
return tankX;
}
public void setTankX(int tankX) {
this.tankX = tankX;
}
private int tankX = 0;
public Bitmap getBitmapRover() {
return bitmapRover;
}
private Bitmap bitmapRover, explode;
public int getJumpHeight() {
return jumpHeight;
}
public void setJumpHeight(int jumpHeight) {
this.jumpHeight = jumpHeight;
}
private int jumpHeight;
private double retardation = 0.5;
private double buggyXdistance = 0;
public double getBuggyXdistance() {
return buggyXdistance;
}
public void setBuggyXdistance(double buggyXdistance) {
this.buggyXdistance = buggyXdistance;
}
public void increaseBuggyXdistance(double d) {
buggyXdistance = buggyXdistance + d;
}
public void decreaseBuggyXdistance(double d) {
buggyXdistance = buggyXdistance - d;
}
public double getRetardation() {
return retardation;
}
public void increaseRetardation(double d) {
retardation = retardation + d;
}
public void setRetardation(double retardation) {
this.retardation = retardation;
}
public double getDistanceDelta() {
return distanceDelta;
}
public void setDistanceDelta(double distanceDelta) {
this.distanceDelta = distanceDelta;
}
private double distanceDelta;
private Bitmap tankMissile;
protected EnemyTank(Context context, String name) {
super(context, name);
missiles = new ArrayList<>();
this.screenHeight = context.getResources().getDisplayMetrics().heightPixels;
this.screenWidth = context.getResources().getDisplayMetrics().widthPixels;
int roverId = context.getResources().getIdentifier(name,
"drawable", context.getPackageName());
bitmapRover = BitmapFactory.decodeResource(context.getResources(), roverId);
int explodeId = context.getResources().getIdentifier("explode",
"drawable", context.getPackageName());
explode = BitmapFactory.decodeResource(context.getResources(), explodeId);
int ufoMissileId = context.getResources().getIdentifier("missile_right",
"drawable", context.getPackageName());
tankMissile = BitmapFactory.decodeResource(context.getResources(), ufoMissileId);
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
}
}, randomize(20000, 18000));
}
//if tank was hit by UFO missile then return true, false otherwise
//not implemented yet
public boolean isHit(UFO ufo) {
boolean isHit = false;
return isHit;
}
//if tank was hit by UFO missile, hits a moon rock or a hole, then explode for some time
//and after a while reset to beginning of section
public void explode(Canvas canvas, Paint paint, float left, float top) {
canvas.drawBitmap(explode, left, top, paint);
}
//if rover fires a missile then draw the missile
//not implemented yet
public void fireMissile(Canvas canvas) {
}
public void draw(Canvas canvas, Paint paint, float left, float top) {
canvas.drawBitmap(bitmapRover, left, top, paint);
}
//if tank jumps then draw the jumping rover
public void jump(Canvas canvas, boolean up) {
if (up && jumpHeight < 500) {
jumpHeight = jumpHeight + 7;
if (distanceDelta < 3) distanceDelta = distanceDelta + 0.55;
} else if (jumpHeight > 0) {
jumpHeight = jumpHeight - 4;
if (distanceDelta < 3) distanceDelta = distanceDelta + 0.55;
}
}
boolean roverDestroysEnemyMissile, wasHit, waitForTimer, waitForUfoTimer;
int missileOffSetY;
// if buggy was hit by a missile then return true
private boolean checkBuggyHitByMissile(Canvas canvas, ParallaxView view, int buggyXDisplacement, double buggyXDistance, Paint paint, Bitmap buggy, int jumpHeight) {
for (Missile missile : missiles) {
if (!roverDestroysEnemyMissile && !UFO.recent && !view.waitForTimer && java.lang.Math.abs(missile.getX() - buggyXDisplacement + buggyXDistance ) < 150 ) {
UFO.recent = true;
canvas.drawBitmap(view.explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
ParallaxView.bombed--;
missileOffSetY = 0;
wasHit = true;
view.recent = true;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> {
UFO.recent = false;
waitForTimer = false;
wasHit = false;
}, 4500);
waitForTimer = true;
} else if (!roverDestroysEnemyMissile && !waitForTimer && !waitForUfoTimer && MoonBackground.checkpoint >= 'A') {
//fire list of missiles
canvas.drawBitmap(tankMissile, (float) missile.getX() , (float) (screenHeight * 0.56), paint);
missile.setX(missile.getX() - 4);
} else {
// missile.setY();
missile.setX(this.tankX-this.getBitmapRover().getWidth()/2);
}
wasHit = false;
}
return wasHit;
}
boolean alreadyExecuted = false;
private long fireTimeout = System.currentTimeMillis();
private int missileX = 25;
//return boolean if tank fires, boolean which is not yet used
private boolean checkFire() {
if (System.currentTimeMillis() - fireTimeout >= randomize(10000, 8500)) {
missileX = tankX;
if (!alreadyExecuted) {
List<Missile> thingsToBeAdd = new ArrayList<Missile>();
thingsToBeAdd.add(new Missile((int) (this.getBuggyXdistance()-this.getBitmapRover().getWidth()/2), tankY));
missiles.addAll(thingsToBeAdd);
alreadyExecuted = true;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> {
alreadyExecuted = false;
}, 10000);
}
}
return true;
}
public boolean drawMissile(ParallaxView view, Canvas canvas, Paint paint, int buggyXDisplacement, double buggyXDistance, Bitmap buggy, int jumpHeight) {
checkFire();
return checkBuggyHitByMissile(canvas, view, buggyXDisplacement, buggyXDistance, paint, buggy, jumpHeight);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T05:10:02.380",
"Id": "385587",
"Score": "0",
"body": "May I ask why did you name your class as `MoonSprite` because if `EnemyTank` is extending a class, I would suppose it would have extended `MovableObject` or `Tank` class. I'm una... | [
{
"body": "<ol>\n<li>Please keep all the class variables together, and <code>getter</code>/<code>setter</code>s together, right now they are scattered in the class.</li>\n<li>Either use Lambdas everywhere, or Anonymous classes for <code>Runnable</code>. You have used both in the class.</li>\n<li>In the <code>co... | {
"AcceptedAnswerId": "200364",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T02:26:17.287",
"Id": "200315",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"game",
"android"
],
"Title": "Collision detection on Android"
} | 200315 |
<h1>Description</h1>
<blockquote>
<p>Master Locksmith has just finished the work of his life: a combination
lock so big and complex that no one will ever open it without knowing
the right combination. He's done testing it, so now all he has to do
is put the lock back into a neutral state, as to leave no trace of the
correct combination.</p>
<p>The lock consists of some number of independently rotating discs. Each
disc has k numbers from <code>0</code> to <code>k-1</code> written around its circumference.
Consecutive numbers are adjacent to each other, i.e. <code>1</code> is between
<code>0</code> and <code>2</code>, and because the discs are circular, <code>0</code> is between <code>k-1</code>
and <code>1</code>. Discs can rotate freely in either direction. On the front of
the lock there's a marked bar going across all discs to indicate the
currently entered combination.</p>
<p>Master Locksmith wants to reset the lock by rotating discs until all
show the same number. However, he's already itching to start work on
an even greater and more complicated lock, so he's not willing to
waste any time: he needs to choose such a number that it will take as
little time as possible to reach it. He can only rotate one disc at a
time, and it takes him <code>1</code> second to rotate it by one position. Given
<code>k</code> and the <code>initialState</code> of the lock, find the number he should
choose. If there are multiple possible answers, <strong>return the smallest
one.</strong></p>
</blockquote>
<h1>Example</h1>
<blockquote>
<p>For <code>k = 10</code> and <code>initialState = [2, 7, 1]</code> </p>
<p>the output should be <code>masterLocksmith(k, initialState) = 1</code></p>
<p>It takes 1 second for the first disc to reach <code>1 (2 → 1)</code>. It takes 4
seconds for the second disc to reach <code>1 (7 → 8 → 9 → 0 → 1)</code>. The
third disc is already at <code>1</code>. The whole process can be completed in
<code>5</code> seconds. Reaching any other number would take longer, so this is
the optimal solution.</p>
</blockquote>
<h1>Constraints</h1>
<p>Guaranteed constraints:</p>
<p><code>3 ≤ k ≤ 10 ** 14</code></p>
<p><code>2 ≤ initialState.length ≤ 10**4</code></p>
<p><code>0 ≤ initialState[i] < k for all valid i</code></p>
<h1>Code</h1>
<pre><code>from operator import itemgetter
from collections import defaultdict
def masterLocksmith(k, initial_state):
occurence = defaultdict(int)
for i in initial_state:
occurence[i] += 1
num_set = set(initial_state)
num_set.add(0)
shortest = {j: 0 for j in num_set}
for i in occurence:
for j in num_set:
shortest[j] += min(abs(i-j), k - abs(i-j)) * occurence[i]
return min([[k, shortest[k]] for k in shortest], key=itemgetter(1,0))[0]
</code></pre>
<p>The TLE's were really hard, I've tried some optimization but the best I could solve this in was still \$ O(n * k) \$ which was not enough to complete the challenge. I am less concerned about readability but more how this can be sped up.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T08:03:44.270",
"Id": "385609",
"Score": "0",
"body": "What limits are you given on \\$n\\$ and \\$k\\$?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T08:06:04.093",
"Id": "385610",
"Score": ... | [
{
"body": "<p>Style nits: misspelling of <code>occurence</code>, gratuitous renaming of the problem statement's <code>initialState</code> to <code>initial_state</code>.</p>\n\n<p>I was initially skeptical of your algorithm, but I think I've convinced myself now that it's correct — even the initially mysterious ... | {
"AcceptedAnswerId": "200332",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T07:45:56.360",
"Id": "200323",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"combinatorics"
],
"Title": "Master Locksmith"
} | 200323 |
<h1>randip.py</h1>
<p>I know there are probably better, easier ways to do this.<br>
It was just a bit of a learning exercise for the sake of familiarising myself with Python.</p>
<p>It takes a single argument (positional parameter):<br>
Either a <code>4</code> (IPv4) or a <code>6</code> (IPv6). </p>
<hr>
<h3>Usage:</h3>
<p><pre><code><b>./randip.py 4</b>
61.104.170.242</pre></code></p>
<pre><code><b>./randip.py 6</b>
4bfc:391d:3ec8:68ef:0ec8:529b:166d:2ece
</code></pre>
<hr>
<h3>Code:</h3>
<pre><code>#!/usr/bin/env python3
from sys import argv
from random import randint, choice
from string import hexdigits
def random_ip(v):
if v == 4:
octets = []
for x in range(4):
octets.append(str(randint(0,255)))
return '.'.join(octets)
elif v == 6:
octets = []
for x in range(8):
octet = []
for x in range(4):
octet.append(str(choice(hexdigits.lower())))
octets.append(''.join(octet))
return ':'.join(octets)
else:
return
def main():
print(random_ip(int(argv[1])))
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>Here are a few ideas about your code.</p>\n\n<h2>Check for command line arguments</h2>\n\n<p>The code fails with an exception if it's invoked with no command line arguments because it attempts to use <code>argv[1]</code> and there isn't any. I'd suggest that it would be nice to print a \"usage\" ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T12:05:28.053",
"Id": "200337",
"Score": "38",
"Tags": [
"python",
"python-3.x",
"random",
"reinventing-the-wheel",
"ip-address"
],
"Title": "Random IP Address Generator"
} | 200337 |
<p>Need to parse MongoDB collection and save parsed data into different postgres tables. MongoDB stores documents with different <code>type</code> field, for each type need to write handler to parse the document of this type.</p>
<p>I wrote <code>Service</code> class but it is overcomplicated. I see this troubles:</p>
<ul>
<li>Bad decomposition</li>
<li>A lot of DAO classes in one class</li>
<li>Function that initializes handlers is too long</li>
</ul>
<p>How to simplify this code and improve its structure?</p>
<pre><code>package services;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Updates;
import mongodb.MongoDB;
import org.bson.Document;
import static com.mongodb.client.model.Filters.ne;
import java.text.ParseException;
import java.util.HashMap;
import org.bson.conversions.Bson;
import pg.dao.*;
import pg.InboxReader;
public class Service {
private MongoClient client;
private HashMap<String, InvoiceWorker> handlers;
private StationDAO stations;
private VpuListDAO vpu;
private CarUpRequestsDAO carUpRequestsDAO;
private CarUpResponseDAO carUpResponseDAO;
private CreatorIdDAO creatorIdDAO;
private FileSyncDAO fileSyncDAO;
private InboxReader inboxReader;
private MongoCollection<Document> inbox;
private MongoCollection<Document> inboxParsed;
public Service() {
this.client = MongoDB.getInstance();
this.handlers = new HashMap<>();
this.stations = new StationDAO();
this.inboxReader = new InboxReader();
this.vpu = new VpuListDAO();
this.carUpRequestsDAO = new CarUpRequestsDAO();
this.carUpResponseDAO = new CarUpResponseDAO();
this.creatorIdDAO = new CreatorIdDAO();
this.fileSyncDAO = new FileSyncDAO();
initHandlers();
}
private void initHandlers() {
handlers.put("file", (Document doc) -> {
final String creatorId = doc.getString("creatorId");
final String sysId = doc.getString("sysId");
if (fileSyncDAO.checkExists((String)doc.get("creatorId"), (String)doc.get("sysId"))) {
System.out.println("The entry already exists in postgres");
return;
}
fileSyncDAO.saveFileSync((String)doc.get("creatorId"),
(String)doc.get("name"),
(String)doc.get("fileHash"),
(String)doc.get("sysId"),
(Long)doc.get("dateCreated"));
System.out.println("Sync document");
System.out.println(doc.toJson());
});
handlers.put("etranInvoice", (Document doc) -> {
inboxReader.readDocument(doc);
System.out.println("Run etranInvoice handler for doc: " + doc.toJson());
});
handlers.put("etranVPU", (Document doc) -> {
if (doc.containsKey("carNumber") && doc.containsKey("invNumber")) {
final String carNumber = doc.getString("carNumber");
final String invNumber = doc.getString("invNumber");
final String vpuDate = doc.getString("vpuDate");
System.out.println(doc.toJson());
if (!vpu.exists(carNumber, invNumber)) {
insertVpu(carNumber, invNumber, vpuDate);
}else{
updateVpuDates(carNumber, invNumber, vpuDate);
}
}
});
handlers.put("carUpRequest", (Document doc) -> {
final String creatorId = doc.getString("creatorId");
if (creatorIdDAO.getCreatorId().equalsIgnoreCase(creatorId)) return;
final String carNumber = doc.getString("carNumber");
final String invNumber = doc.getString("invNumber");
if (!carUpRequestsDAO.wagonIdentifierExists(carNumber, invNumber)) {
carUpRequestsDAO.insertDocument(doc);
}
});
handlers.put("carUpResponse", (Document doc) -> {
final String creatorId = doc.getString("creatorId");
if (creatorIdDAO.getCreatorId().equalsIgnoreCase(creatorId)) return;
final String carNumber = doc.getString("carNumber");
final String invNumber = doc.getString("invNumber");
if (!carUpResponseDAO.wagonIdentifierExists(carNumber, invNumber)) {
carUpResponseDAO.insertDocument(doc);
}
});
}
private void insertVpu(String carNumber, String invNumber, String vpuDate) {
try {
long vpuDateTimestamp = inboxReader.formatDate(vpuDate);
vpu.insertVpuDate1(carNumber, invNumber, vpuDateTimestamp);
}
catch (ParseException e) {
System.out.println(e);
}
}
private void updateVpuDates(String carNumber, String invNumber, String vpuDate) {
try {
long vpuDateTimestamp = inboxReader.formatDate(vpuDate);
long date2 = vpu.selectVpuDate1(carNumber, invNumber);
if(date2 < vpuDateTimestamp){
vpu.setDate2(carNumber, invNumber, vpuDateTimestamp);
}else{
vpu.setDate1(carNumber, invNumber, vpuDateTimestamp);
}
}
catch (ParseException e) {
System.out.println(e);
}
}
public synchronized void service() {
inbox = client.getDatabase("test")
.getCollection("inbox");
inboxParsed = client.getDatabase("test")
.getCollection("inbox_parsed");
MongoCursor<Document> cursor = inbox
.find(ne("parsed", "true"))
.iterator();
parseInbox(cursor);
}
private void parseInbox(MongoCursor<Document> cursor) {
try {
while (cursor.hasNext()) {
Document doc = cursor.next();
if (doc.containsKey("type")) {
String type = doc.getString("type");
if (handlers.containsKey(type)) {
handlers.get(type).proceed(doc);
}
}
setDocumentParsed(doc);
//moveToInboxParsed(doc);
}
}
finally {
cursor.close();
System.out.println("Run service()");
}
}
private void setDocumentParsed(Document doc) {
Bson updates = Updates.set("parsed", "true");
inbox.findOneAndUpdate(doc, updates);
}
private void moveToInboxParsed(Document doc) {
inboxParsed.insertOne(doc);
inbox.deleteOne(doc);
}
}
</code></pre>
<p><code>Main.java</code>:</p>
<pre><code>import services.Service;
public class Main {
public static void main(String[] args) {
Service s = new Service();
while (true) {
s.service();
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Stating the obvious: your handlers all have a common interface (basically the same as <code>Consumer<Document></code>) and implement their respective business logic. Thus, create a common interface and implement the different handlers in their specific classes, e.g.</p>\n\n<pre><code>public ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T12:42:48.620",
"Id": "200341",
"Score": "0",
"Tags": [
"java",
"parsing",
"mongodb"
],
"Title": "Decompose big service class into small classes"
} | 200341 |
<h1>Problem</h1>
<p>Read a file and capture two tokens for every multi-line entry.</p>
<p>First token is hexcode with which the entry starts.</p>
<p>Second token is the remaining line(multi-line) of the entry. Trailing backslash indicates the continuation of line.</p>
<p>Typical entries of a file is as shown below:</p>
<pre><code>0x0512ff01 R 5330 R XY.Zion, \
"parseexp( {f 7},{S \"OWAUTO\"})", "0x0222ff02 -:-", \
"parseexp( {g 7},{S \"TWFAB\"})", "0x0222ff02 -:-", \
"setfault", "0x0222ff03 -:-"
# whatever
0x0436ff02 I 5330 R XY.Yion, " \
! ( strcat( {H 19.19.121.180}, {attr 0x11137f }) \
"default", "0x0222ff03 -:-"
0x0236ff03 G 50
0x0588ff03 H 49
0x0777ff03 R 34
</code></pre>
<p>There are such ~100 files to read</p>
<hr>
<h1>Solution</h1>
<p>Input to this function is a generator that provides <code>path</code>, one at a time</p>
<pre><code>def get_tokens(file_paths):
for path in file_paths:
ruleCapture = False
with open(path) as f:
for line in f:
line=line.strip() # remove \n and other spaces
if line.startswith('#'): # comments
continue
elif (not line.endswith('\\')) and (ruleCapture == False):
event_rule_match = re.search(r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)',line)
if event_rule_match:
yield event_rule_match.group(1), event_rule_match.group(2)
elif line.endswith('\\') and ruleCapture == False:
buffer = line[0:-2]
ruleCapture = True
elif line.endswith('\\') and ruleCapture == True:
buffer = ' '.join([buffer, line[0:-2]])
elif (not line.endswith('\\')) and ruleCapture == True:
buffer = ' '.join([buffer, line])
ruleCapture = False
event_rule_match = re.search(r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)',buffer)
yield event_rule_match.group(1), event_rule_match.group(2)
buffer=''
</code></pre>
<hr>
<p>1) Can this code avoid regex?</p>
<p>2) Can <code>elif</code> structure still be optimized?</p>
<p>3) Can this code avoid reading the file line by line? Instead use <code>f.read()</code> and compile regex once....</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T18:35:52.023",
"Id": "385743",
"Score": "1",
"body": "This looks a lot like homework? If so, please tag it as such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T18:53:02.220",
"Id": "385746",
... | [
{
"body": "<h3>1) Control flow clarity</h3>\n\n<pre><code>if a and b: ...\nelif a and not b: ...\nelif not a and b: ...\nelif not a and not b: ...\n</code></pre>\n\n<p>can be improved to</p>\n\n<pre><code>if a:\n if b: ...\n else: ...\nelse:\n if b: ...\n else: ...\n</code></pre>\n\n<h3>2) Remove un... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T12:45:55.553",
"Id": "200343",
"Score": "3",
"Tags": [
"python",
"regex"
],
"Title": "Reading a file line by line - Two tokens per entry"
} | 200343 |
<p><code>findSecondLargestNumberInTheArray()</code> method returns the second highest number from an array.</p>
<p>Could you please review this code to enhance performance.</p>
<pre><code>public static int findSecondLargestNumberInTheArray(int array[]) {
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;
// Loop over the array
for (int i = 0; i < array.length; i++) {
// If current element is greater than highest
if (array[i] > highest) {
// assign second highest element to highest element
secondHighest = highest;
// highest element to current element
highest = array[i];
} else if (array[i] > secondHighest)
// Just replace the second highest
secondHighest = array[i];
}
// After exiting the loop, secondHighest now represents the second
// largest value in the array
return secondHighest;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T13:46:32.030",
"Id": "385668",
"Score": "0",
"body": "What test cases did you try? Do you have a more complete problem statement? As Martin indicates, this code doesn't work when the highest value occurs multiple times."
},
{
... | [
{
"body": "<p>Several <em>comments</em> are unnecessary:</p>\n\n<pre><code> // Loop over the array\n for (int i = 0; i < array.length; i++) {\n\n // assign second highest element to highest element\n secondHighest = highest;\n</code></pre>\n\n<p>I recommend do use braces <code>{ ... }</code> for ... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T12:57:08.887",
"Id": "200346",
"Score": "4",
"Tags": [
"java",
"array"
],
"Title": "Finding the second largest value In an Array"
} | 200346 |
<p>I am coming from a Ruby background and I am learning Python. This is a method I've created to generate a URL safe unique key:</p>
<pre><code>import random;
def generate_unique_key():
array = []
for letter in range(97,123):
array.append(chr(letter))
for letter in range(65,91):
array.append(chr(letter))
for number in range(0,10):
array.append(number)
for char in ["-", ".", "_", "~"]:
array.append(char)
random_values = random.sample(array, 15)
random_values = map(lambda x: str(x), random_values)
return "".join(random_values)
print(generate_unique_key())
</code></pre>
<p>Coming from a Ruby background I was certainly puzzled first at not being able call <code>join</code> directly on my list, but having to call it from a string instance.</p>
<p>Also in Ruby I would have written something similar to <code>random.sample(array, 15).join("")</code> directly without having to convert them all to string, but this I believe this is how <code>join()</code> works.</p>
<p>While this works, how can this function be more Pythonic?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T16:12:44.597",
"Id": "385711",
"Score": "0",
"body": "@Peilonrayz Apologies, this is indeed python 3. I was testing on a python 2.7 interpreter which is why the print looks like that, but I will be using it in a python 3.7 environme... | [
{
"body": "<ol>\n<li>You can pass <code>str</code> to <code>map</code> rather than a <code>lambda</code>.</li>\n<li>You can remove the need for <code>map</code> if you change your third loop to append <code>str(number)</code>.</li>\n<li>You can use <a href=\"https://docs.python.org/3/library/string.html\" rel=\... | {
"AcceptedAnswerId": "200356",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T15:50:18.590",
"Id": "200355",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"strings",
"random"
],
"Title": "Generating a unique key"
} | 200355 |
<blockquote>
<p><strong>Problem Statement</strong></p>
<p>I want to be able to look at log files and figure out where the
bottlenecks are in the code in an easy/visual way rather than trying
to do the math every time I make some improvements. I want to be able
to use a single instance of this throughout the <strong>target</strong> class rather than
creating a new instance in every function within it. Hope that helps to clear
some of the confusion.</p>
</blockquote>
<p><strong>Class Description</strong></p>
<blockquote>
<p>The ExecTimeLogger class has a simple interface of Start(), Stop() and
Summary() and it stores that information in a map keyed off of a token
and the function name</p>
</blockquote>
<pre><code>#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <chrono>
#include <map>
#include <atomic>
#include <Logger.h>
/*
Utility class which provides logging the function execution times and summarizing the results of all executed functions within a class
*/
class ExecTimeLogger
{
private:
std::map <std::string, ExecTimeData> _execMap;
std::atomic<int> _sectionNumber;
int const INSTANCE_TOKEN = 0;
std::string const INSTANCE_NAME = "Entire Instance";
Logger* _logger;
std::string GetKeyName(int token, std::string sectionName)
{
auto keyName = std::to_string(token) + "_" + sectionName;
return keyName;
}
void LogMessage(std::string message)
{
if (_logger != nullptr)
{
_logger->printMessage("\n");
_logger->printMessage(message.c_str());
}
else
std::cout << message.c_str();
}
public:
/*
Instantiates the ExecTimeLogger class with an optional pointer to logger
If a logger is not provided, it logs everything to the console
*/
ExecTimeLogger(Logger* logger = nullptr)
{
_sectionNumber = INSTANCE_TOKEN;
this->Start(INSTANCE_NAME);
this->_logger = logger;
}
~ExecTimeLogger()
{
delete _logger;
this->_logger = nullptr;
}
/*
Stops the timer for the given section name
*/
int Start(std::string sectionName)
{
ExecTimeData newSection;
newSection.SectionName = sectionName;
newSection.TokenID = _sectionNumber++;
newSection.SectionStartTime = std::chrono::high_resolution_clock::now();
auto keyName = GetKeyName(newSection.TokenID, sectionName);
if (_execMap.count(sectionName) == 0)
{
_execMap.insert(std::make_pair(keyName, newSection));
}
else
{
_execMap[keyName] = newSection;
}
return newSection.TokenID;
}
/*
Stops the timer for the given section name and token combination
*/
void Stop(std::string sectionName, int tokenID)
{
auto keyName = GetKeyName(tokenID, sectionName);
if (_execMap.count(keyName) == 0)
{
LogMessage(sectionName + " or " + std::to_string(tokenID) + " does not exist.\n");
return;
}
_execMap[keyName].SectionStopTime = std::chrono::high_resolution_clock::now();
std::stringstream summaryBuf;
summaryBuf << _execMap[keyName].TokenID << ") " << _execMap[keyName].SectionName.c_str() << " = " << _execMap[keyName].Elapsed() << "(ms)" << std::endl;
LogMessage(summaryBuf.str());
}
/*
Prints the execution time summary either to the logger if available or to the console
*/
void LogSummary()
{
this->Stop(INSTANCE_NAME, 0);
std::stringstream summaryBuf;
summaryBuf << "---------------------------------------------------------------------------------------\n";
summaryBuf << "------------------------------------Execution Times------------------------------------\n";
summaryBuf << "---------------------------------------------------------------------------------------\n";
summaryBuf
<< std::setw(10)
<< "Token"
<< std::setw(20)
<< "Section Name"
<< std::setw(21)
<< "Exec. Time (ms)"
<< std::setw(14)
<< "% of total"
<< std::setw(22)
<< "Impact"
<< std::endl;
summaryBuf << "---------------------------------------------------------------------------------------\n";
auto instanceElapsed = _execMap[GetKeyName(INSTANCE_TOKEN, INSTANCE_NAME)].Elapsed();
long long totalExec = 0;
for (auto const& record : _execMap)
{
auto currentRecord = record.second;
// Don't print the full binary time
if (currentRecord.TokenID == INSTANCE_TOKEN)
continue;
auto currentRecordElapsed = currentRecord.Elapsed();
if (currentRecordElapsed > 0)
totalExec += currentRecordElapsed;
auto percentage = ((float)currentRecordElapsed / instanceElapsed) * 100.00;
int impact = percentage / 5;
std::string impactStr = "";
if (currentRecordElapsed < 0)
impactStr = "NA";
else
{
for (size_t i = 0; i <= impact; i++)
{
impactStr += "*";
}
}
summaryBuf
<< std::fixed
<< std::setprecision(2)
<< std::setw(9)
<< std::to_string(currentRecord.TokenID)
<< ")"
<< std::setw(20)
<< currentRecord.SectionName
<< std::setw(21)
<< currentRecordElapsed
<< std::setw(14)
<< ((float)currentRecordElapsed / instanceElapsed) * 100.00
<< std::setw(22)
<< impactStr
<< std::endl;
}
summaryBuf << "---------------------------------------------------------------------------------------\n";
summaryBuf << "Total Execution Time of the Instance\t\t= " << std::to_string(instanceElapsed) << "(ms)\n";
summaryBuf << "Total Execution Time of all the functions\t= " << std::to_string(totalExec) << "(ms)\n";
summaryBuf << std::fixed << std::setprecision(2)
<< "% execution time of all the functions\t\t= " << (((float)totalExec / instanceElapsed) * 100.00) << "%\n";
summaryBuf << "---------------------------------------------------------------------------------------\n";
LogMessage(summaryBuf.str());
}
};
</code></pre>
<p>This is the class which holds the data:</p>
<pre><code>/*
Class which holds the execution time data
*/
class ExecTimeData
{
public:
int TokenID;
std::string SectionName;
std::chrono::high_resolution_clock::time_point SectionStartTime;
std::chrono::high_resolution_clock::time_point SectionStopTime;
/*
Returns the total number of milliseconds that've elapsed to execute the section
*/
long long Elapsed()
{
// The clock was never stopped
if (SectionStopTime.time_since_epoch().count() == 0)
return -1;
long long elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(SectionStopTime - SectionStartTime).count();
return elapsed;
}
};
</code></pre>
<p>And, here is an example use case:</p>
<pre><code>class ClassToBeBenchmarked
{
private:
ExecTimeLogger* exec;
void PrivateFunctionOne()
{
auto token = exec->Start(__FUNCTION__);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
exec->Stop(__FUNCTION__, token);
return;
}
void PrivateFunctionTwo()
{
auto token = exec->Start(__FUNCTION__);
std::this_thread::sleep_for(std::chrono::milliseconds(700));
exec->Stop(__FUNCTION__, token);
return;
}
public:
ClassToBeBenchmarked()
{
exec = new ExecTimeLogger();
}
~ClassToBeBenchmarked()
{
exec->LogSummary();
}
void PublicEntryFunction()
{
auto token = exec->Start(__FUNCTION__);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
PrivateFunctionOne();
PrivateFunctionTwo();
exec->Stop(__FUNCTION__, token);
return;
}
};
int main()
{
ClassToBeBenchmarked bench;
bench.PublicEntryFunction();
return 0;
</code></pre>
<p>}</p>
<p>One thing that I'm not a fan of here is to have to put</p>
<pre><code>auto token = exec.Start(__FUNCTION__);
</code></pre>
<p>and</p>
<pre><code>exec.Stop(__FUNCTION__, token);
</code></pre>
<p>in every function.</p>
<p>Please suggest if there is a clever way to handle that, otherwise general code improvement comments are appreciated. Thanks!</p>
<p>Sample Output:</p>
<pre><code>2) ClassToBeBenchmarked::PrivateFunctionOne = 500(ms)
3) ClassToBeBenchmarked::PrivateFunctionTwo = 701(ms)
1) ClassToBeBenchmarked::PublicEntryFunction = 3224(ms)
0) Entire Instance = 3233(ms)
322437244425----------------------------------------------------------------------------------------------------------------
------------------------------------------------Execution Times-------------------------------------------------
----------------------------------------------------------------------------------------------------------------
Token Section Name Exec. Time (ms) % of total Impact
----------------------------------------------------------------------------------------------------------------
1) ClassToBeBenchmarked::PublicEntryFunction 3224 99.72 ********************
2) ClassToBeBenchmarked::PrivateFunctionOne 500 15.47 ****
3) ClassToBeBenchmarked::PrivateFunctionTwo 701 21.68 *****
----------------------------------------------------------------------------------------------------------------
Total Execution Time of the Instance = 3233(ms)
Total Execution Time of all the functions = 4425(ms)
% execution time of all the functions = 136.87%
----------------------------------------------------------------------------------------------------------------
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T18:08:05.917",
"Id": "385736",
"Score": "0",
"body": "To those who want to rollback: please don't. I believe that better example usage doesn't invalidate answers. I'll remove mention from mine."
},
{
"ContentLicense": "CC BY... | [
{
"body": "<p>If you return an object from <code>Start</code>, you could arrange for its destructor to stop the timer. That RAII style instantly reduces the intrusiveness of the instrumentation by half (and saves you having to think about all the return points of the functions - which might be as exceptions, r... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T16:04:46.373",
"Id": "200357",
"Score": "7",
"Tags": [
"c++",
"c++11",
"benchmarking"
],
"Title": "Code to track execution time for each function in a class"
} | 200357 |
<p>When writing custom network serialization in Rust, I've come across a use case for storing and retrieving values in bitfields smaller than the <code>u8</code> available in Rust. </p>
<p>I wrote a library that fits my use case. It exposes an API for writing enums/data at particular bit offsets and widths and retrieving their values by "position" in the underlying storage. </p>
<p>One obvious limitation is the hard-coded <code>StorageType = u32</code>, limiting users to at most 32 bits. Another is the current reliance on <code>TryFrom</code>, which isn't stable yet.</p>
<p>Any comments and suggestions for improving the API and implementation are welcome!</p>
<p><strong>Rust Playground:</strong> <a href="https://play.rust-lang.org/?gist=f9b7c3243abe4a1c27db5c7d87f557e9&version=nightly&mode=debug&edition=2015" rel="noreferrer">https://play.rust-lang.org/?gist=f9b7c3243abe4a1c27db5c7d87f557e9&version=nightly&mode=debug&edition=2015</a></p>
<p><strong>Raw Source:</strong></p>
<pre><code>//! Helpers for grouping together data in sub-byte bitfields.
#![feature(try_from)]
use std::collections::HashMap;
use std::convert::TryFrom;
use std::mem;
type StorageType = u32;
#[derive(Debug, PartialEq)]
pub enum Error {
DataTooLarge,
OutOfBounds,
WouldOverlap,
TryFromError,
}
struct BitField {
pos: StorageType,
width: StorageType,
}
/// A set of bit fields
pub struct BitFieldSet {
/// Total number of bits spanned by this set
num_bits: usize,
storage: StorageType, // TODO support wider types
entries: HashMap<StorageType, BitField>,
}
impl BitFieldSet {
pub fn new(num_bits: usize) -> Result<Self, Error> {
let supported_bits = mem::size_of::<StorageType>() * 8;
if num_bits > supported_bits {
return Err(Error::OutOfBounds);
}
Ok(BitFieldSet {
num_bits: supported_bits,
storage: 0,
entries: HashMap::new(),
})
}
/// Creates an associative [BitField] entry in this [BitFieldSet]
pub fn add(&mut self, pos: StorageType, width: StorageType) -> Result<(), Error> {
if pos > self.num_bits as StorageType {
return Err(Error::OutOfBounds);
}
self.entries.insert(pos, BitField { pos, width });
Ok(())
}
/// Inserts the the data at the provided position and associates its position and width.
pub fn insert<D: Into<StorageType>>(
&mut self,
pos: StorageType,
width: StorageType,
data: D,
) -> Result<StorageType, Error> {
if pos > self.num_bits as StorageType {
return Err(Error::OutOfBounds);
}
let data: StorageType = data.into();
let data_too_large = mem::size_of::<D>() > self.num_bits;
let data_overflow = (width + pos) > self.num_bits as StorageType;
if data_too_large || data_overflow {
return Err(Error::DataTooLarge);
}
self.storage |= data << pos;
self.entries.insert(pos, BitField { pos, width });
Ok(data)
}
pub fn get(&self, pos: StorageType) -> Option<StorageType> {
let entry = self.entries.get(&pos)?;
let mask = (2 as StorageType).pow(entry.width) - 1;
let mask = mask << entry.pos;
let value = self.storage & mask;
let value = value >> entry.pos;
Some(value)
}
pub fn get_as<T: TryFrom<StorageType>>(&self, pos: StorageType) -> Result<T, Error> {
let value = self.get(pos).ok_or_else(|| Error::TryFromError)?;
T::try_from(value).map_err(|_| Error::TryFromError)
}
}
impl From<StorageType> for BitFieldSet {
fn from(raw: StorageType) -> Self {
let supported_bits = mem::size_of::<StorageType>() * 8;
BitFieldSet {
num_bits: supported_bits,
storage: raw,
entries: HashMap::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::{BitFieldSet, Error};
use std::convert::TryFrom;
use StorageType;
const PATH_TYPE_POS: StorageType = 7;
const PROTOCOL_POS: StorageType = 2;
const ADDRESS_TYPE_POS: StorageType = 0;
#[derive(Debug, PartialEq)]
#[repr(u8)]
enum PathTypes {
Named,
Unique,
}
#[derive(Debug, PartialEq)]
#[repr(u8)]
enum AddressTypes {
IPv4,
IPv6,
Domain,
}
#[derive(Debug, PartialEq)]
#[repr(u8)]
enum ProtocolTypes {
Local,
TCP,
UDP,
UDT,
}
impl TryFrom<StorageType> for PathTypes {
type Error = Error;
fn try_from(value: StorageType) -> Result<Self, Self::Error> {
match value {
x if x == PathTypes::Named as StorageType => Ok(PathTypes::Named),
x if x == PathTypes::Unique as StorageType => Ok(PathTypes::Unique),
_other => Err(Error::TryFromError),
}
}
}
impl TryFrom<StorageType> for AddressTypes {
type Error = Error;
fn try_from(value: StorageType) -> Result<Self, Self::Error> {
match value {
x if x == AddressTypes::IPv4 as StorageType => Ok(AddressTypes::IPv4),
x if x == AddressTypes::IPv6 as StorageType => Ok(AddressTypes::IPv6),
x if x == AddressTypes::Domain as StorageType => Ok(AddressTypes::Domain),
_other => Err(Error::TryFromError),
}
}
}
impl TryFrom<StorageType> for ProtocolTypes {
type Error = Error;
fn try_from(value: StorageType) -> Result<Self, Self::Error> {
match value {
x if x == ProtocolTypes::Local as StorageType => Ok(ProtocolTypes::Local),
x if x == ProtocolTypes::TCP as StorageType => Ok(ProtocolTypes::TCP),
x if x == ProtocolTypes::UDP as StorageType => Ok(ProtocolTypes::UDP),
x if x == ProtocolTypes::UDT as StorageType => Ok(ProtocolTypes::UDT),
_other => Err(Error::TryFromError),
}
}
}
#[test]
fn insertion() {
// TODO force compiler-aware mapping of position to type stored
let mut bfs = BitFieldSet::new(8).expect("8 bits should fit into default storage type u32");
bfs.insert(PATH_TYPE_POS, 1, PathTypes::Unique as u8)
.expect("Data width of 1 should fit inside expected 32 bits");
bfs.insert(PROTOCOL_POS, 5, ProtocolTypes::UDP as u8)
.expect("Data width of 5 should fit inside expected 32 bits");
bfs.insert(ADDRESS_TYPE_POS, 2, AddressTypes::IPv6 as u8)
.expect("Data width of 2 should fit inside expected 32 bits");
assert_eq!(
bfs.get(PATH_TYPE_POS).unwrap(),
PathTypes::Unique as StorageType
);
assert_eq!(
bfs.get_as::<PathTypes>(PATH_TYPE_POS).unwrap(),
PathTypes::Unique
);
assert_eq!(
bfs.get_as::<AddressTypes>(ADDRESS_TYPE_POS).unwrap(),
AddressTypes::IPv6
);
assert_eq!(
bfs.get_as::<ProtocolTypes>(PROTOCOL_POS).unwrap(),
ProtocolTypes::UDP
);
}
#[test]
fn from_raw() {
let raw: StorageType = 0b10001001;
let mut bfs = BitFieldSet::from(raw);
bfs.add(PATH_TYPE_POS, 1)
.expect("Data of width 1 should fit inside expected 32 bits");
bfs.add(PROTOCOL_POS, 5)
.expect("Data of width 1 should fit inside expected 32 bits");
bfs.add(ADDRESS_TYPE_POS, 2)
.expect("Data of width 1 should fit inside expected 32 bits");
assert_eq!(
bfs.get(PATH_TYPE_POS).unwrap(),
PathTypes::Unique as StorageType
);
assert_eq!(
bfs.get_as::<PathTypes>(PATH_TYPE_POS).unwrap(),
PathTypes::Unique
);
assert_eq!(
bfs.get_as::<AddressTypes>(ADDRESS_TYPE_POS).unwrap(),
AddressTypes::IPv6
);
assert_eq!(
bfs.get_as::<ProtocolTypes>(PROTOCOL_POS).unwrap(),
ProtocolTypes::UDP
);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T16:37:24.730",
"Id": "385721",
"Score": "1",
"body": "Welcome to Code Review! This is a great first question; it's good that you've included the unit tests that show how it's used. I hope to see more of your contributions in future ... | [
{
"body": "<p>All in all well-written and mostly self-explanatory code. However, there are some remarks:</p>\n\n<h1>Negative tests</h1>\n\n<p>You already provide <code>WouldOverlap</code> as a possible error, but you don't use it in <code>insert</code> or <code>add</code>. Your tests cannot check this at the mo... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T16:12:44.840",
"Id": "200358",
"Score": "7",
"Tags": [
"rust",
"library",
"serialization"
],
"Title": "Library for managing sub-byte named bitfields"
} | 200358 |
<h2>Problem Statement:</h2>
<blockquote>
<p>A k-distinct-partition of a number \$n\$ is a set of \$k\$ distinct positive integers that add up to \$n\$. For example, the 3-distinct partitions of 10 are </p>
<p>\$1+2+7\$<br>
\$1+3+6\$<br>
\$1+4+5\$<br>
\$2+3+5\$ </p>
<p>The objective is to count all k-distinct partitions of a number that have at least two perfect squares in the
elements of the partition.<br>
Note that 1 is considered a perfect square.</p>
</blockquote>
<h3>Constraints</h3>
<blockquote>
<p>\$k<N<200\$, so that at least one k-distinct partition exists.</p>
</blockquote>
<h3>Input Format</h3>
<blockquote>
<p>The input consists of one line containing of \$N\$ and \$k\$ separated by a comma.</p>
</blockquote>
<h3>Output</h3>
<blockquote>
<p>One number denoting the number of k-distinct partitions of N that have at least two perfect squares in the
elements of the partition.</p>
</blockquote>
<h3>Explanation</h3>
<blockquote>
<p>Example 1</p>
<p>Input</p>
<p>10, 3</p>
<p>Output</p>
<p>1</p>
<p>Explanation: The input asks for 3-distinct-partitions of 10. There are 4 of them (1+2+7, 1+3+6, 1+4+5 and
2+3+5). Of these, only 1 has at least two perfect squares in the partition (1+4+5).</p>
<hr>
<p>Example 2</p>
<p>Input</p>
<p>12, 3</p>
<p>Output</p>
<p>2</p>
<p>Explanation
The input asks for 3-distinct partitions of 12. There are 7 of them (9+2+1, 8+3+1,7+4+1,7+3+2,6+5+1,
6+4+2, 5+4+3). Of these, two, (9+4+1, 7+4+1) have two perfect squares. Hence, the output is 2.</p>
</blockquote>
<p>My code hangs when the numbers are big, e.g. when N = 150 and k = 30</p>
<hr>
<h1>The code</h1>
<pre><code>#include <stdio.h>
#include <math.h>
int a[200];
int count=0;
int n,k;
int i,sum,perf;
void func(int,int);
int perfect(int number);
int main()
{
scanf("%d,%d",&n,&k);
func(0,1);
printf("%d",count);
return 0;
}
void func(int index,int val){
sum=0,perf=0;
if(index==k){
for(i=0;i<k;i++){
sum=sum+a[i];
}
if(sum==n){
for(i=0;i<k;i++){
if(perfect(a[i])){
perf++;
}
}
if(perf>=2){
count++;
}
}
}
else{
a[index]=val;
for(i=a[index];a[index]<n;a[index]++){
func(index+1,a[index]+1);
}
}
}
int perfect(int number)
{
int iVar;
float fVar;
fVar=sqrt((double)number);
iVar=fVar;
if(iVar==fVar) return 1;
else return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T11:10:19.223",
"Id": "385834",
"Score": "2",
"body": "It should be noted that if \\$N=150\\$ and \\$k=30\\$, there exists no solution. Since all integers need to be distinct, the minimum partition with 30 elements is \\$1+2+3+4+...+... | [
{
"body": "<p>This is an interesting challenge! Here are some ways you could improve your code.</p>\n\n<h1>Globals</h1>\n\n<p>None of your variables should be global. It makes it significantly harder to figure out where a variable is changing. Given that you reset <code>sum</code> and <code>perf</code> to 0 eve... | {
"AcceptedAnswerId": "200392",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T18:32:30.710",
"Id": "200365",
"Score": "3",
"Tags": [
"algorithm",
"c",
"programming-challenge",
"recursion",
"time-limit-exceeded"
],
"Title": "Find k-distinct partitions which contain at least two perfect squares"
} | 200365 |
<p>This is my first C# project, so feel free to be brutal. :) </p>
<p>I have an automated external process on another machine generate and email a budget report to me every Sunday. This program is a Microsoft Outlook add-in that automatically fetches those emails and saves the attached report to a particular location on my hard drive organized by year. Here's the algorithm:</p>
<ol>
<li>if there is no unread email in the mail folder, quit</li>
<li>otherwise, save the attachment to a subfolder under the year</li>
<li>renaming it to append the date </li>
</ol>
<p>Because it's tied to the new email event, it only runs once each time new a new email is received.</p>
<p>This is the code which includes some autogenerated code.</p>
<h2>BudgetTool.cs</h2>
<pre><code>using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace BudgetToolAddIn
{
public partial class BudgetTool
{
private void BudgetTool_Startup(object sender, System.EventArgs e)
{
this.Application.NewMail += new Microsoft.Office.Interop.Outlook
.ApplicationEvents_11_NewMailEventHandler(ThisApplication_NewMail);
}
private void ThisApplication_NewMail()
{
string folderName = "Budget Reports";
// the destiationFolder must include the trailing \
string destinationFolder = @"C:\users\Edward\planning\budget\";
Outlook.MAPIFolder inBox = Application.ActiveExplorer()
.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;
try
{
inBox = inBox.Folders[folderName];
}
catch
{
System.Windows.Forms.MessageBox.Show(@"Can't find folder '" + folderName + "'");
return;
}
Outlook.Items inBoxItems = inBox.Items;
Outlook.MailItem newEmail = null;
inBoxItems = inBoxItems.Restrict("[Unread] = true");
try
{
foreach (object collectionItem in inBoxItems)
{
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
const string extension = ".csv";
string originalFileName = newEmail.Attachments[i].FileName;
if (originalFileName.EndsWith(extension))
{
int extloc = originalFileName.LastIndexOf(extension);
DateTime date = newEmail.SentOn;
string year = date.ToString("yyyy");
string fileName = originalFileName.Remove(extloc, extension.Length) + "_" + date.ToString("yyyyMMdd") + extension;
newEmail.Attachments[i].SaveAsFile(destinationFolder + year + @"\" + fileName);
}
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
System.Windows.Forms.MessageBox.Show(@"Create Folder <{destionationFolder}>");
}
}
}
private void BudgetTool_Shutdown(object sender, System.EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(BudgetTool_Startup);
this.Shutdown += new System.EventHandler(BudgetTool_Shutdown);
}
#endregion
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T20:27:32.140",
"Id": "385762",
"Score": "1",
"body": "__WHY U NO USING VBA__ ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T20:54:22.860",
"Id": "385769",
"Score": "2",
"body": "@Phra... | [
{
"body": "<p>As it seems to be a \"for-your-own-eyes-only\"-function I will not comment on the hard coded paths and other strings :-).</p>\n\n<p>This syntax</p>\n\n<blockquote>\n<pre><code> this.Application.NewMail += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailEventHandler(ThisAppl... | {
"AcceptedAnswerId": "200404",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T19:22:09.263",
"Id": "200368",
"Score": "6",
"Tags": [
"c#",
"beginner",
"outlook"
],
"Title": "Microsoft Outlook add-in to automatically save generated report"
} | 200368 |
<p>This is the code of my function to endless scrolling. It's a good practice to bind new disposable in onscroll listener? What do you think about my code?</p>
<pre><code> private fun searchData(srsearch: String) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(et_search_querry.windowToken, 0)
rv_results.layoutManager = LinearLayoutManager(this)
val manager = rv_results.layoutManager as LinearLayoutManager
pb_fetch.visibility = View.VISIBLE
disposable =
wikiApiServe.getRecordsByQuerry("query", "json", "search", srsearch)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result ->
var continueS = result._continue._continue
var offset = result._continue.sroffset
var searchS = srsearch
pb_fetch.visibility = View.GONE
rv_results.adapter = ResultsAdapter(result.query.search, this)
tv_search_results.text =
String.format(resources.getQuantityText(R.plurals.results_found,
result.query.searchinfo.totalhits).toString(), result.query.searchinfo.totalhits)
rv_results.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (!isLoading) {
if (manager.findLastCompletelyVisibleItemPosition()
>= rv_results.adapter.itemCount - 1) {
isLoading = true
pb_fetch.visibility = View.VISIBLE
disposable?.dispose()
disposable = wikiApiServe.getMoreRecords("query", "json", "search", continueS, offset, searchS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result ->
isLoading = false
continueS = result._continue._continue
offset = result._continue.sroffset
pb_fetch.visibility = View.GONE
(rv_results.adapter as ResultsAdapter).addMore(result.query.search)
}, { _ ->
isLoading = false
pb_fetch.visibility = View.GONE
Toast.makeText(this@MainActivity,
"Something went wrong try again",
Toast.LENGTH_SHORT).show()
})
}
}
}
})
},
{ _ ->
pb_fetch.visibility = View.GONE
Toast.makeText(this,
"Something went wrong try again",
Toast.LENGTH_SHORT).show()
}
)
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T20:21:20.787",
"Id": "200372",
"Score": "2",
"Tags": [
"android",
"kotlin",
"reactive-programming"
],
"Title": "Endless scroll in kotlin (android)"
} | 200372 |
<p>I have a <a href="https://en.wikipedia.org/wiki/Look-and-say_sequence" rel="noreferrer">pattern where every number is counted by the number of repetitions</a>. A new resulting number is formed by adding that repetition to the front of that value. The resulting pattern would look like this.</p>
<ol>
<li>1</li>
<li>11</li>
<li>21</li>
<li>1211</li>
<li>111221</li>
</ol>
<p>so:</p>
<p><kbd>index</kbd><kbd>number</kbd><kbd>comment</kbd><br/>
<kbd>0 </kbd><kbd>1 </kbd><kbd>
one + 1 ->11 </kbd><br/>
<kbd>1 </kbd><kbd>11 </kbd><kbd> two + 1 -> 21 </kbd><br/>
<kbd>2 </kbd><kbd>21 </kbd><kbd>one + 2 + one + 1 -> 1211 </kbd><br/></p>
<p>etc...</p>
<p>I was given a number 4, and I needed to produce the resulting number 1211.</p>
<p>My approach was to use a recursive function that used every subsequent iteration starting from 0 to evaluate every resulting value until I reached my target iteration. </p>
<p>Runtime Complexity: I decremented the number recursively O(N) as I carried the resulting evaluation result. </p>
<p>At every recursive step, I produced every result by walking the resulting values, counting the repetitions as I went along. I stored every key-value pairs along an Index represented by a synecdochic key in a line of contiguous repetition. I tallied the repetitions until I had a key-value pair at the intersection of every index.</p>
<p>I then assembled the value by swapping the key values pairs at every index into a new object array which I used to repeat the process. O(C) </p>
<p>I then used reduce to format the results and repeat the process O(F) </p>
<p>O(N *C +F) = O(N^2)</p>
<p>space complexity is O(N^2) since the amount of space needed to process doubles on every resulting iteration. </p>
<p>Are my Time and Space analysis correct, did I miss a much simpler approach where I might have been able to take advantage of Fibonacci, XOR or some other simpler mathematical approach? and could this have been done better programmatically by using some other type of data structure, or could it have been written in some other concise way?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function countStay(num) {
if (num === 1) {
return 1
}
return drill(num, [1])
}
function drill(exitCount, result) {
const map = {
0: {}
},
arr = [];
let count = 0,
index = 0;
result = result.reduce((acc, a, i, aa) => {
if (aa[i - 1] && aa[i] && a !== aa[i - 1]) {
index += 1
count = 0
map[index] = {
[a]: count
}
}
if (((map || {})[index] || {})[a] && count !== 0) {
map[index][a] = count += 1
arr[index] = [count, a]
}
if (!((map || {})[index] || {})[a] && count === 0) {
count += 1
map[index] = {
[a]: count
}
arr[index] = [count, a]
}
return acc = {
arr
}
}, {})
result = join(result)
exitCount--
if (exitCount <= 1) {
return result.join('')
}
return drill(exitCount, result)
}
function join(result) {
return result = result.arr.reduce((acum, a) => acum.concat(a), [])
}
console.log(countStay(4))</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T23:50:54.360",
"Id": "385790",
"Score": "1",
"body": "I haven't looked enough at your code to post an answer but take a gander at [PCG's answers to generate this sequence.](https://codegolf.stackexchange.com/questions/70837/say-what... | [
{
"body": "<p>It seems like you tried too hard to avoid all loops by limiting yourself to <code>.reduce()</code> and recursion. While JavaScript supports functional programming to some extent, sticking to pure FP everywhere will likely lead to clunky code. A better strategy would be to define some functions t... | {
"AcceptedAnswerId": "200444",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T21:14:12.930",
"Id": "200376",
"Score": "5",
"Tags": [
"javascript",
"performance",
"algorithm",
"recursion",
"hash-map"
],
"Title": "Recursively generating the look-and-say sequence"
} | 200376 |
<p>How should I incorporate a JButton array, and how do I get rid of the multitude of action listeners? I would also like to modify it so that you can do more than one operation on numbers with multiple digits.</p>
<pre><code>/*
* A one operation calculator.
* Only handles single digits for basic arithmetic.
* Trig operations accept values in degrees.
*
* I'll make a real calculator later.
*/
public class BasicCalculator extends JFrame {
private JPanel panel;
private JTextField input;
private JButton butt0, butt1, butt2, butt3,
butt4, butt5, butt6, butt7,
butt8, butt9, buttSine, buttCosine,
buttEquals, buttClear, buttAdd,
buttSubtract, buttMultiply, buttDivide,
buttTangent;
private final int WINDOW_WIDTH = 360;
private final int WINDOW_HEIGHT = 300;
/*
* Constructor calls the superclass's constructor and creates the window.
*/
public BasicCalculator() {
super("Calculate a Simple Expression");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
/*
* Method to put the input box and all the buttons onto the window.
*
* I know, I know, I should've used an array for the buttons.
*/
private void buildPanel() {
input = new JTextField(16);
buttEquals = new JButton("=");
buttEquals.addActionListener(new Listener1());
buttClear = new JButton("AC");
buttClear.addActionListener(new Listener2());
buttAdd = new JButton("+");
buttAdd.addActionListener(new Listener3());
buttSubtract = new JButton("-");
buttSubtract.addActionListener(new Listener4());
buttMultiply = new JButton("x");
buttMultiply.addActionListener(new Listener5());
buttDivide = new JButton("÷");
buttDivide.addActionListener(new Listener6());
butt0 = new JButton("0");
butt0.addActionListener(new Listener7());
butt1 = new JButton("1");
butt1.addActionListener(new Listener8());
butt2 = new JButton("2");
butt2.addActionListener(new Listener9());
butt3 = new JButton("3");
butt3.addActionListener(new Listener10());
butt4 = new JButton("4");
butt4.addActionListener(new Listener11());
butt5 = new JButton("5");
butt5.addActionListener(new Listener12());
butt6 = new JButton("6");
butt6.addActionListener(new Listener13());
butt7 = new JButton("7");
butt7.addActionListener(new Listener14());
butt8 = new JButton("8");
butt8.addActionListener(new Listener15());
butt9 = new JButton("9");
butt9.addActionListener(new Listener16());
buttSine = new JButton("sin");
buttSine.addActionListener(new Listener17());
buttCosine = new JButton("cos");
buttCosine.addActionListener(new Listener18());
buttTangent = new JButton("tan");
buttTangent.addActionListener(new Listener19());
panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 30));
panel.add(input);
panel.add(buttEquals);
panel.add(buttClear);
panel.add(buttAdd);
panel.add(buttSubtract);
panel.add(buttMultiply);
panel.add(buttDivide);
panel.add(butt0);
panel.add(butt1);
panel.add(butt2);
panel.add(butt3);
panel.add(butt4);
panel.add(butt5);
panel.add(butt6);
panel.add(butt7);
panel.add(butt8);
panel.add(butt9);
panel.add(buttSine);
panel.add(buttCosine);
panel.add(buttTangent);
}
/*
* Action listener for the "equals" button.
* All the calculations are done here.
*/
private class Listener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = input.getText();
double num1, num2, radians, result;
if (str.charAt(0) == 's' || str.charAt(0) == 'c' || str.charAt(0) == 't')
{
radians = Math.toRadians(Double.parseDouble(str.substring(3)));
switch (str.charAt(0)) {
case 's':
result = Math.sin(radians);
break;
case 'c':
result = Math.cos(radians);
break;
case 't':
result = Math.tan(radians);
break;
default:
result = 0;
}
}
else
{
num1 = Double.parseDouble(str.substring(0, 1));
num2 = Double.parseDouble(str.substring(4, 5));
switch (str.charAt(2)) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case 'x':
result = num1 * num2;
break;
case '÷':
result = num1 / num2;
break;
default:
result = 0;
}
}
input.setText(Double.toString(result));
JOptionPane.showMessageDialog(null, str + " = " + result);
}
}
/*
* The rest of the action listeners print the button text to the text field.
*/
private class Listener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText("");
}
}
private class Listener3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + " + ");
}
}
private class Listener4 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + " - ");
}
}
private class Listener5 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + " x ");
}
}
private class Listener6 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + " ÷ ");
}
}
private class Listener7 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "0");
}
}
private class Listener8 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "1");
}
}
private class Listener9 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "2");
}
}
private class Listener10 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "3");
}
}
private class Listener11 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "4");
}
}
private class Listener12 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "5");
}
}
private class Listener13 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "6");
}
}
private class Listener14 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "7");
}
}
private class Listener15 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "8");
}
}
private class Listener16 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "9");
}
}
private class Listener17 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "sin");
}
}
private class Listener18 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "cos");
}
}
private class Listener19 implements ActionListener {
public void actionPerformed(ActionEvent e) {
input.setText(input.getText() + "tan");
}
}
/*
* main method
*/
public static void main(String[] args) {
new BasicCalculator();
}
}
</code></pre>
| [] | [
{
"body": "<p>You don't need to have implementations consisting of just single line.\nFor example, you can replace the <code>Listener2</code> direclty with a lambda as :</p>\n\n<pre><code>buttClear = new JButton(\"AC\");\nbuttClear.addActionListener(event -> input.setText(\"\"));\n</code></pre>\n\n<p>Same g... | {
"AcceptedAnswerId": "200383",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-26T21:53:31.170",
"Id": "200378",
"Score": "2",
"Tags": [
"java",
"calculator",
"swing"
],
"Title": "A very basic Java calculator that calculates only single digit numbers"
} | 200378 |
<p>I'm using Digital Persona U.are.U 4000b fingerprint reader and I have this function that verifies the fingerprint from SQL server</p>
<p>My problem is the loop because it takes a lot of time to compare the templates.</p>
<p>Please give me some advice on how can I optimize or revise my code.</p>
<p>CODE:</p>
<pre><code>Protected Sub Process(ByVal Sample As DPFP.Sample)
con = New SqlConnection
con.ConnectionString = "Data Source=Test;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=Passw0rd"
Dim command As String = "SELECT * FROM Bio_Emplist"
Dim da As New SqlDataAdapter(command, con)
Dim dtb As New DataTable
da.Fill(dtb)
If dtb.Rows.Count > 0 Then
rowCount = dtb.Rows.Count
Try
For Each dr As DataRow In dtb.Rows
Dim fpt As Byte() = CType(dr("Fpt"), Byte())
Dim ms As New MemoryStream(fpt)
Dim tmpObj As DPFP.Template = New DPFP.Template
Dim verify As DPFP.Verification.Verification = New DPFP.Verification.Verification
Template = tmpObj
tmpObj.DeSerialize(fpt)
DrawPicture(ConvertSampleToBitmap(Sample))
Dim features As DPFP.FeatureSet = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification)
' Check quality of the sample and start verification if it's good
If Not features Is Nothing Then
' Compare the feature set with our template
Dim result As DPFP.Verification.Verification.Result = New DPFP.Verification.Verification.Result()
verify.Verify(features, Template, result)
'UpdateStatus(result.FARAchieved)
If result.Verified Then
MakeReport("The fingerprint was VERIFIED.")
empID = dr("EmpID")
empFName = dr("FName")
empLName = dr("LName")
SetVerifyText(empID, empFName, empLName)
Exit Try
Else
FailedVerifyText()
If rowCount = 1 Then
MakeReport("The fingerprint was NOT VERIFIED.")
Else
rowCount = rowCount - 1
MakeReport("Finding Match...")
End If
End If
End If
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T11:24:38.167",
"Id": "387460",
"Score": "0",
"body": "Have you tried using parallel.ForEach?"
}
] | [
{
"body": "<p>Remove everything that is repeated in the loop and return/do the same thing. Put them outside the loop. Example, this draw the same image every time, you only need it once.</p>\n\n<pre><code>DrawPicture(ConvertSampleToBitmap(Sample))\n</code></pre>\n\n<p>And this seems to get the same feature ever... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T00:27:22.970",
"Id": "200386",
"Score": "1",
"Tags": [
"performance",
"template",
"vb.net"
],
"Title": "Digital persona fingerprint verification takes a lot of time"
} | 200386 |
<p>I have a personal project that runs the backend under spring boot that implements websocket for real-time functionality and I apply it to a crud operations.</p>
<p>Although the code is working and work as expected I doubt if I do the correct implementation of spring websocket here.</p>
<p>I've used React as my frontend as call the crud function on their <code>@MessageMapping</code> annotation.</p>
<p>The way I implement the backend to my frontend is.</p>
<ul>
<li>Fetching all <code>Person</code> records and store in an array state.</li>
<li>Then for create <code>Person</code> record I just append in to the new record to the persons state array</li>
</ul>
<p>I doubt if I do it correctly because when I debug the websocket client, I found out that it.</p>
<pre><code>@Autowired
private SimpMessagingTemplate template;
@Autowired
public PersonController(PersonRepository personRepository) {
this.personRepository = personRepository;
}
@MessageMapping("/person/add")
public void createPerson(Person person) {
Person savePerson = new Person(person.getFirstName(), person.getLastName());
personRepository.save(savePerson);
this.template.convertAndSend("/topic/person", viewPersons());
}
@RequestMapping("/person")
@ResponseBody
public List<Person> viewPersons(){
List<Person> persons = personRepository.findAll();
return persons;
}
@MessageMapping("/person/delete")
public void deletePerson(@Payload PersonDeleteRequest request) {
Person person = personRepository.findById(request.getId()).orElseThrow(() -> new RuntimeException("No id found."));
personRepository.delete(person);
this.template.convertAndSend("/topic/person", viewPersons());
}
@MessageMapping("/person/update")
public void updatePerson(@Payload Person requestPerson) {
Person person = personRepository.findById(requestPerson.getId()).orElseThrow(() -> new RuntimeException("No id found."));
person.setFirstName(requestPerson.getFirstName());
person.setLastName(requestPerson.getLastName());
personRepository.save(person);
this.template.convertAndSend("/topic/person", viewPersons());
}
</code></pre>
| [] | [
{
"body": "<p><code>@Autowired</code> is not required on constructor in Spring over 4.3 (class has to be annotated as bean and have only one constructor).</p>\n\n<p>Inject <code>SimpMessagingTemplate template</code> in a constructor. Now you mix annotation and constructor injection.</p>\n\n<p>IMHO you shouldn't... | {
"AcceptedAnswerId": "200653",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T01:58:44.413",
"Id": "200388",
"Score": "4",
"Tags": [
"javascript",
"react.js",
"spring",
"websocket"
],
"Title": "Spring Boot Websocket STOMP Crud"
} | 200388 |
<p>I have a stored procedure that is taking more than 2 hours to complete and I noticed the below SQL is taking close to 25 mins for updating a million+ values. There are multiple steps like this and all added up takes around 2+ hours to finish.</p>
<p>All it is doing is taking a column value i.e. <code>birth_year</code> and replacing it with age i.e. <code>getdate() - birth_year</code>.</p>
<pre><code>SELECT id,
birth_month,
birth_year
INTO #birth_date
FROM table_name
WHERE birth_year IS NOT NULL
UPDATE table_name
SET birth_year = ( YEAR(GETDATE()) - bd.birth_year )
FROM #birth_date bd
INNER JOIN table_name ap ON ap.id= bd.id
WHERE bd.birth_month <= MONTH(GETDATE())
OR bd.birth_month IS NULL
UPDATE table_name
SET birth_year = ( YEAR(GETDATE()) - bd.birth_year - 1 )
FROM #birth_date bd
INNER JOIN table_name ap ON ap.id= bd.id
WHERE bd.birth_month > MONTH(GETDATE())
</code></pre>
<p>I replaced the above SQL with the below SQL and now instead of 25 mins, the below SQL takes less than a minute. I've verified the results and all seems good. Is there anything that I am missing? Is there a better or alternate way?</p>
<pre><code>UPDATE table_name
SET birth_year = case
when birth_month <= MONTH(GETDATE()) OR birth_month IS NULL then (YEAR(GETDATE()) - birth_year)
when birth_month > MONTH(GETDATE()) then ( YEAR(GETDATE()) - birth_year - 1 )
else null
end
FROM table_name
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T07:44:08.113",
"Id": "385815",
"Score": "0",
"body": "Please include your DB schema."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-12T14:13:13.330",
"Id": "388057",
"Score": "1",
"body": "W... | [
{
"body": "<p>As per my understanding, you are looking for current age for each records. But for that, you should go ahead with datedifference function by year. no need to calculate this much operation.<br/>\nMake sure you should have index on below columns.<br/>\nbirth_month , birth_year</p>\n\n<p>After all, p... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T03:14:39.050",
"Id": "200390",
"Score": "2",
"Tags": [
"sql",
"time-limit-exceeded",
"sql-server"
],
"Title": "Replacing birth year column values with calculated age value"
} | 200390 |
<p>I am new to PySpark. My goal is to translate this table:</p>
<pre><code>|Key|Value1|Value2|Value3| ...
+---+------+------+------+
| 1| v1| v2| v3|
</code></pre>
<p>into a table like this:</p>
<pre><code>|Key|ColumnName|ColumnValue|
+---+----------+-----------+
| 1| Value1| v1|
| 1| Value2| v2|
| 1| Value3| v3|
</code></pre>
<p>And here is my code for doing so:</p>
<pre><code>from pyspark.sql import *
sample = spark.read.format("csv").options(header='true', delimiter = ',').load("/FileStore/tables/sample.csv")
class Closure:
def __init__(self, columnNames):
self.columnNames = columnNames
def flatMapFunction(self, columnValues):
result = []
columnIndex = 0
for columnValue in columnValues:
if not columnIndex == 0:
result.append(Row(Key = columnValues[0], ColumnName = self.columnNames[columnIndex], ColumnValue = columnValue))
columnIndex = columnIndex + 1
return result
closure = Closure(sample.columns)
sample.rdd.flatMap(closure.flatMapFunction).toDF().show()
</code></pre>
<p>I know it is weird that I have to explicitly created the closure, but it looks like it is required, without which the execution would fail with a weird exception.</p>
<p><strong>Questions</strong>:</p>
<ul>
<li>Is it good code?</li>
<li>Is it going to scale well? There will be a few hundred columns but millions of rows.</li>
<li>Is there anything I should do to improve the code?</li>
</ul>
| [] | [
{
"body": "<p>There is a function in the standard library to create closure for you: <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"noreferrer\"><code>functools.partial</code></a>. This mean you can focus on writting your function as naturally as possible and bother of bind... | {
"AcceptedAnswerId": "200398",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T04:27:54.543",
"Id": "200391",
"Score": "12",
"Tags": [
"python"
],
"Title": "PySpark code that turns columns into rows"
} | 200391 |
<blockquote>
<p>Given an array of words, print the count of all anagrams together in
sorted order (increasing order of counts). For example, if the given
array is {“cat”, “dog”, “tac”, “god”, “act”}, then grouped anagrams
are “(dog, god) (cat, tac, act)”. So the output will be 2 3.</p>
<p><strong>Input:</strong> </p>
<p>First line consists of T test case. First line of every test case
consists of N, denoting the number of words in array. Second line of
every test case consists of words of array.</p>
<p><strong>Output:</strong> </p>
<p>Single line output, print the counts of anagrams in increasing
order.</p>
<p><strong>Constraints:</strong> </p>
<p>1<=T<=100 1<=N<=50</p>
<p><strong>Example:</strong> </p>
<blockquote>
<p>Input: </p>
<p>2 </p>
<p>5 </p>
<p>act
cat tac god dog </p>
<p>3 act cat tac </p>
<p>Output: </p>
<p>2 3 </p>
<p>3</p>
</blockquote>
</blockquote>
<p>My approach:</p>
<pre><code>/*package whatever //do not write package name here */
import java.util.Scanner;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.lang.StringBuffer;
class GFG {
private static void getAnagramCt (String[] words) {
HashMap <String, Integer> anag = new HashMap<>();
List<Integer> counts = new ArrayList<> ();
Set<String> keys;
String[] keyArr;
anag.put(words[0],0);
keys = anag.keySet();
keyArr = keys.toArray(new String[keys.size()]);
for (int i = 1; i < words.length; i++) {
String elem = words[i];
for (int j = 0; j < keyArr.length; j++) {
if (isAnagram(elem,keyArr[j])) {
int ct = anag.get(keyArr[j]);
anag.put(keyArr[j],ct+1);
}
else {
if (j == keyArr.length - 1) {
anag.put(elem, 0);
}
else {
continue;
}
}
}
keys = anag.keySet();
keyArr = keys.toArray(new String[keys.size()]);
}
for (Map.Entry<String,Integer> entry : anag.entrySet()) {
//System.out.println(entry.getKey() + " " + entry.getValue());
counts.add(entry.getValue() + 1);
}
Collections.sort(counts);
for (Integer elem : counts) {
System.out.print(elem + " ");
}
System.out.println();
}
private static boolean isAnagram (String word2, String word1) {
if (word1.length() != word2.length()) {
return false;
}
StringBuffer word = new StringBuffer(word2);
for (int i = 0; i < word1.length(); i++) {
if (word.length() == 0) {
return false;
}
else if (word.indexOf((String.valueOf(word1.charAt(i)))) == -1) {
return false;
}
else {
int ind = word.indexOf((String.valueOf(word1.charAt(i))));
word.deleteCharAt(ind);
}
}
return true;
}
public static void main (String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int numTests = sc.nextInt();
for (int i = 0; i < numTests; i++) {
int numWords = sc.nextInt();
String[] words = new String[numWords];
for (int j = 0; j < numWords; j++) {
words[j] = sc.next();
}
getAnagramCt(words);
}
}
}
</code></pre>
<p>I have the following questions with regards to the above code:</p>
<ol>
<li><p>How can I further improve my approach?</p></li>
<li><p>Is there a better way to solve this question?</p></li>
<li><p>Are there any grave code violations that I have committed?</p></li>
<li><p>Can space and time complexity be further improved?</p></li>
</ol>
<p><a href="https://practice.geeksforgeeks.org/problems/k-anagrams-1/0" rel="nofollow noreferrer">Reference</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T12:09:28.510",
"Id": "385840",
"Score": "1",
"body": "You shouldn't use isAnagram() function, instead sorted characters: \"god\"->\"dgo\", \"dog\"->\"dgo\" and count that. See: https://codereview.stackexchange.com/questions/119904/p... | [
{
"body": "<blockquote>\n<pre><code> for (int i = 0; i < word1.length(); i++) {\n</code></pre>\n</blockquote>\n\n<p>Since you never use <code>i</code> except to calculate <code>word1.charAt(i)</code>, you could more easily do </p>\n\n<pre><code> for (char current : word1.toCharArray()) {\n</cod... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T08:13:52.167",
"Id": "200401",
"Score": "2",
"Tags": [
"java",
"beginner",
"interview-questions",
"cyclomatic-complexity"
],
"Title": "Group Anagrams Together approach in Java"
} | 200401 |
<p>I need to transform the coordinates from spherical to Cartesian space using the Eigen C++ Library. The following code serves the purpose:</p>
<pre><code>const int size = 1000;
Eigen::Array<std::pair<float, float>, Eigen::Dynamic, 1> direction(size);
for(int i=0; i<direction.size();i++)
{
direction(i).first = (i+10)%360; // some value for this example (denoting the azimuth angle)
direction(i).second = (i+20)%360; // some value for this example (denoting the elevation angle)
}
Eigen::MatrixX<T1> transformedMatrix(3, direction.size());
for(int i=0; i<transformedMatrix.cols(); i++)
{
const T1 azimuthAngle = direction(i).first*M_PI/180; //converting to radians
const T1 elevationAngle = direction(i).second*M_PI/180; //converting to radians
transformedMatrix(0,i) = std::cos(azimuthAngle)*std::cos(elevationAngle);
transformedMatrix(1,i) = std::sin(azimuthAngle)*std::cos(elevationAngle);
transformedMatrix(2,i) = std::sin(elevationAngle);
}
</code></pre>
<p>I would like to know a better implementation is possible to improve the speed. I know that Eigen has supporting functions for Geometrical transformations. But I am yet to see a clear example to implement the same. Is it also possible to vectorize the code to improve the performance?</p>
<p>Note: This is a <a href="https://stackoverflow.com/questions/51555759/efficiently-transforming-from-spherical-coordinates-to-cartesian-coordinates-usi">duplicate</a> posting. I think that the question will be more relevant on this site.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T21:39:17.713",
"Id": "385921",
"Score": "0",
"body": "Don't post the exact same question on multiple Stack Exchange sites."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T17:32:44.317",
"Id": "386... | [
{
"body": "<p>There's not really much to review here. While I have some experience with Eigen, I have no idea what SSPL is. I'm going to assume <code>SSPL:MatrixX</code> is basically <code>Eigen::Matrix3Xf</code>.</p>\n\n<pre><code>const int size = 1000;\n</code></pre>\n\n<p>This should probably use <code>const... | {
"AcceptedAnswerId": "200494",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T11:10:05.583",
"Id": "200411",
"Score": "3",
"Tags": [
"c++",
"performance",
"c++11",
"coordinate-system",
"eigen"
],
"Title": "Transforming from spherical coordinates to Cartesian coordinates using Eigen"
} | 200411 |
<p>In a Python (3.6) application I receive messages from Kafka in JSON format. (The code base makes heavy use of <a href="https://docs.python.org/3/library/typing.html" rel="nofollow noreferrer">static type annotations</a>, and every file is automatically checked using <code>mypy --strict</code> to catch type errors as early as possible.)</p>
<p>So I try to deserialize the received messages into objects immediately in order to avoid working with <code>Dict[str, Any]</code> instances in the downstream code. I'd like the deserialization to be type-safe, i.e., to not only fail if not all class members are defined in the JSON string, but also if one or more of them have an incorrect type.</p>
<p>My current approach looks as follows:</p>
<p>(The class <code>Foo</code> in the unit tests is an example of a typical <code>target_class</code>.)</p>
<pre><code>#!/usr/bin/env python3
"""
Type-safe JSON deserialization
"""
import inspect
from typing import Any, List
import json
import unittest
def get_all_member_variable_names(target_class: Any) -> List[str]:
"""Return list of all public member variables."""
all_members = [name for name, _ in inspect.getmembers(target_class,\
lambda a: not inspect.isroutine(a))]
return list(filter(lambda name: not name.startswith("__"), all_members))
def deserialize_json(target_class: Any, object_repr: str) -> Any:
"""Constructs an object in a type-safe way from a JSON strings"""
data = json.loads(object_repr)
members = get_all_member_variable_names(target_class)
for needed_key in members:
if needed_key not in data:
raise ValueError(f'Key {needed_key} is missing.')
dummy = target_class()
for needed_key in members:
json_type = type(data[needed_key])
target_type = type(getattr(dummy, needed_key))
if json_type != target_type:
raise TypeError(f'Key {needed_key} has incorrect type. '
'({json_type} instead of {target_type}')
return target_class(**data)
class Foo():
"""Some dummy class"""
val: int = 0
msg: str = ''
frac: float = 0.0
def __init__(self, val: int = 0, msg: str = '', frac: float = 0.0) -> None:
self.val: int = val
self.msg: str = msg
self.frac: float = frac
class TestDeserialization(unittest.TestCase):
"""Test with valid and invalid JSON strings"""
def test_ok(self) -> None:
"""Valid JSON string"""
object_repr = '{"val": 42, "msg": "hello", "frac": 3.14}'
a_foo: Foo = deserialize_json(Foo, object_repr)
self.assertEqual(a_foo.val, 42)
self.assertEqual(a_foo.msg, 'hello')
self.assertEqual(a_foo.frac, 3.14)
def test_missing(self) -> None:
"""Invalid JSON string: missing a field"""
object_repr = '{"val": 42, "msg": "hello"}'
with self.assertRaises(ValueError):
deserialize_json(Foo, object_repr)
def test_incorrect_type(self) -> None:
"""Invalid JSON string: incorrect type of a field"""
object_repr = '{"val": 42, "msg": "hello", "frac": "incorrect"}'
with self.assertRaises(TypeError):
deserialize_json(Foo, object_repr)
</code></pre>
<p>It works and the unit tests succeed, but I'm not sure if I am missing some potential problem or other opportunities to improve this. It would be cool if you could give me some hints or general criticism.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T12:23:46.223",
"Id": "385843",
"Score": "0",
"body": "@MathiasEttinger The class `Foo` used in the test cases is such an example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T12:33:46.737",
"Id... | [
{
"body": "<p>You need to:</p>\n\n<ol>\n<li>Get the annotated signature of a <code>target_class</code>' <code>__init__</code> method;</li>\n<li>Apply whatever arguments come from the provided JSON string;</li>\n<li>Check that all arguments are present;</li>\n<li>Check that all arguments conform to the annotatio... | {
"AcceptedAnswerId": "200418",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T12:00:08.143",
"Id": "200413",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"json",
"type-safety"
],
"Title": "Type-safe JSON deserialization"
} | 200413 |
<p>I have implemented Conway's Game of Life simulation. What can I improve? How could I structure my programme better? All suggestions would be appreciated.</p>
<p>World.java:</p>
<pre><code>public class World {
private int WORLDSIZE;
private final int DEAD = 0;
private final int ALIVE = 1;
private int world[][];
private int worldCopy[][];
public World(int WORLDSIZE) {
this.WORLDSIZE = WORLDSIZE;
this.world = new int[WORLDSIZE][WORLDSIZE];
this.worldCopy = new int[WORLDSIZE][WORLDSIZE];
}
public int getWorldSize() {
return this.WORLDSIZE;
}
public int[][] getWorld() {
return this.world;
}
public int getCellState(int x, int y) {
if (world[x][y] == ALIVE)
return ALIVE;
else
return DEAD;
}
public int getAlive() {
return this.ALIVE;
}
public int getNeighborCells(int x, int y) {
int neighbors = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (world[i][j] == ALIVE && (x != i || y != j))
neighbors += 1;
}
}
return neighbors;
}
public void createRandomWorld() {
for (int y = 0; y < WORLDSIZE; y++) {
for (int x = 0; x < WORLDSIZE; x++) {
if (Math.random() > 0.9) {
world[x][y] = ALIVE;
} else
world[x][y] = DEAD;
}
}
}
public int[][] applyRules() {
for (int i = 1; i < WORLDSIZE - 1; i++) {
for (int j = 1; j < WORLDSIZE - 1; j++) {
int neighbors = getNeighborCells(i, j);
if (world[i][j] == ALIVE) {
if ((neighbors < 2) || (neighbors > 3)) {
worldCopy[i][j] = DEAD;
}
if (neighbors == 2 || neighbors == 3) {
worldCopy[i][j] = ALIVE;
}
}
if (world[i][j] == 0 && neighbors == 3) {
worldCopy[i][j] = ALIVE;
}
}
}
return worldCopy;
}
public void updateWorld() {
world = applyRules();
}
</code></pre>
<p>Board.java:</p>
<pre><code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Board extends JPanel {
private int width = 250;
private int height = 250;
private World world;
private final int CELLSIZE = 5;
public Board(World world) {
this.world = world;
world.createRandomWorld();
setPreferredSize(new Dimension(width, height));
setBackground(Color.YELLOW);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < world.getWorldSize(); i++) {
for (int j = 0; j < world.getWorldSize(); j++) {
if (world.getCellState(i, j) == world.getAlive()) {
g.setColor(Color.RED);
g.fillRect(i * CELLSIZE, j * CELLSIZE, CELLSIZE, CELLSIZE);
}
else {
g.setColor(Color.YELLOW);
g.fillRect(i * CELLSIZE, j * CELLSIZE, CELLSIZE, CELLSIZE);
}
}
}
}
}
</code></pre>
<p>Simulation.java:</p>
<pre><code>import java.util.Timer;
import java.util.TimerTask;
public class Simulation {
private World world;
private Board board;
private Timer timer = new Timer();
private final int period = 100;
public Simulation(Board board, World world) {
this.board = board;
this.world = world;
this.simulate();
}
public void simulate() {
timer.schedule(new TimerTask() {
@Override
public void run() {
world.applyRules();
world.updateWorld();
board.repaint();
}
}, 0, period);
}
}
</code></pre>
<p>Main.java:</p>
<pre><code>import javax.swing.JFrame;
public class Main {
private World world;
private Board board;
private Simulation simulation;
private JFrame frame = new JFrame("GameOfLife");
private final int width = 250, height = 250;
public Main() {
world = new World(50);
board = new Board(world);
simulation = new Simulation(board, world);
frame.setSize(width, height);
frame.add(board);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
</code></pre>
<p>Thank you in advance. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T09:19:15.410",
"Id": "385961",
"Score": "0",
"body": "do the closing braces and the indentation look exactly like in your IDE? Or did one level of indentation get lost when copying your code into the question?"
}
] | [
{
"body": "<p>I'm going to focus on World, because it's the simplest part and also the main logic behind the program.</p>\n\n<p>The biggest change I'd make is <strong>make World immutable</strong>. Every time you make a change to World, you create a new instance of it. That simplifies thing within World and als... | {
"AcceptedAnswerId": "200421",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T12:31:10.177",
"Id": "200416",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"simulation",
"game-of-life"
],
"Title": "Java Conway's Game Game of Life"
} | 200416 |
<p>I am writing a function to calculate the total size of a "player appearance".</p>
<p>There are various "item slots" the player has, and if they are empty then 1 byte will be sent, otherwise there will be 2.</p>
<pre><code>const getAppearanceBlockSize = (appearance: PlayerAppearance) => {
const headObscured = isCoveringHead(appearance.outfit.head);
return (
40
+ (appearance.outfit.head ? 2 : 1)
+ (appearance.outfit.cape ? 2 : 1)
+ (appearance.outfit.amulet ? 2 : 1)
+ (appearance.outfit.weapon ? 2 : 1)
+ (appearance.outfit.shield ? 2 : 1)
+ (appearance.outfit.head ? 2 : 1)
+ (headObscured ? 2 : 4)
);
};
</code></pre>
<p>The code seems fairly clear to me, but <a href="https://codeclimate.com" rel="nofollow noreferrer" title="Code Climate">Code Climate</a> has given it a high "cognitive complexity" score - indicating that the code is complex and should be broken up.</p>
<p>I can't think of any ways to break the code up, however, that wouldn't result in it being more complex than it currently is.</p>
| [] | [
{
"body": "<p>One option you can try:</p>\n\n<pre><code>return (\n 40 + 5 + 2\n + !!appearance.outfit.head\n + !!appearance.outfit.cape\n + !!appearance.outfit.amulet\n + !!appearance.outfit.weapon\n + !!appearance.outfit.shield\n + 2 * headObscured\n);\n</code></pre>\n\n<p>Take the base si... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T13:08:04.207",
"Id": "200417",
"Score": "5",
"Tags": [
"node.js",
"typescript",
"cyclomatic-complexity"
],
"Title": "Calculating total size of player data"
} | 200417 |
<p>The goal is to collect market data from a free rest api. The response is in json and size per response is above 1MB. I want to get at least updated data once per minute which means about 24h * 60min * 1MB ~ 1.5GB per day of json data. Since i have to collect data over a few weeks in order to start analysing market patterns i have to store the json responses in a space efficient way --> SQLite is my idea so far. Now the ugly part is dealing with nested (4 levels) json and insert it into a relational database.</p>
<p>json example:</p>
<pre><code>{
'country-id': 1,
'name': 'USA',
'states': [
{
'country-id': 1,
'name': 'Alaska',
'state-id': 11,
'cities': [
{
'state-id': 11,
'name': 'Anchorage',
'city-id': 111,
'streets':
[
{
'city-id': 111,
'name': 'Ingra St.',
'street-id': 1111
}
]
},
{
'state-id': 11,
'name': 'Fairbanks',
'city-id': 112,
'streets':
[
{
'city-id': 112,
'name': 'Johansen Expy',
'street-id': 1121
}
]
}
]
},
]
}
</code></pre>
<p>My approach:</p>
<pre><code>from dataclasses import dataclass
from typing import List
@dataclass
class Country:
def __init__(self, country_json):
self.country_id: int = country_json['country-id']
self.name: str = country_json['name']
self.states: List(State) = [State(state) for state in country_json['states']]
@dataclass
class State:
def __init__(self, state_json):
self.country_id: int = state_json['country_id']
self.name: str = state_json['name']
self.state_id: int = state_json['state_id']
self.cities: List(City) = [City(city) for city in state_json['cities']]
@dataclass
class City:
def __init__(self, city_json):
self.state_id: int = city_json['state-id']
self.name: str = city_json['name']
self.city_id: int = city_json['city-id']
self.streets: List(Street) = [Street(street) for street in city_json['street']]
@dataclass
class Street:
def __init__(self, street_json):
self.city_id: int = street_json['city-id']
self.name: str = street_json['name']
self.street_id: int = street_json['street-id']
</code></pre>
<p>Next steps would be to add functions to each dataclass that store the values in a SQlite DB. I am really not sure if my general approach is efficient or if there is a better solution for this kind of problem. My idea in general was that if i build it like this i can easily add other steps e.g. data validation.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T09:38:36.600",
"Id": "386914",
"Score": "0",
"body": "Personally, I'd just store the json as a file (with intelligence to store files in a YYYYMM per-month folder structure) and make an interface to handle any reading/writing of the... | [
{
"body": "<p>You don't use <code>typing</code> properly. <a href=\"https://docs.python.org/3/library/typing.html#generics\" rel=\"nofollow noreferrer\">Parametrizing generic types should be done using brackets notation</a> (aka <code>__getitem__</code>) not parenthesis (aka instantiation).</p>\n\n<p>You also d... | {
"AcceptedAnswerId": "200429",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T14:39:17.693",
"Id": "200422",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"json",
"web-scraping"
],
"Title": "Store nested json repsonses in relational database"
} | 200422 |
<p>I already have my code working, but I believe that could be improved.</p>
<p>This is basically the main part, where I re-order a list of items;</p>
<pre><code>const splice = ($index, item, direction) => {
$scope.list.splice($index, 1);
$scope.list.map((i) => {
if (i.order === item.order) {
i.order = direction === 'up' ? i.order + 1 : i.order - 1;
}
return i;
});
$scope.list.push(item);
$scope.list.sort((a, b) => {
if(a.order < b.order) return -1;
if(a.order > b.order) return 1;
return 0;
});
}
</code></pre>
<p>You can see the entire code here:
<a href="https://codepen.io/rochapablo/pen/jpGKKa" rel="nofollow noreferrer">https://codepen.io/rochapablo/pen/jpGKKa</a></p>
| [] | [
{
"body": "<p>I find it confusing that a function named <code>splice</code> does something different from what it commonly does.\nThis function does too many things:</p>\n\n<ul>\n<li>It removes one item from a list</li>\n<li>It modifies the <code>order</code> field of some items in the list</li>\n<li>It adds an... | {
"AcceptedAnswerId": "200473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T14:41:54.890",
"Id": "200423",
"Score": "-2",
"Tags": [
"javascript",
"sorting"
],
"Title": "Is there a better way to sort this items?"
} | 200423 |
<p>I'm trying to go through Adrian simple programming tasks; Elementary <a href="https://adriann.github.io/programming_problems.html" rel="nofollow noreferrer">task 8</a> It's basically asking for an infinite loop to print every prime number as it finds it. </p>
<p>Are there too many <code>if</code> statements? Call it intuitive knowledge, but something is just bugging me, like I'm missing something. Like, I can remove one of the <code>if</code> statements. So I'm wondering what you guys will find.</p>
<pre><code>package main
import "fmt"
func main() {
var current_prime int
var prime bool
current_prime = 0
for {
prime = true
current_prime++
for i := 2; i < current_prime; i++ {
if current_prime % i == 0 {
prime = false
i = current_prime
}
}
if prime {
fmt.Println("found prime:", current_prime);
}
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p><a href=\"https://adriann.github.io/programming_problems.html\" rel=\"nofollow noreferrer\">Simple Programming Problems</a></p>\n \n <p>Write a program that prints all prime numbers. (Note: if your\n programming language does not support arbitrary size numbers, printing\n all p... | {
"AcceptedAnswerId": "200426",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T14:49:46.373",
"Id": "200424",
"Score": "5",
"Tags": [
"performance",
"primes",
"formatting",
"go"
],
"Title": "Show all primes in go"
} | 200424 |
<p>I built a GUI tool that takes excel files and outputs a finished report to help automate a report at work. It was a fantastic learning experienced and I feel much more comfortable with pandas and python, but I am very aware of some bad programming practices I have included.</p>
<p>I am self taught, and a little stuck on what I should focus on how to improve my program, I'm just looking to be pointed in the right direction.</p>
<p>Most of the program is wrapped into one "Try/Except" block. I'm really not experienced enough to know what else I can do to improve it, aside from implementing some DRY and wrapping part of the program into a function so its not repeated for multiple files.</p>
<p>Could a pandas guru or python guru give me a nudge in the right direction? I'm hitting a block on best practices to implement.</p>
<pre><code>import Tkinter
import pandas as pd
import xlsxwriter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid() # Create the grid
#Label for entering filename
label_one = Tkinter.Label(self, text="Please Enter a Filename:",anchor="w",fg="black",
font="Times_New_Roman 10 bold")
label_one.grid(column=0,row=1,sticky='W')
#Label for entering filename
label_one2 = Tkinter.Label(self, text="Please Enter a 2nd Filename:",anchor="w",fg="black",
font="Times_New_Roman 10 bold")
label_one2.grid(column=0,row=2,sticky='W')
#Example label
label_two = Tkinter.Label(self, text="RXInfoAug1.xlsx",anchor="center",fg="black",
font="Times_New_Roman 10")
label_two.grid(column=1,row=3,sticky='EW')
#Creating label area for user information.
label_three = Tkinter.Label(self, text="Please select User:",anchor='w',fg='black',
font="Times_New_Roman 10 bold")
label_three.grid(column=0,row=4,sticky='EW')
#Label four is for EXAMPLE text
label_four = Tkinter.Label(self,text="Example:",anchor='w',fg='black',
font="Times_New_Roman 10 bold")
label_four.grid(column=0,row=3,sticky='W')
#Label five is below Generate RX report, spits out result information.
label_five = Tkinter.Label(self,text="----------Result Info----------",anchor='center',
fg='black',font="Times_New_Roman 10 bold")
label_five.grid(column=0,row=6,sticky='EW',columnspan=2)
#Label six is return information after clicking the button
self.labelVariable_six = Tkinter.StringVar() #have to create a variable to return
label_six = Tkinter.Label(self,text="None",anchor='center',fg='white',bg="blue",
font='Times_New_Roman 10 bold',
textvariable=self.labelVariable_six) #notice the return variable
label_six.grid(column=0,row=8,sticky='EW',columnspan=2)
#Label seven is more return information, pertaining to after you click the button.
self.labelVariable_seven = Tkinter.StringVar() #creating the return variable
label_seven = Tkinter.Label(self,text="None",anchor='center',fg='white',bg='blue',
font='Times_New_Roman 10 bold',
textvariable=self.labelVariable_seven)
label_seven.grid(column=0,row=9,sticky='EW',columnspan=2)
#Entry Variable creation and location set.
self.entryVariable = Tkinter.StringVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable) #NOTICE the entry var name
self.entry.grid(column=1,row=1,sticky='EW')
#Entry Variable2 creation and location set.
self.entryVariable2 = Tkinter.StringVar()
self.entry2 = Tkinter.Entry(self,textvariable=self.entryVariable2) #NOTICE the entry var name
self.entry2.grid(column=1,row=2,sticky='EW')
#Creating the variable of which user used by option menu
self.var = Tkinter.StringVar(self)
self.var.set("User")
#Creating a drop down menu for user selection
self.option_menu = Tkinter.OptionMenu(self, self.var, "Corey","Warwick","Jane", "Jacque")
self.option_menu.grid(column=1,row=4,sticky='EW')
#Button to generate reports - When clicked runs OnButtonClick
button = Tkinter.Button(self,text="Generate RX Report",
font="Times_New_Roman 12 bold",
command=self.OnButtonClick)
button.grid(column=0,row=6,sticky="EW",columnspan=2)
#Layout management area
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
#Layout Manager resizes if you adjust window
self.resizable(True,True)
self.update()
#sets canvas size (Length, depth)
self.geometry("320x170+300+300")
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
self.entry2.selection_range(0, Tkinter.END)
def OnButtonClick(self):
UserName = self.var.get()
FileName = self.entryVariable.get()
if len(self.entryVariable2.get()) > 0:
FileName2 = self.entryVariable2.get()
else:
FileName2 = self.entryVariable.get()
if UserName == "User":
self.labelVariable_six.set("Please select a User before Continuing")
self.labelVariable_seven.set("")
elif UserName == "Corey":
FilePath = "\cashley\Desktop\\"
self.labelVariable_six.set("Welcome Corey, enjoy the report.")
self.labelVariable_seven.set("Output file is located on desktop")
writer = pd.ExcelWriter('C:\\Users\\cashley\\Desktop\\RX_STATS.xlsx')
elif UserName == "Warwick":
FilePath = "\wbarlow.GMSPRIMARY\Desktop\\"
self.labelVariable_six.set("Welcome Warwick, always great to see you")
self.labelVariable_seven.set("Output file is RX_STATS located on desktop")
writer = pd.ExcelWriter('C:\\Users\\wbarlow.GMSPRIMARY\\Desktop\\RX_STATS.xlsx')
elif UserName == "Jane":
FilePath = "\janen.GMSPRIMARY\Desktop\\"
self.labelVariable_six.set("Welcome Jane, enjoy the report")
self.labelVariable_seven.set("Output file is RX_STATS located on desktop")
writer = pd.ExcelWriter('C:\\Users\\janen.GMSPRIMARY\\Desktop\\RX_STATS.xlsx')
elif UserName == "Jacque":
FilePath = "\jacquea\Desktop\\"
self.labelVariable_six.set("Welcome Jacquea, enjoy the report")
self.labelVariable_seven.set("Output file is RX_STATS located on desktop")
writer = pd.ExcelWriter('C:\\Users\\jacquea\\Desktop\\RX_STATS.xlsx')
try:
df = pd.read_excel("C:\Users" + FilePath + FileName)
#DF_C Was added in so you can bring two files in to compare the two.
df_C = pd.read_excel("C:\Users" + FilePath + FileName2)
df.columns = ['GROUP','MEMBER_NAME','DRUG','CLAIM_DATE','SUB_QUANT','DAYS_SUPPLY','COPAY_AMT','TOTAL_COST']
df_C.columns = ['GROUP','MEMBER_NAME','DRUG','CLAIM_DATE','SUB_QUANT','DAYS_SUPPLY','COPAY_AMT','TOTAL_COST']
df['GROUP'] = df['GROUP'].astype(str)
df_C['GROUP'] = df_C['GROUP'].astype(str)
total_expense = df['TOTAL_COST'].sum()
Y = total_expense * .80
df['PERCENT'] = (df['TOTAL_COST'] / total_expense).round(4)
#Bad DRY here but metrics for analysis for df_C
total_expense_C = df_C['TOTAL_COST'].sum()
Y_C = total_expense_C * .80
df_C['PERCENT'] = (df_C['TOTAL_COST'] / total_expense_C).round(4)
emp_dict = {
'FAKELASTNAME, FAKEFIRSTNAME': 'REDACTED1',
'BOB, FAKE': 'REDACTED2',
'SARAH, FAKE': 'REDACTED3',
}
df['MEMBER_NAME'].replace(emp_dict, inplace=True)
df.loc[df.DRUG.isin(['LATUDA TAB 20MG', 'LATUDA TAB 60MG','LATUDA TAB 40MG']), 'DRUG'] = 'LATUDA TAB'
df.loc[df.DRUG.isin(['HUMIRA START KIT 40MG PEN', 'HUMIRA PEN INJ 40MG/0.8','HUMIRA KIT 40MG SYN']), 'DRUG'] = 'HUMIRA'
df.loc[df.DRUG.isin(['ENBREL SCLIK SYR 50MG/ML', 'ENBREL SYR 50MG/ML','ENBREL SYR 25/0.5ML']), 'DRUG'] = 'ENBREL'
df.loc[df.DRUG.isin(['TRULICITY(4) PEN 1.5/0.5', 'TRULICITY(4) PEN 0.75/0.5']), 'DRUG'] = 'TRULICITY'
df_C['MEMBER_NAME'].replace(emp_dict, inplace=True)
df_C.loc[df_C.DRUG.isin(['LATUDA TAB 20MG', 'LATUDA TAB 60MG','LATUDA TAB 40MG']), 'DRUG'] = 'LATUDA TAB'
df_C.loc[df_C.DRUG.isin(['HUMIRA START KIT 40MG PEN', 'HUMIRA PEN INJ 40MG/0.8','HUMIRA KIT 40MG SYN']), 'DRUG'] = 'HUMIRA'
df_C.loc[df_C.DRUG.isin(['ENBREL SCLIK SYR 50MG/ML', 'ENBREL SYR 50MG/ML','ENBREL SYR 25/0.5ML']), 'DRUG'] = 'ENBREL'
df_C.loc[df_C.DRUG.isin(['TRULICITY(4) PEN 1.5/0.5', 'TRULICITY(4) PEN 0.75/0.5']), 'DRUG'] = 'TRULICITY'
df2 = df['TOTAL_COST'].groupby(df['MEMBER_NAME']).sum().nlargest(10)
df3 = df['TOTAL_COST'].groupby(df['DRUG']).sum().nlargest(20)
df4 = df['MEMBER_NAME'].value_counts().nlargest(20)
df5 = df['PERCENT'].groupby(df['MEMBER_NAME']).sum().nlargest(20)
df7 = df[df['TOTAL_COST'] > 0]
df8 = df['TOTAL_COST'].groupby(df['MEMBER_NAME']).sum().nlargest(1000)
df13 = df['TOTAL_COST'].groupby(df['GROUP']).sum().nlargest(5)
count = 0
total = 0
for row in df8:
if total < Y:
total = total + row
count += 1
WW = count
#Count of how many Members are in the file. It combines duplicate individuals with nunique.
Ind_count = df['MEMBER_NAME'].nunique()
# Count of non zero individuals in the file.
Ind_count_nonzero = df7['MEMBER_NAME'].nunique()
# Finding what 20 percent of the total is
twenty_percent1 = Ind_count_nonzero * .20
twenty_percent = round(twenty_percent1,0)
row_count = df.shape[0]
df10 = df['PERCENT'].groupby(df['MEMBER_NAME']).sum().nlargest(WW)
group_dict = {
'2006':'GROUPNAME1',
'2033':'GROUPNAME2',
'2041':'GROUPNAME3',
}
df['GROUP'].replace(group_dict, inplace=True)
df_C['GROUP'].replace(group_dict, inplace=True)
df15 = df_C[~df_C.MEMBER_NAME.isin(df.MEMBER_NAME)]
pivot_C = pd.pivot_table(df15, index=['MEMBER_NAME','GROUP'],values=['TOTAL_COST'], aggfunc='sum')
pivot_C2 = pivot_C.sort_values(by=['TOTAL_COST'],ascending=False)
pv_C = pivot_C2.head(20)
pv_C2 = pv_C.reset_index()
df13 = df['TOTAL_COST'].groupby(df['GROUP']).sum().nlargest(5)
df3 = df3.reset_index()
df2 = df2.reset_index()
df4 = df4.reset_index()
df5 = df5.reset_index()
df10 = df10.reset_index()
df13 = df13.reset_index()
pivot2 = pd.pivot_table(df, index=['MEMBER_NAME','GROUP'],values=['TOTAL_COST'], aggfunc='sum')
pivot3 = pivot2.sort_values(by=['TOTAL_COST'],ascending=False)
pv3 = pivot3.head(20)
pv4 = pv3.reset_index()
writer = pd.ExcelWriter('C:\\Users' + FilePath + 'RX_STATS.xlsx')
#writer = pd.ExcelWriter('C:\\Users\\wbarlow.GMSPRIMARY\\Desktop\\RX_STATS.xlsx')
pv4.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=0,startrow=10)
pv_C2.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=0,startrow=35)
df3.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=4,startrow=10)
df4.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=7,startrow=10)
df10.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=10,startrow=10)
df13.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=4,startrow=0)
df.to_excel(writer, sheet_name='Raw Data',index=False,header=True)
df_C.to_excel(writer, sheet_name='Compare Data',index=False,header=True)
worksheet1 = writer.sheets['Summary']
worksheet2 = writer.sheets['Raw Data']
worksheet3 = writer.sheets['Compare Data']
workbook = writer.book
format1 = workbook.add_format({'num_format':'$#,###.##'})
format6 = workbook.add_format({'num_format':'$#,###.##','bold':True})
format2 = workbook.add_format({'bold': True})
format5 = workbook.add_format({'bold': True,'border':1,'align':'center'})
format3 = workbook.add_format({'bold': True, 'align': 'center'})
format4 = workbook.add_format({'num_format':'0.00%'})
merge_format = workbook.add_format({
'bold':1,
'border':1,
'align':'center'})
worksheet1.write('A1', "Caremark File Statistics", format2)
worksheet1.write('A6', "Individual Count:", format2)
worksheet1.write('A3', "Individual Non-Zero Count:", format2)
worksheet1.write('A4', "Twenty percent of all individuals:", format2)
worksheet1.write('A5', "Count representing eighty percent:", format2)
worksheet1.write('A2', "RX Total Expense:", format2)
worksheet1.write('B6', Ind_count, format2)
worksheet1.write('B3', Ind_count_nonzero, format2)
worksheet1.write('B4', twenty_percent, format2)
worksheet1.write('B5', WW, format2)
worksheet1.write('B2', total_expense, format6)
worksheet1.conditional_format('C12:C31',{'type':'cell',
'criteria':'>=',
'value':1,
'format':format1})
worksheet1.conditional_format('F12:F31',{'type':'cell',
'criteria':'>=',
'value':1,
'format':format1})
worksheet1.conditional_format(11,11,11+WW,11,{'type':'cell',
'criteria':'>=',
'value':0,
'format':format4})
worksheet1.conditional_format('F2:F6',{'type':'cell',
'criteria':'>=',
'value':0,
'format':format1})
worksheet2.conditional_format(1,8,row_count,8,{'type':'cell',
'criteria':'>=',
'value':0,
'format':format4})
worksheet3.conditional_format(1,8,row_count,8,{'type':'cell',
'criteria':'>=',
'value':0,
'format':format4})
worksheet1.conditional_format('C37:C56',{'type':'cell',
'criteria':'>=',
'value':1,
'format':format1})
worksheet1.set_column(0,0,32)
worksheet1.set_column(1,1,35)
worksheet1.set_column(2,2,12)
worksheet1.set_column(3,3,5)
worksheet1.set_column(4,4,36)
worksheet1.set_column(5,5,12)
worksheet1.set_column(6,6,5)
worksheet1.set_column(7,7,30)
worksheet1.set_column(8,8,12)
worksheet1.set_column(9,9,5)
worksheet1.set_column(10,10,30)
worksheet1.set_column(11,11,12)
worksheet2.set_column(0,0,35)
worksheet2.set_column(1,1,30)
worksheet2.set_column(2,2,35)
worksheet2.set_column(3,3,20)
worksheet2.set_column(4,4,13)
worksheet2.set_column(5,5,13)
worksheet2.set_column(6,6,13)
worksheet2.set_column(7,7,13)
worksheet2.set_column(8,8,9)
worksheet3.set_column(0,0,35)
worksheet3.set_column(1,1,30)
worksheet3.set_column(2,2,35)
worksheet3.set_column(3,3,20)
worksheet3.set_column(4,4,13)
worksheet3.set_column(5,5,13)
worksheet3.set_column(6,6,13)
worksheet3.set_column(7,7,13)
worksheet3.set_column(8,8,9)
worksheet1.merge_range('A9:C9','Top Twenty Expense Individuals',merge_format)
worksheet1.merge_range('E9:F9','Top Twenty RX Prescriptions', merge_format)
worksheet1.merge_range('H9:I9','Top Twenty Prescription Fills Per Person', merge_format)
worksheet1.merge_range('K9:L9','Individuals Representing 80% of Total Cost', merge_format)
worksheet1.merge_range('A34:C34','New Individuals with Largest RX Totals', merge_format)
worksheet1.write('H11', 'MEMBER_NAME', format5)
worksheet1.write('I11','COUNT',format5)
worksheet1.write('E1','LARGEST RX GROUPS',format5)
worksheet1.write('A36','MEMBER NAME', format5)
writer.save()
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
except:
self.labelVariable_six.set("Confirm User is accurate.")
self.labelVariable_seven.set("Confirm your filename.")
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('WB Caremark Cleaner')
app.mainloop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T15:40:57.820",
"Id": "385881",
"Score": "1",
"body": "Welcome to Code Review! I suspect that `emp_dict` and `group_dict` are supposed to be initialized with some data? Could you fill in some fake sample entries?"
},
{
"Conte... | [
{
"body": "<p>To get this working for Python 3, I needed to change:</p>\n\n<pre><code>import Tkinter\nclass simpleapp_tk(Tkinter.Tk):\n</code></pre>\n\n<p>to</p>\n\n<pre><code>import tkinter\nclass simpleapp_tk(tkinter.Tk):\n</code></pre>\n\n<p>So just a lower case for tkinter (a global search/replace). Warwick... | {
"AcceptedAnswerId": "200885",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T15:04:35.727",
"Id": "200425",
"Score": "4",
"Tags": [
"python",
"beginner",
"pandas",
"tkinter"
],
"Title": "Pandas/Tkinter GUI Excel report generator"
} | 200425 |
<p>For traversing 70,000 rows (using a <code>for</code> loop), my macro is taking a lot of time to give output comment as per various conditions (<code>if</code> statement). Please help me improve my approach. I am working on around 70,000 rows and my code is taking a lot of time to run. Please see the attachment image that depicts how data looks.</p>
<p><a href="https://i.stack.imgur.com/FIXVx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FIXVx.png" alt="enter image description here"></a></p>
<pre><code>Option Explicit
Sub Analysis()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
ActiveSheet.DisplayPageBreaks = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Dim wsa As Worksheet
Dim l, AudLastRow, AudLastCol, NIMsLastCol, NIMsRow As Long
Dim d19, d8, d25, p19, p8, p25 As Integer
Dim ColLtr As String
Dim aPRTS, bNIMS, Deployed19, Deployed800, Deployed2500, PRTS800, PRTS1900, PRTS2500 As Variant
Set wsa = ThisWorkbook.Worksheets("Audit-NIMS vs Site Topology")
NIMsLastCol = ThisWorkbook.Sheets("NIMSCarrierCount").Cells(2, Columns.Count).End(xlToLeft).Column
NIMsRow = ThisWorkbook.Sheets("NIMS dump-SC level").Cells(Rows.Count, 2).End(xlUp).Row
With wsa
AudLastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
AudLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
.Cells(1, AudLastCol + 1).Value = "Match;Issue Type;Actions"
For l = 2 To AudLastRow
aPRTS = .Cells(l, AudLastCol).Value
bNIMS = .Cells(l, NIMsLastCol).Value
' tempin = .Cells(l, 2).Value
If aPRTS = bNIMS Then
Deployed19 = Application.Match("Deployed(1.9)", .Rows(1), 0)
If IsNumeric(Deployed19) Then
d19 = .Cells(l, Deployed19).Value
Else
d19 = 0
End If
Deployed800 = Application.Match("Deployed (800)", .Rows(1), 0)
If IsNumeric(Deployed800) Then
d8 = .Cells(l, Deployed800).Value
Else
d8 = 0
End If
Deployed2500 = Application.Match("Deployed (2.5)", .Rows(1), 0)
If IsNumeric(Deployed2500) Then
d25 = .Cells(l, Deployed2500).Value
Else
d25 = 0
End If
PRTS800 = Application.Match("Total-800-PRTS", .Rows(1), 0)
If IsNumeric(PRTS800) Then
p8 = .Cells(l, PRTS800).Value
Else
p8 = 0
End If
PRTS1900 = Application.Match("Total-1900-PRTS", .Rows(1), 0)
If IsNumeric(PRTS1900) Then
p19 = .Cells(l, PRTS1900).Value
Else
p19 = 0
End If
PRTS2500 = Application.Match("Total-2500-PRTS", .Rows(1), 0)
If IsNumeric(PRTS2500) Then
p25 = .Cells(l, PRTS2500).Value
Else
p25 = 0
End If
If (p19 = d19) And (p8 = d8) And (p25 = d25) Then
.Cells(l, AudLastCol + 1).Value = "TRUE;None;No Action Required."
Else
.Cells(l, AudLastCol + 1).Value = "FALSE;Both;Update NIMS and PRTS."
End If
ElseIf aPRTS = "NA" And bNIMS = "0" Then
.Cells(l, AudLastCol + 1).Value = "TRUE;None;No Action Required."
ElseIf aPRTS = "0" And bNIMS = "NA" Then
.Cells(l, AudLastCol + 1).Value = "TRUE;None;No Action Required."
ElseIf aPRTS > 0 And bNIMS = "NA" Then
.Cells(l, AudLastCol + 1).Value = "N/A;NIMS;Update NIMS."
ElseIf bNIMS > 0 And aPRTS = "NA" Then
.Cells(l, AudLastCol + 1).Value = "N/A;PRTS;Check traffic from PRTS & Report to PRTS Team."
ElseIf bNIMS > aPRTS Then
.Cells(l, AudLastCol + 1).Value = "FALSE;PRTS;Check traffic from PRTS & Report to PRTS Team."
ElseIf bNIMS < aPRTS Then
.Cells(l, AudLastCol + 1).Value = "FALSE;NIMS;Update NIMS."
End If
If InStr(1, .Cells(l, 1).Value, "52XC") > 0 Then
.Cells(l, AudLastCol + 1).Value = .Cells(l, AudLastCol + 1).Value & "Clearwire Site."
ElseIf InStr(1, .Cells(l, 1).Value, "82XC") > 0 Then
.Cells(l, AudLastCol + 1).Value = .Cells(l, AudLastCol + 1).Value & "Clearwire Site."
ElseIf InStr(1, .Cells(l, 1).Value, "XT") > 0 Then
.Cells(l, AudLastCol + 1).Value = .Cells(l, AudLastCol + 1).Value & "COW Site."
End If
If bNIMS = "NA" And Application.CountIf(ThisWorkbook.Sheets("NIMS dump-SC level").Range("B1:B" & NIMsRow), .Cells(l, 2).Value) Then
.Cells(l, AudLastCol + 1).Value = Cells(l, AudLastCol + 1).Value & "Present in NIMS Dump."
End If
Next l
End With
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
ActiveSheet.DisplayPageBreaks = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T12:19:32.910",
"Id": "385972",
"Score": "0",
"body": "How do you know this snippet is the bottleneck? How long does it take right now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T12:25:16.123",
... | [
{
"body": "<p>Your logic is probably the biggest factor here. Using your estimate of 70,000 rows and assuming that <code>aPRTS</code> and <code>bNIMS</code> are equal for all of them, then you are doing around 420,000 <code>Match</code> calculations and an even greater number of accesses to cells (with all the ... | {
"AcceptedAnswerId": "200500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T15:46:53.853",
"Id": "200427",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "Generating output comment for 70000 rows"
} | 200427 |
<p><strong>Problem Description</strong></p>
<blockquote>
<p>The objective is to form the maximum possible time in the HH:MM:SS
format using any six of nine given single digits (not necessarily
distinct) </p>
<p>Given a set of nine single (not necessarily distinct)
digits, say 0, 0, 1, 3, 4, 6, 7, 8, 9, it is possible to form many
distinct times in a 24 hour time format HH:MM:SS, such as 17:36:40 or
10:30:41 by using each of the digits only once. The objective is to
find the maximum possible valid time (00:00:01 to 24:00:00) that can
be formed using some six of the nine digits exactly once. In this
case, it is 19:48:37.</p>
<p><strong>Input Format</strong></p>
<p>A line consisting of a sequence of 9 (not necessarily distinct) single
digits (any of 0-9) separated by commas. The sequence will be
non-decreasing</p>
<p><strong>Output</strong></p>
<p>The maximum possible time in a 24 hour clock (00:00:01 to 24:00:00) in
a HH:MM:SS form that can be formed by using some six of the nine given
digits (in any order) precisely once each. If no combination of any
six digits will form a valid time, the output should be the word
Impossible</p>
<p><strong>Explanation</strong></p>
<p>Example 1 </p>
<p>Input </p>
<p>0,0,1,1,3,5,6,7,7 </p>
<p>Output 17:57:36 </p>
<p>Explanation: The maximum valid
time in a 24 hour clock that can be formed using some six of the 9
digits precisely once is 17:57:36 </p>
<hr>
<p>Example 2 </p>
<p>Input</p>
<p>3,3,3,3,3,3,3,3,3</p>
<p>Output</p>
<p>Impossible</p>
<p>Explanation: No set of six digits from the input may be used to
form a valid time.</p>
</blockquote>
<p><strong>The Code:</strong></p>
<pre><code>def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] < arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
seq_a=list(map(int,input().split(',')))
# print(seq_a)
bubbleSort(seq_a)
# print(seq_a)
hrs=[None,None]
mins=[None,None]
secs=[None,None]
#hrs
for x in seq_a:
if x <= 2:
hrs[0]=x
seq_a.remove(x)
break
# print(seq_a)
# print(hrs,mins,secs)
if hrs[0]:
if hrs[0]==2:
for x in seq_a:
if x <= 4:
hrs[1]=x
seq_a.remove(x)
break
else:
for x in seq_a:
if x <= 9:
hrs[1]=x
seq_a.remove(x)
break
# print(seq_a)
# print(hrs,mins,secs)
#mins
if hrs[1]:
for x in seq_a:
if x < 6:
mins[0]=x
seq_a.remove(x)
break
# print(seq_a)
# print(hrs,mins,secs)
if mins[0]:
for x in seq_a:
if x <= 9:
mins[1]=x
seq_a.remove(x)
break
# print(seq_a)
# print(hrs,mins,secs)
#secs
if mins[1]:
for x in seq_a:
if x < 6:
secs[0]=x
seq_a.remove(x)
break
# print(seq_a)
# print(hrs,mins,secs)
if secs[0]:
for x in seq_a:
if x <= 9:
secs[1]=x
seq_a.remove(x)
break
# print(seq_a)
# print(hrs,mins,secs)
if secs[1]:
print(str(hrs[0])+str(hrs[1])+':'+str(mins[0])+str(mins[1])+':'+str(secs[0])+str(secs[1]))
else:
print('Impossible')
</code></pre>
| [] | [
{
"body": "<h2>Bugs</h2>\n\n<p>Your program produces these erroneous results:</p>\n\n<ul>\n<li><p><code>0,5,5,5,5,5,5,5,9</code> → <code>Impossible</code> (should be <code>09:55:55</code>)<br>\n<code>0,2,5,5,5,5,5,5,5</code> → <code>Impossible</code> (should be <code>20:55:55</code>)</p>\n\n<p>Due to tests like... | {
"AcceptedAnswerId": "200439",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T18:06:33.810",
"Id": "200434",
"Score": "7",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"datetime"
],
"Title": "Code Vita: Form the maximum possible time in the HH:MM:SS format using any six of nine given single digits"
} | 200434 |
<p>I needed to write a function in JavaScript which checks if any rotation of an array is equal to another array.</p>
<p>By rotation, I mean:</p>
<pre><code>rotate [1, 2, 3] --> [3, 1, 2]
rotate [3, 1, 2] --> [2, 3, 1]
rotate [2, 3, 1] --> [1, 2, 3]
</code></pre>
<p>Here's the code for my function. It feels pretty verbose, especially since the array functions added by ES6 seem perfect for this sort of thing, yet I've used very few of them. In particular, using a label on the outer loop feels wrong.</p>
<p>Is there any way I can make this function shorter and/or faster?</p>
<pre><code>/**
* Taking two arrays, checks whether one may be rotated so that it equals
* the other.
*/
function arraysEqualByRotation(first, second) {
if (first.length !== second.length) {
return false;
}
// We'll rotate the first continually and compare it to the second
var rotatedFirst = first.slice(0);
outer:
for (var rotateCounter = 0; rotateCounter < rotatedFirst.length; rotateCounter++) {
// Rotate the array
rotatedFirst.unshift(rotatedFirst.pop());
// Check if their elements are equal
for (var i = 0; i < rotatedFirst.length; i++) {
if (rotatedFirst[i] !== second[i]) {
// Try another rotation
continue outer;
}
}
// At this stage, they're equal
return true;
}
// At this stage, a matching combination was never found
return false;
}
</code></pre>
<p>Example inputs and outputs:</p>
<pre><code>first | second | result
-----------------------------------------------
[1, 2, 3] | [1, 2, 3] | true (same array)
[1, 2, 3] | [3, 1, 2] | true (rotate once)
[1, 2, 3] | [2, 3, 1] | true (rotate twice)
[1, 2] | [1, 2, 3] | false (different lengths)
[1, 2, 3] | [1, 3, 2] | false (no valid rotation)
</code></pre>
| [] | [
{
"body": "<p>I have not looked too deeply into the problem and I am guessing that there may be some function that produces a unique hash based on the sequence and independent of starting position. That would then only require that you iterate each array to create the hash and then compare to see if they match.... | {
"AcceptedAnswerId": "200456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T18:34:29.657",
"Id": "200435",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"array"
],
"Title": "Checking if an array can be rotated to equal another in JavaScript"
} | 200435 |
<p>The idea is to calculate sum of diagonals
example [[1,2,3],[4,5,6],[7,8,9] the correct answer would be [1,5,9][3,5,7] = total 30</p>
<pre><code>def sum_of_matrix(data):
arr_solver = []
counter = 0
counter2 = -1
while counter < len(data):
arr_solver.append(data[counter][counter])
arr_solver.append(data[counter][counter2])
counter += data[counter][counter2]
counter2 -= data[counter][counter]
return sum(arr_solver)
</code></pre>
<p>This is my todays interview question I had, is this a good solution to a question?
My idea was to implement a graph and calculate path, but that'd take waaaaay too long and probably wouldn't be able to implement it on the go.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T20:22:22.453",
"Id": "385908",
"Score": "3",
"body": "Your example does not work. `sum_of_matrix([[1,2,3],[4,5,6],[7,8,9]])` aborts with `IndexError`."
}
] | [
{
"body": "<p>The algorithm that you have implemented right now just raises an <code>IndexError</code>.</p>\n\n<p>I'll suggest a slightly different way to do is that will have <code>O(n)</code> speed and <code>O(1)</code> memory, where <code>n</code> is the side length of the matrix.</p>\n\n<p>Correct me if I'm... | {
"AcceptedAnswerId": "200443",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T18:56:49.113",
"Id": "200437",
"Score": "-3",
"Tags": [
"python",
"matrix"
],
"Title": "Sum of diagonal elements in a matrix"
} | 200437 |
<p>I wrote my <a href="https://en.wikipedia.org/wiki/Sierpinski_triangle" rel="nofollow noreferrer" title="Sierpinski Triangle">Sierpinski Triangle</a> fractal animation using HTML canvas with JavaScript: <a href="https://jsfiddle.net/2x4wzb5c/" rel="nofollow noreferrer">JsFiddle</a></p>
<p>What do you think about it? How I can optimize it, if you see a need for that?</p>
<p>Code:</p>
<pre><code>requestAnimationFrame(update);
const canvas = document.getElementById("c");
const context = canvas.getContext('2d');
var iterations = 0; //how many iterations to perform in current frame, count of fractal func invokes grows exponentially and can be calculated from sum: E 3^k, k = 0 to iterations
const maxIterations = 8; //used when animating, it's better to set 'gradientAnimation' to false, when setting 'maxIterations' to bigger values
const center = { x: canvas.width * 0.5, y: canvas.height * 0.5 };
const halfTriangleSide = 250;
//color animation
const gradientAnimation = true;
var t = 0;
var speed = 0.1;
//division animation
var divideAnim = true;
var divide = true; //loop flag
var mod = 0.0; //color modificator
function drawTriangle(A, B, C)
{
context.beginPath();
context.moveTo(A.x, A.y);
context.lineTo(B.x, B.y);
context.lineTo(C.x, C.y);
context.lineTo(A.x, A.y);
if(gradientAnimation)
{
context.fillStyle =
"rgb(" +
((A.x + A.y) * 0.19 * mod) + "," +
((B.x + B.y) * 0.15 * mod) + "," +
((C.x + C.y) * 0.22 * mod) +
")";
}
context.fill();
}
function fractal(center, halfSideLen, i)
{
i++;
var quaterSide = halfSideLen * 0.5;
//calc new triangle coords
var A = {
x: center.x - quaterSide,
y: center.y
};
var B = {
x: center.x + quaterSide,
y: center.y
};
var C = {
x: center.x,
y: center.y + halfSideLen
};
drawTriangle(A, B, C);
if(i < iterations)
{
fractal({x: A.x, y: A.y + quaterSide}, quaterSide, i);
fractal({x: B.x, y: B.y + quaterSide}, quaterSide, i);
fractal({x: C.x, y: C.y - (halfSideLen + quaterSide)}, quaterSide, i);
}
}
function update()
{
context.clearRect(0, 0, canvas.width, canvas.height);
//init coords
var A = {
x: center.x - halfTriangleSide,
y: center.y + halfTriangleSide
};
var B = {
x: center.x + halfTriangleSide,
y: center.y + halfTriangleSide
};
var C = {
x: center.x,
y: center.y - halfTriangleSide
};
context.fillStyle = "#F00";
drawTriangle(A, B, C);
context.fillStyle = "#000";
if(iterations != 0) fractal(center, halfTriangleSide, 0);
t += speed;
if(t > Math.PI * 2)
{
t = 0;
if(divideAnim)
{
if(iterations == maxIterations) divide = false;
else if(iterations == 0) divide = true;
if(divide) iterations++;
else iterations--;
}
}
if(gradientAnimation)
{
mod = 1.25 - Math.sin(t) * 0.5;
}
requestAnimationFrame(update);
}
</code></pre>
| [] | [
{
"body": "<h2>Good things:</h2>\n<ul>\n<li><code>const</code> is used for variables that shouldn't be re-assigned</li>\n<li><code>requestAnimationFrame()</code> is used for animating</li>\n<li>constants and global variables are declared at the top of the script.</li>\n<li>only three functions are used</li>\n</... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T19:55:29.723",
"Id": "200441",
"Score": "9",
"Tags": [
"javascript",
"animation",
"canvas",
"fractals"
],
"Title": "Sierpinski triangle html canvas Implementation"
} | 200441 |
<p>The following code attempts to efficiently stream queue messages to processing units using an IEnumerable yield return.</p>
<ol>
<li>create a blocking collection to handle the stream</li>
<li>create a linked token source to abort by external call or internal one</li>
<li>read from q by the EventingBasicConsumer and add messages to the
blocking collection.</li>
<li>start a while loop to yield return the messages to the caller.</li>
<li><p>in abort case clean the blocking collection wait for acks and close the connection. </p>
<pre><code>private EventingBasicConsumer GetConsumer(string queueName, ushort prefetchCount = 10)
{
_channel = Connection.CreateModel();
_channel.BasicQos(
prefetchSize: 0,
prefetchCount: prefetchCount,
global: false
);
_channel.QueueDeclare(
queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null
);
return new EventingBasicConsumer(_channel);
}
/// <summary>
/// Consumer running continuously to listen for messages
/// </summary>
/// <typeparam name="T">MQContractObject</typeparam>
/// <param name="queueName">The queue name to listen to.</param>
/// <param name="cancellationToken">The cancellation token to about the operation.</param>
/// <param name="autoAck">True to automatically acknowledge dequeue messages. other wise false and let to process acknowledge the message when done.</param>
/// <param name="prefetchCount">the max number of message the queue will serve without acknowledgment on previous ones</param>
/// <returns>yield enumerator of type T</returns>
public IEnumerable<T> DequeueYield<T>(string queueName, CancellationToken cancellationToken = default(CancellationToken), bool autoAck = true, ushort prefetchCount = 10) where T : MQContractObject
{
using (var resultsQueue = new BlockingCollection<T>())
{
using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
EventingBasicConsumer consumer = null;
var isConsumerError = false;
void cancelRun() {
try
{
tokenSource.Cancel();
}
catch (ObjectDisposedException)
{
}
}
void recivedHandler(object sender, BasicDeliverEventArgs ea)
{
try
{
var body = _utensils.ByteArrayToObject<T>(ea.Body);
body.DeliveryTag = ea.DeliveryTag;
resultsQueue.Add(body);
}
catch (Exception ex)
{
logger.Error($"Failed to receive message from queue '{queueName}'.", ex);
isConsumerError = true;
unRegisterHandlers();
cancelRun();
}
}
void consumerHandler(object sender, ConsumerEventArgs ea)
{
lock (_locker)
{
isConsumerError = true;
unRegisterHandlers();
cancelRun();
}
}
void shutdownHandler(object sender, ShutdownEventArgs ea)
{
lock (_locker)
{
if (!tokenSource.IsCancellationRequested)
{
logger.Warn($"RabbitSimpleReceiver:: DequeueYield has initiated a shutdown, cause { ea.Cause?.ToString() }. will try to read from queue again in 1/2 sec.");
Task.Delay(500).Wait();
// try reading from q again.
readFromQueue();
}
}
}
void unRegisterHandlers()
{
if(consumer!= null)
{
consumer.Received -= recivedHandler;
consumer.Shutdown -= shutdownHandler;
consumer.ConsumerCancelled -= consumerHandler;
}
}
void registerHandlers()
{
//https://stackoverflow.com/a/7065771/395890
unRegisterHandlers();
if (consumer != null)
{
consumer.Received += recivedHandler;
consumer.ConsumerCancelled += consumerHandler;
consumer.Shutdown += shutdownHandler;
}
}
void readFromQueue()
{
lock (_locker)
{
if (consumer == null)
{
consumer = GetConsumer(queueName, prefetchCount);
}
if (consumer.IsRunning)
{
return;
}
registerHandlers();
_channel.BasicConsume(
queue: queueName,
autoAck: autoAck,
consumer: consumer
);
}
}
try
{
readFromQueue();
T result = null;
while (true)
{
result = null;
try
{
result = resultsQueue.Take(tokenSource.Token);
}
catch (OperationCanceledException)
{
unRegisterHandlers();
break;
}
catch (ObjectDisposedException)
{
unRegisterHandlers();
break;
}
yield return result;
}
// empty the blocking collection.
while (resultsQueue.TryTake(out result))
{
yield return result;
}
if (!autoAck)
{
Task.Delay(MaxTimeToLeaveTheConnectionOpenForAckAfterCancelactionRequest).Wait();
}
if (isConsumerError)
{
throw new Exception(consumer.ShutdownReason.ToString());
}
else
{
yield break;
}
}
finally
{
CloseConnection(consumer);
}
}
}
}
</code></pre></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T21:34:02.530",
"Id": "385919",
"Score": "3",
"body": "Local functions are great helpers but you really overuse them here. Defining those somewhere in the middle of some statement makes it very confusing. They could all be static met... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T20:23:24.073",
"Id": "200442",
"Score": "4",
"Tags": [
"c#",
"performance",
"rabbitmq"
],
"Title": "Rabbit MQ long running de-queue by using IEnumerable yield return"
} | 200442 |
<p>This is a percolation of ideas which originated this SO question:</p>
<p><a href="https://stackoverflow.com/questions/51506521/">Compound pointer traits class with method generalizing make_shared and make_unique?</a></p>
<p>The <a href="https://en.cppreference.com/w/cpp/memory/pointer_traits" rel="nofollow noreferrer"><code>std::pointer_traits</code> class</a> offers the following traits, basically:</p>
<p>Types: <code>pointer</code>, <code>element_type</code>, <code>difference_type</code>, and <code>rebind</code> (given a pointer-like type for pointing to <code>T</code>, get a pointer-like type for pointing to <code>U</code>)</p>
<p>Static methods:</p>
<ul>
<li><code>to_address</code> - get the plain vanilla T* from some fancy pointer-to-T-like class, if possible</li>
<li><code>pointer_to</code> - opposite of <code>to_address</code>. This is a fishy method, since it's not clear what it means with respect to resource ownership.</li>
</ul>
<p>I think it's useful to add at least two methods - for creating a pointer to a new object / array of objects, a-la <code>std::make_shared</code> and <code>std::make_unique</code>, and one for releasing ownership + getting the raw address. Here's my implementation:</p>
<pre><code>#pragma once
#ifndef EXTRA_POINTER_TRAITS_HPP_
#define EXTRA_POINTER_TRAITS_HPP_
#include <memory>
template <typename Ptr>
struct extra_pointer_traits;
template <typename T>
struct extra_pointer_traits<T*>
{
using ptr_type = T*;
using element_type = T;
static ptr_type make(size_t count) { return new T[count]; }
static ptr_type make() { return new T; }
};
template <typename T>
struct extra_pointer_traits<T[]>
{
using ptr_type = T[];
using element_type = T;
static T* make(size_t count) { return new T[count]; }
static T* make() { return new T; }
};
template <typename T, class Deleter>
struct extra_pointer_traits<std::unique_ptr<T[], Deleter>>
{
using ptr_type = std::unique_ptr<T[], Deleter>;
using element_type = T;
static T* release(ptr_type& ptr) { return ptr.release(); }
static std::unique_ptr<T[], Deleter> make(size_t count)
{
return std::make_unique<T[]>(count);
}
};
template <typename T, class Deleter>
struct extra_pointer_traits<std::unique_ptr<T, Deleter>>
{
using ptr_type = std::unique_ptr<T, Deleter>;
using element_type = T;
static T* release(ptr_type& ptr) { return ptr.release(); }
static std::unique_ptr<T, Deleter> make()
{
return std::make_unique<T>();
}
};
template <typename T>
struct extra_pointer_traits<std::shared_ptr<T>>
{
using ptr_type = std::shared_ptr<T>;
using element_type = typename std::pointer_traits<ptr_type>::element_type;
// No release()
static std::shared_ptr<element_type[]> make(size_t count)
{
return std::make_shared<element_type[]>(count);
}
static std::shared_ptr<element_type> make()
{
return std::make_shared<element_type>();
}
};
#endif // EXTRA_POINTER_TRAITS_HPP_
</code></pre>
<p>I'm considering suggesting something like this as an <em>addition</em> to the existing traits class the standards committe, but for now I've implemented it as a separate class.</p>
<p><strong>Note:</strong> To clarify - these are not all possible template specializations for pointer-like classes in the standard library, there would be a few more.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T08:55:53.533",
"Id": "385960",
"Score": "0",
"body": "I tried to suggest an idea to the committee but faced quite a lot of questions I didn't think of. They're also busy with all of those concepts, contracts, modules, executors, etc... | [
{
"body": "<p>First, <code>size_t</code> should be <code>std::size_t</code> everywhere.</p>\n\n<p>Why don't the raw pointer/array cases have <code>release()</code>? Granted, it won't really change any ownership in reality, but it could conceptually.</p>\n\n<pre><code>static ptr_type make(size_t count) { return ... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-27T23:12:44.483",
"Id": "200449",
"Score": "3",
"Tags": [
"c++",
"pointers",
"c++17"
],
"Title": "A traits class for (compound) pointers - beyond what std::pointer_traits offers"
} | 200449 |
<p>I have Products table which looks like this:</p>
<p><a href="https://i.stack.imgur.com/zJrGy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zJrGy.jpg" alt="enter image description here"></a></p>
<p>I have some data in this table and I want to filter it depending on this columns (Filtering with columns type of string isn't problem). For this I have the code (in ASP.NET Core Web API Project) shown below. I know it's not a good approach. I have another table which has more foreign keys, so it will be more difficult to do this kind of work on it.</p>
<p>In SearchProduct action method I am getting the product object, which properties have specific values. For example, If <code>Name="Box"</code>, then I want to get products from the product list, which Name is "Box" too.</p>
<p>The consumer of this service is WPF application, where I have the window, where the controls (textboxes and comboboxes{ for productType and ProductUnit}) are placed and the user will be able to search data with any criteria. For example, if he wants to search only with Name, he will write something only in Name textbox. If he wants to search product which name is "Box" and also the productType is "A", then he will write "Box" in name textbox and will choose A type in comboBox.</p>
<p>P.S When product is added in this table, if user doesn't write anything in the Name textbox for example, the value of Name will be "" and not null.</p>
<pre><code> [HttpPost("SearchProduct")]
public IEnumerable<Product> SearchProduct([FromBody]Product product)
{
IEnumerable<Product> data;
if(product.ProductTypeID != null && product.ProductUnitID != null)
{
data = _context.Products.Where(x =>
x.Name.Contains(product.Name) &&
x.Code.Contains(product.Code) &&
x.Barcode.Contains(product.Barcode) &&
x.InnerCode.Contains(product.InnerCode) &&
(x.ProductTypeID == product.ProductTypeID &&
x.ProductUnitID == product.ProductUnitID))
.Include(x => x.ProductType)
.Include(x => x.ProductUnit);
}
else if(product.ProductTypeID == null && product.ProductUnitID == null)
{
data = _context.Products.Where(x =>
x.Name.Contains(product.Name) &&
x.Code.Contains(product.Code) &&
x.Barcode.Contains(product.Barcode) &&
x.InnerCode.Contains(product.InnerCode) ||
(x.ProductTypeID == product.ProductTypeID &&
x.ProductUnitID == product.ProductUnitID))
.Include(x => x.ProductType)
.Include(x => x.ProductUnit);
}
else if(product.ProductTypeID != null)
{
data = _context.Products.Where(x =>
x.Name.Contains(product.Name) &&
x.Code.Contains(product.Code) &&
x.Barcode.Contains(product.Barcode) &&
x.InnerCode.Contains(product.InnerCode) &&
x.ProductTypeID == product.ProductTypeID)
.Include(x => x.ProductType)
.Include(x => x.ProductUnit);
}
else
{
data = _context.Products.Where(x =>
x.Name.Contains(product.Name) &&
x.Code.Contains(product.Code) &&
x.Barcode.Contains(product.Barcode) &&
x.InnerCode.Contains(product.InnerCode) &&
x.ProductUnitID == product.ProductUnitID)
.Include(x => x.ProductType)
.Include(x => x.ProductUnit);
}
return data;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T06:26:46.183",
"Id": "385939",
"Score": "0",
"body": "One more thing... this is you actual code, isn't? It's a bit strange that you don't have something like `.ToList()` anywhere. The context should already be disposed when the quer... | [
{
"body": "<p>You should maybe reconsider the fields in the data table. You should restrict nullable fields to a minimum. A product without a name or ProductTypeId?</p>\n\n<hr>\n\n<p>As for the queries, you could simplify it to not repeat code like:</p>\n\n<pre><code>public List<Product> SearchProduct([Fr... | {
"AcceptedAnswerId": "200585",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T04:18:31.307",
"Id": "200458",
"Score": "5",
"Tags": [
"c#",
"database",
"wpf",
"asp.net-core"
],
"Title": "Filter Producs by any property"
} | 200458 |
<p>I have a method that generates the S3 key prefix according to the provided args. However, my gut feeling is that this method is not as elegant as it should be, maybe I just don't have an eye for it. Care to instruct me on how to make this little bit less sketchy? </p>
<pre><code>private String generateFullQualifiedS3KeyPrefix(DataStream dataStream, Options options) {
String environmentName, applicationName, streamName = applicationName = environmentName = null;
if (dataStream != null) {
environmentName = dataStream.getEnvironmentName();
applicationName = dataStream.getApplicationName();
streamName = dataStream.getStreamName();
}
String year, month, date, groupById = date = month = year = null;
if (options != null) {
year = String.valueOf(options.getYear());
month = String.format("%02d", options.getMonth());
date = String.format("%02d", options.getDate());
groupById = options.getGroupById();
}
String[] arr = new String[]{environmentName, applicationName, streamName, groupById, year, month, date};
StringJoiner filePath = new StringJoiner("/");
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) {
break;
}
filePath.add(arr[i]);
}
return filePath.toString() + "/";
}
</code></pre>
| [] | [
{
"body": "<p>The local variables make this very verbose:\neach variable is declared, initialized, re-assigned, and referenced.\n(They each appear 3-4 times in the code.)\nYou could instead accumulate values in a list.</p>\n\n<p>Creating an array that may contain <code>null</code> values,\nthen filtering out th... | {
"AcceptedAnswerId": "200485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T07:13:52.227",
"Id": "200464",
"Score": "2",
"Tags": [
"java",
"spring",
"amazon-web-services"
],
"Title": "More elegant way to construct the S3 path name with given options"
} | 200464 |
<p>There is a question in a contest but it doesn't have any answer. I solve it but I get time limit for most of test case. Is it possible to improve my code or give a better approach?</p>
<h2>Question</h2>
<p>There is a directed graph with vertices \$1,...,n\$ and each vertex has a label which is \$a_i\$ (a number not character). we start walk and write label for each vertex we see in path (we can use vertices and edges more than one time) for example if we start from vertex \$v\$ and go to vertex \$u\$ then string of path is \$a_va_u\$. (if \$a_v=23\$ and \$a_u=456\$ then string of path is \$23456\$) we want to find strings of length \$k\$ and between different way of find that, choose one that produce maximum string of path (larger number) and print it. </p>
<h2>Input</h2>
<p>In the first line numbers n,m,k are given denoting the number of vertices, edges and length of string path that we want.
Next line contains n integers one after another, i-th integer is equal to \$a_i\$. (the number written on vertex i)
Afterwards m lines each consisting of two integers u, v are given showing edge \$u \rightarrow v\$ exists in the graph.<br>
\$1 \le v, u \le n\$<br>
\$n, m, k \le 1000\$<br>
\$1 \le a_i \le 100000\$<br>
the graph can contain loop or multiple edges.</p>
<h2>Output</h2>
<p>In the only line of output display the k digit number that is maximized.
Display −1 if no answer exists!</p>
<h2>Sample input</h2>
<p>5 4 3<br>
4 12 3 1 1<br>
1 2<br>
2 3<br>
1 4<br>
4 5 </p>
<h2>Sample output</h2>
<p>412</p>
<h2>My Solution</h2>
<p>In my solution because we can traverse each edges and vertices more than one time, so I don't use something like visited array. I use deep first search to traverse all vertices and because we solve some problems more than one time, I use dynamic programming approach (to-down with memoization) to solve it faster however I get time limit. I Think my solution is right and I have time problem but maybe you find some implementation problem. (I hope that is true)</p>
<pre><code>#include <iostream>
#include <vector>
using namespace std;
int *value;
int *size;
int **valueC;
vector<int> *edges;
int k;
int length(int n);
int concat(const int &n1, const int &n2);
int dfs(int i, int reminder);
int length(int n) {
int s = 0;
do {
n /= 10;
s++;
} while (n > 0);
return s;
}
int concat(const int &n1, const int &n2) {
int times = 1;
while (times <= n2)
times *= 10;
return n1 * times + n2;
}
int dfs(int i, int reminder) {
if (valueC[i][reminder] != -1)
return valueC[i][reminder];
int q = -1;
for (int j : edges[i]) {
int temp = -2;
if (reminder - size[j] == 0)
temp = value[j];
else if (reminder - size[j] > 0)
temp = dfs(j, reminder - size[j]);
if (temp > q)
q = temp;
}
if (q == -1)
valueC[i][reminder] = -2;
else
valueC[i][reminder] = concat(value[i], q);
return valueC[i][reminder];
}
int main() {
int n, m;
cin >> n >> m >> k;
if (k == 0) {
cout << -1;
return 0;
}
value = new int[n];
size = new int[n];
valueC = new int *[n];
for (int i = 0; i < n; ++i) {
valueC[i] = new int[k];
for (int j = 0; j < k; ++j) {
valueC[i][j] = -1;
}
}
for (int i = 0; i < n; ++i) {
cin >> value[i];
size[i] = length(value[i]);
}
edges = new vector<int>[n];
for (int j = 0; j < m; ++j) {
int s, e;
cin >> s >> e;
s--;
e--;
edges[s].push_back(e);
}
int maximum = 0;
for (int i = 0; i < n; ++i) {
int temp = dfs(i, k - size[i]);
if (temp > maximum)
maximum = temp;
}
if (maximum != 0)
cout << maximum;
else
cout << -1;
return 0;
}
</code></pre>
<h2>Update 1</h2>
<p>I remove one more space that is used as mentioned. about edges I use <code>vector<int>[n]</code> because I have <code>n</code> vertices and for each vertex I use a <code>vector<int></code> to know that is connected to which vertices. about <code>concat</code> and <code>length</code>, I use int and I don't worry because the restriction on the question say that my numbers are at most 100000 and that is enough and both function work without overflow. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T17:37:33.533",
"Id": "386024",
"Score": "0",
"body": "I'm sorry. I fix it. first I use bfs name for my function but I change it because dfs name is true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-2... | [
{
"body": "<p>Your code is fairly readable, which is good. I see a few things that could be improved, though.</p>\n<h1>Bugs</h1>\n<p>In <code>main()</code> you are allocating <code>n + 1</code> elements and then iterating from 1 to <code>n</code>. C-based languages use 0-based arrays, so always allocating 1 ext... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T09:48:32.330",
"Id": "200467",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"graph"
],
"Title": "Finding intersting path in a graph"
} | 200467 |
<p>To get points which lie on the border of a rectangle, I use 4 <code>for</code> loops. At first I thought about creating <code>Rectangle</code> and using <code>PathItterator</code>, but it confused me very much. Is there a better way than mine?</p>
<pre><code>int r = 5;
int x = 0;
int y = 0;
int length = r * 2 + 1;
for (int i = 0; i < length; i++) {
System.out.print(String.format("(%d,%d) ", x - r + i, y - r));
}
System.out.println();
for (int i = 0; i < length; i++) {
System.out.print(String.format("(%d,%d) ", x - r + i, y + r));
} System.out.println();
for (int i = 0; i < length; i++) {
System.out.print(String.format("(%d,%d) ", x - r , y - r+i));
} System.out.println();
for (int i = 0; i < length; i++) {
System.out.print(String.format("(%d,%d) ", x + r , y - r+i));
}
System.out.println();
</code></pre>
| [] | [
{
"body": "<p>Most rectangles have a length and a width. I’ve never heard of a rectangle with a radius, but it would be known as a square.</p>\n\n<p>More constructively:</p>\n\n<pre><code>System.out.print(String.format(\"(%d,%d) \", x - r + i, y - r));\n</code></pre>\n\n<p>Could be written as:</p>\n\n<pre><cod... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T11:02:53.973",
"Id": "200471",
"Score": "0",
"Tags": [
"java"
],
"Title": "Getting point on a rectangle border"
} | 200471 |
<p>I'm a beginner to Haskell (intermediate in web-dev stuff and JavaScript) and I'm not really sure what I could do <a href="https://www.cis.upenn.edu/%7Ecis194/spring13/hw/01-intro.pdf" rel="nofollow noreferrer">better for Homework 1 of CIS194 that I'm taking online</a>.</p>
<p>The problem statement is as follows (shortened):</p>
<blockquote>
<p>Validate a credit card number by the following steps:</p>
<ol>
<li>Double the value of every second digit from the right</li>
<li>Take the sum of the digits of the new values</li>
<li>Check whether the sum modulo 10 is 0.</li>
</ol>
<p>Write the functions <code>toDigits</code>, <code>toDigitsRev</code> and <code>doubleEveryOther</code> for the first task, <code>sumDigits</code> for the second, and <code>validate</code> for the third.</p>
</blockquote>
<pre><code>toDigits :: Integer -> [Integer]
toDigits x
| x <= 0 = []
| divBy10 < 10 = [divBy10, remainder]
| otherwise = toDigits divBy10 ++ [remainder]
where remainder = x `mod` 10
divBy10 = x `div` 10
toDigitsRev :: Integer -> [Integer]
toDigitsRev x = reverse (toDigits x)
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther xs = reverse $ doubleEveryOther' (reverse xs)
where doubleEveryOther' [] = []
doubleEveryOther' (x:[]) = [x]
doubleEveryOther' (x:y:[]) = [x, y*2]
doubleEveryOther' (x:y:xs) = [x, y*2] ++ doubleEveryOther' xs
sumDigits :: [Integer] -> Integer
sumDigits xs = sum $ map sum $ map toDigits xs
validate :: Integer -> Bool
validate x = ((sumDigits (doubleEveryOther (toDigits x))) `mod` 10) == 0
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T12:04:56.003",
"Id": "385967",
"Score": "0",
"body": "What is your main concern?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T12:05:11.213",
"Id": "385968",
"Score": "0",
"body": "Welco... | [
{
"body": "<p>First of all, it's great that you've used type signatures. So let's have a look at the contents of your functions.</p>\n\n<h1>Use <code>divMod</code> instead of <code>div</code> and <code>mod</code></h1>\n\n<p>In <code>toDigits</code>, you both <code>div</code> and <code>mod</code> <code>x</code> ... | {
"AcceptedAnswerId": "200478",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T11:08:42.753",
"Id": "200472",
"Score": "6",
"Tags": [
"beginner",
"haskell",
"checksum"
],
"Title": "Simple Credit card validation"
} | 200472 |
<p>Inspired by <a href="https://youtu.be/JfmTagWcqoE?t=1467" rel="nofollow noreferrer">the talk of Herb Sutter in CppCon2016</a>, I decided to make a doubly linked list using templates, smart pointers, and raw pointers (for back-pointers, having a cycle of <code>std::unique_ptr</code>s would be a bug).</p>
<p>The following proof-of-concept implementation compiles and works properly.<br>
I would love to hear your suggestions / improvements about the entire header and your design approach.</p>
<p>Below you can find the header and a small test main.</p>
<p><strong>LinkedList.h</strong></p>
<pre><code>#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <memory>
#include <initializer_list>
namespace DLL {
template <typename T> class LinkedList{
private:
struct ListNode{
std::unique_ptr<ListNode> next; //2 uniq_ptr can't point to one another.
ListNode* prev = nullptr; //weakptr needs to be cast back to a shared_ptr to check its state.
T data{}; //Initialize empty;
ListNode(const T& element){
this->data = element;
}
};
public:
std::unique_ptr<ListNode> head;
ListNode* tail = nullptr;
LinkedList(){}
~LinkedList(){}
void append(const T& element){
ListNode* curr = nullptr;
if (head.get() == nullptr){ //If list is empty.
head = std::make_unique<ListNode>(element);
}
else if(head.get() -> next.get() == nullptr){ //If list has one element.
head.get() -> next = std::make_unique<ListNode>(element);
curr = head.get() -> next.get(); //Sets raw pointer to the first element.
curr -> prev = head.get();
tail = curr;
}
else{
tail -> next = std::make_unique<ListNode>(element);
curr = tail -> next.get(); //Sets raw pointer to the last element.
curr -> prev = tail;
tail = curr;// The new last element is the tail.
}
}
int remove(const T& element){
ListNode* curr = nullptr;
if (head.get() == nullptr){ //If list is empty.
return -1; //Error: Can't remove from empty list.
}
//List has one or more elements.
curr = head.get();
while(curr != nullptr){
if(curr -> data == element){ //Found element.
if(curr -> prev == nullptr){ //it's head
head = std::move(curr -> next); //Head now points to the next element.
if (head) {
head->prev = nullptr;
}
//New head's previous element points to nothing, making it a true head element.
}
else if(curr -> next.get() == nullptr){ //it's tail.
tail = curr -> prev; //Reference the previous element.
tail -> next.reset(); //Destroy the old tail element.
if(head.get() == tail){
tail = nullptr; //tail and head should not be the same.
} //List contains one element.
}
else{//it's intermediate.
//The next node should point to the previous one
curr -> next -> prev = curr -> prev;
curr -> prev -> next = std::move(curr -> next);
//The prev node now points to the next one of current.
}
return 1; //Element found in list.
}
curr = curr -> next.get(); //Traverse the next element.
}
return 0; //Element not found in list.
}
void print() {
ListNode* curr = head.get(); //Start from the start of the list.
std::cout << "[ ";
while (curr != nullptr) {
std::cout << curr -> data << " ";
curr = curr -> next.get();
}
std::cout << "]" << std::endl;
}
};
}
#endif
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "LinkedList.h"
int main() { //Temporary Test Main will be split from the implementation file in the future
DLL::LinkedList <int> list; //Create an empty list
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
list.print();
list.remove(5);
list.print();
list.remove(1);
list.print();
list.remove(3);
list.print();
list.remove(2);
list.print();
list.remove(4);
list.print();
return 0;
}
</code></pre>
<p>I compiled with g++: <code>g++ -std=c++14 main.cpp -o out</code> and with the <code>VS2015</code> compiler.<br>
The C++14 flag is needed for the <code>std::make_unique</code> call.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T13:59:21.747",
"Id": "385990",
"Score": "0",
"body": "you'll want to ask a follow up question to make sure you're not invalidating any answers that have been posted already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creat... | [
{
"body": "<p>Well, there's a reason I wouldn't ever use a smart-pointer which isn't a shared-pointer or self-relative as base for a doubly-linked-list:</p>\n\n<p>Most of the time, one has to work around the smart-pointer to get things done efficiently, or with the right semantics at all. Some examples from you... | {
"AcceptedAnswerId": "200484",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T12:02:52.427",
"Id": "200477",
"Score": "5",
"Tags": [
"c++",
"linked-list",
"c++14",
"template",
"pointers"
],
"Title": "Doubly linked list std::unique_ptr template class implementation"
} | 200477 |
<p>I wanted to create a simple function that can read and return the HTML content from a specified URL. This is what reading here and there lead me to:</p>
<pre><code>from socket import timeout
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
def get_html_content(url, max_attempt = 3):
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
content = ""
attempt = 1
while True:
try:
html_page = urlopen(req, timeout=10)
content = html_page.read()
except (HTTPError, URLError, timeout) as e:
if isinstance(e, HTTPError):
print("The server couldn\'t fulfill the request....attempt %d/%d" % (attempt, max_attempt))
print('Error code: ', e.code)
if isinstance(e, URLError):
print("We failed to reach a server....attempt %d/%d" % (attempt, max_attempt))
print('Reason: ', e.reason)
if isinstance(e, timeout):
print('timeout...attempt %d/%d' % (attempt, max_attempt))
attempt += 1
if attempt > max_attempt:
break
continue
else:
break
return content
</code></pre>
<p>I would use this function to parse the content of many URLs. For <code>if content = ""</code>, I would raise a random exception after writing to some file whatever I had already successfully gathered.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T19:24:10.767",
"Id": "386044",
"Score": "2",
"body": "you may want to consider using [requests](http://docs.python-requests.org/en/master/), possibly with an extension to account for the multiple attempts, or just iterating as you d... | [
{
"body": "<p>There are a couple of minor technical issues:</p>\n\n<ul>\n<li><p>The <code>content</code> variable is unnecessary, because you can simply return <code>html_page.read()</code> directly. (And you could as well return <code>urlopen(req, timeout=10).read()</code> directly...) When the max attempts ar... | {
"AcceptedAnswerId": "200483",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T13:25:45.473",
"Id": "200481",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"http"
],
"Title": "Reading and returning the HTML content from a specified URL"
} | 200481 |
<p>As a part of a challenge, I was asked to write a function to determine if there was repetition in a string (if no repetition, output is 1), and if a substring is repeated throughout the string (for example if the string is "abcabc," "abc" is repeated twice 2, if the string is "bcabcabc," the repetition is 0 since we start from the first string (no leftovers)).</p>
<p>My code works and I have submitted it to the challenge, but I am curious if there are ways to improve this code:</p>
<pre><code>def answer(s):
length = (len(s))
range_list = (range(1, len(s)+1))
list_char = list(s)
divisors = []
divisors = [x for x in range_list if (length)% (x) == 0]
max_pieces = []
for i in range (len(divisors)):
size = divisors[i]
split = [list_char[i:i+size] for i in range(0, length, size)]
if(all(x == split[0] for x in split)):
max_pieces = int(length/size)
break
return max_pieces
</code></pre>
| [] | [
{
"body": "<pre><code> length = (len(s))\n</code></pre>\n\n<p>Unnecessary ( )’s.</p>\n\n<pre><code> range_list = (range(1, len(s)+1))\n</code></pre>\n\n<p>Again, unnecessary ( )’s. Does not actually create a list, just a <code>range</code> object, so a better name is in order. And you can remove this entire ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T15:32:27.930",
"Id": "200489",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Use Python to determine the repeating pattern in a string (no leftovers)"
} | 200489 |
<p>I'm looking for the most simple and efficient way to track the number of string elements in a container.</p>
<p>I'm currently using <code>std::vector</code> but I wonder if there's a better container which is more suitable for my purpose.</p>
<p><strong>My Code :</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
class Table
{
public:
void insert(const std::string &name)
{
data.push_back(name);
}
void remove(const std::string &name)
{
auto it = std::find(data.begin(), data.end(), name);
if (it != data.end())
data.erase(it);
}
/* get the number of occurrences */
int count(const std::string &name)
{
auto num = std::count(data.begin(), data.end(), name);
return static_cast<int>(num);
}
private:
std::vector<std::string> data;
};
int main(int argc, const char * argv[])
{
Table table;
table.insert("Apple");
table.insert("Apple");
table.insert("Orange");
table.insert("Orange");
table.remove("Orange");
std::cout << "Number of Apples : " << table.count("Apple") << std::endl;
std::cout << "Number of Oranges : " << table.count("Orange") << std::endl;
std::cout << "Number of Lemons : " << table.count("Lemon") << std::endl;
return 0;
}
</code></pre>
<p><strong>The Result :</strong></p>
<pre><code>Number of Apples : 2
Number of Oranges : 1
Number of Lemons : 0
Program ended with exit code: 0
</code></pre>
<p>Is there a way to improve the class <code>Table</code> so my program can be more efficient? </p>
<p>And would you recommend a different container than <code>std::vector</code> for the class <code>Table</code>? </p>
<p>P.S: Usually, from 50 to 500 strings will be stored to a container in my program.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T18:39:58.653",
"Id": "386037",
"Score": "1",
"body": "I rolled back to the first version. Please do not edit after receiving an answer, as it invalidates existing ones. Post a follow-up instead if you want review of a new version."
... | [
{
"body": "<p>Of course there is lots to improve:</p>\n\n<ol>\n<li><p>Always ask the compiler. <a href=\"http://coliru.stacked-crooked.com/a/0eb8716b375f3a85\" rel=\"noreferrer\">A reasonably-high warning-level helps.</a>.</p></li>\n<li><p>You need to <code>#include <algorithm></code> for <code>std::find(... | {
"AcceptedAnswerId": "200496",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T15:38:20.627",
"Id": "200490",
"Score": "7",
"Tags": [
"c++",
"algorithm"
],
"Title": "Better container for tracking number of string elements?"
} | 200490 |
<p>I wrote this code because I was often annoyed that I couldn't get the parent object. This class allows you to traverse the parent-child relationship between objects, in both directions. It also preserves prototypes.</p>
<p>For example:</p>
<pre><code>let myTree = new Tree({a:{b:{k:2}}});
myTree.a.b; // { k: 2 }
myTree.a === myTree.a.b.__parent__; // true
</code></pre>
<p>It also enables you to add more properties:</p>
<pre><code>myTree.c = {d:{l:5}}; // {d: {l: 5}}
myTree.c.__parent__ === myTree; // true
</code></pre>
<p>You can also move a branch:</p>
<pre><code>myTree.a.b.__parent__ = myTree.c; // {d: {l: 5}}
myTree.c.b.k; // 2
myTree.a.b; // undefined
</code></pre>
<p>You can even move it to another tree:</p>
<pre><code>let anotherTree = new Tree({});
myTree.a.l = 3;
myTree.a.l; // 3
myTree.a.__parent__ = anotherTree;
anotherTree.a; // {l: 3}
myTree.a; // undefined
anotherTree.a.__parent__ === anotherTree; // true
</code></pre>
<p>Now, you may be wondering, how do you get a human readable and console-friendly version of this tree?</p>
<pre><code>myTree.__raw__();
</code></pre>
<p>Note: only properties that are objects are able to give you the parent object.</p>
<p>My code:</p>
<pre><code>const Tree = (function(){
const TARGET = Symbol('__target__'),
HANDLER = Symbol('__handler__'),
PROXY = Symbol('__proxy__'),
{ assign, defineProperty, entries, setPrototypeOf } = Object,
convert=( obj )=>{
let res = new Branch(obj);
entries(obj).forEach(([key, value], _) => {
if( ({}).hasOwnProperty.call(obj, key) ) {
if(typeof value === 'object') {
res[key] = convert(value);
defineProperty(res[key], '__parent__', {
value: res[PROXY],
configurable: false,
writable: true
});
} else {
res[key] = value.constructor(value);
}
}
});
return res;
},
getKey = (obj, val) => {
return entries(obj).filter(([key, value], _) => { return value[TARGET] === val; })[0][0];
};
let genHandler = (_target) => {
return (function(){
let res = {
set: (target, prop, value) => {
if( ['__parent__'].includes(prop) ) {
if( typeof value === 'object' && (value.__istree__ || value.__isbranch__) && value !== target.__parent__) {
const key = getKey(target.__parent__, target);
if(target.__parent__[key]) {
delete target.__parent__[key];
}
value[key] = target;
return value;
} else {
throw TypeError('Cannot assign __parent__ to a non-tree value');
}
}
if(typeof value === 'object') {
value = convert(value);
defineProperty(value, '__parent__', {
value: target[PROXY],
configurable: false,
writable: true
});
}
target[prop] = value;
return value;
},
setProxy: (val) => {
res.proxy = val;
},
get: (target, prop) => {
if( prop === '__raw__' ) {
return __raw__.bind(target);
}
if( prop === TARGET ) {
return _target;
}
if( prop === HANDLER ) {
return res;
}
if( prop === PROXY ) {
return res.proxy;
}
return target[prop];
}
};
return res;
})()
};
/**
* Get the raw value of the tree, without all that proxy stuff.
* @returns {Object} The raw object. Please not that objects will not be the same instances.
* @memberof Tree#
*/
function __raw__() {
let res = setPrototypeOf({}, this.__proto__);
entries(this).forEach( ([key, value], _) => {
if( {}.hasOwnProperty.call(this, key )) {
if( typeof value === 'object') {
res[key] = __raw__(value[TARGET]);
} else {
res[key] = value;
}
}
});
return res;
}
/**
* A class that enables navigation from child properties to parent. WIP - currently figuring out how to make new properties.
* For all purposes this functions as intended, but it doesn't print well in the console. It even perserves prototypes.
* @property {(Branch|*)} * Properties.
* @property {(Tree|Branch)} __parent__ The parent element. This can be changed to move the object to another tree or branch.
*/
class Tree {
/**
* Constructs a new Tree instance.
* @constructs Tree
* @param {Object} obj The object to convert to a tree.
* @throws {TypeError} You probably passed it a primitive.
*/
constructor(obj) {
let conf = { __istree__: true },
res = new Proxy(setPrototypeOf(conf, obj.__proto__), genHandler(conf));
Object.defineProperty(res[HANDLER], 'proxy', {
value: res,
protected: true
});
if( typeof obj !== 'object') {
throw TypeError('Tree expects an object');
} else {
for( let key in obj) {
let value = obj[key];
if(typeof value === 'object') {
res[key] = convert(value);
defineProperty(res[key], '__parent__', {
value: res[PROXY],
configurable: false
writable: true,
});
} else {
res[key] = value.constructor(value);
};
};
};
return res;
}
}
class Branch {
constructor(obj) {
let conf = { __isbranch__: true },
res = new Proxy(setPrototypeOf(conf, obj.__proto__), genHandler(conf));
Object.defineProperty(res[HANDLER], 'proxy', {
value: res,
protected: true
});
return res;
}
}
return Tree;
})();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T01:38:13.340",
"Id": "387031",
"Score": "1",
"body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question... | [
{
"body": "<p>Looks like the examples you give don't work as intended.</p>\n\n<pre><code>> let myTree = new Tree({a:{b:{k:2}}});\nundefined\n> myTree.a.b; // { k: 2 }\nProxy [ { __isbranch__: true, k: 2 },\n { set: [Function: set],\n setProxy: [Function: setProxy],\n get: [F... | {
"AcceptedAnswerId": "200942",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-28T19:15:11.983",
"Id": "200495",
"Score": "5",
"Tags": [
"javascript",
"object-oriented",
"tree",
"ecmascript-6"
],
"Title": "Traversing the parent-child relationship between objects"
} | 200495 |
<p>I solved the maze backtracking question using a stack however could not find any other solution like that anywhere (to validate my solution is actually a valid one).<br/>
The problem statement is as follows - <br/></p>
<blockquote>
<p>Imagine a robot sitting on the upper left corner of grid with r rows
and c columns. The robot can only move right or down but certain cells
are "off limit" such that the robot cannot step on them. design an
algorithm to find a path for the robot from the top left to the bottom
right</p>
</blockquote>
<p>My Solution (java) is as follows - </p>
<pre><code>public static boolean solve(boolean[][] maze) {
int maxY = maze.length-1;
int maxX = maze[0].length-1;
int[] end = new int[]{maxY, maxX};
int[] currentPosition = new int[]{0, 0};
Stack<int[]> lastPosition = new Stack<>();
lastPosition.push(currentPosition);
while ( (currentPosition[0] != end[0] || currentPosition[1] != end[1])
&& !lastPosition.isEmpty()) {
// get current position coordinates
int y = currentPosition[0];
int x = currentPosition[1];
// Try moving right
if(x+1 <= maxX && maze[y][x+1]) {
currentPosition = new int[]{y,x+1}; // Move one step right
lastPosition.push(currentPosition);
} else if(y+1 <= maxY && maze[y+1][x]) { // Try moving down
currentPosition = new int[]{y+1,x}; // Move one step down
lastPosition.push(currentPosition);
} else {
maze[y][x] = false; // Mark as dead end (so we will not try to reach here again)
currentPosition = lastPosition.pop();
}
}
return !lastPosition.isEmpty();
}
</code></pre>
<p>It looks like it works well (I tested it against several mazes to make sure), it should also run in O(rc) time at worst case (which is fine for the a maze of rc size) but everything else I've seen uses recursion or other methods to solve this problem. Am I missing something?</p>
<p>Will appreciate any kind of guidance.</p>
| [] | [
{
"body": "<p>Your solution looks correct. Your don't need to find a similar implementation to validate yours. You just need to verify yours works correctly, by stepping through the logic as if with a debugger, and verifying all execution paths, and considering all possible corner cases. </p>\n\n<p>By the way, ... | {
"AcceptedAnswerId": "200515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T00:24:10.883",
"Id": "200503",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"interview-questions",
"dynamic-programming"
],
"Title": "Solving maze problem with backtracking solution using stack"
} | 200503 |
<p>I am participating in a challenge and one of the challenges was to write a script to sort a list of software versions (ex: 1.0, 1.3.2, 12, 1.3.0). Here is the my solution:</p>
<pre><code>def answer(l):
return sorted(l, key=lambda s: [int(i) for i in s.split('.')])
print(answer(eval(raw_input())))
</code></pre>
<p>In this code, I am essentially taking the list, and splitting each element by '.', converting them to integers, and then sorting the list. One thought is to use list comprehension to remove lambda altogether, but unsure how to achieve it. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T12:21:07.777",
"Id": "386097",
"Score": "0",
"body": "What does _\"no modules\"_ mean? You want to avoid any `import`s or are modules from the standard library fine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate"... | [
{
"body": "<p>The best way would be to use the <a href=\"https://github.com/python/cpython/blob/master/Lib/distutils/version.py#L93\" rel=\"nofollow noreferrer\"><code>distutils.StrictVersion</code></a> as your sort <code>key</code> argument.</p>\n\n<p>However, as you do not want to use <code>import</code>s, yo... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T00:37:58.093",
"Id": "200504",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"python-2.x",
"sorting"
],
"Title": "Sorting software version list using Python 2.7 (no modules)"
} | 200504 |
<p>In my game you can earn either a bronze, silver or gold medal. There is 4 difficulties which you can earn a medal on.</p>
<p>I want to display a medal depending on the lowest common medal earnt if that makes sense. </p>
<p>So if the user has bronze in 3 and gold in the other, it will display bronze.</p>
<p>Gold in 3 of them but no medal in 1. it wont display anything.</p>
<p>2 silver and 2 gold will display silver.</p>
<pre><code> int easyMedal = PlayerPrefs.GetInt("EasyModeMedal");
int mediumMedal = PlayerPrefs.GetInt("MediumModeMedal");
int hardMedal = PlayerPrefs.GetInt("HardModeMedal");
int insaneMedal = PlayerPrefs.GetInt("InsaneModeMedal");
if (easyMedal != 0 && mediumMedal != 0 && hardMedal != 0 && insaneMedal !=0)
{
enduranceMedal.SetActive(true);
Image enduranceImage = enduranceMedal.GetComponent<Image>();
if (easyMedal == 1)
{
enduranceImage.sprite = bronzeSprite;
} else if (easyMedal == 2)
{
if (mediumMedal < 2 || hardMedal < 2 || insaneMedal < 2)
{
enduranceImage.sprite = bronzeSprite;
} else {
enduranceImage.sprite = silverSprite;
}
} else
{
if (mediumMedal < 3 || hardMedal < 3 || insaneMedal < 3)
{
if (mediumMedal == 1 || hardMedal == 1 || insaneMedal == 1)
{
enduranceImage.sprite = bronzeSprite;
} else
{
enduranceImage.sprite = silverSprite;
}
}
else
{
enduranceImage.sprite = goldSprite;
}
}
}
</code></pre>
<p>So the first 4 variables get each difficulties medal. 0 = no medal, 1 = bronze, 2 = silver and 3 = gold.</p>
<p>I then have a long and confusing if-statement to determine what medal should be shown. I'm sure there must be a way to clean this up.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T08:55:42.120",
"Id": "386081",
"Score": "2",
"body": "`Math.Min()` does that. Fictional: `Min(a, Min(b, Min(c, d)))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T09:48:42.390",
"Id": "386083",
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T06:45:58.880",
"Id": "200509",
"Score": "7",
"Tags": [
"c#",
"cyclomatic-complexity"
],
"Title": "Set an image sprite depending on the lowest common number in a set"
} | 200509 |
<p>I have a method that is responsible for receiving an object and perform the information saved with Entity Framwork, using the Repository pattern. The issue is that this object is, basically, a DTO. The information contained in this object must be assigned to the models managed by the data layer, which is a bit confusing to me with respect to the way of making said assignments, considering that there are conditions for some of them.</p>
<pre><code>public int RegisterParticipant(ParticipantDTO participant)
{
try
{
EventoParticipante participante = new EventoParticipante();
if(participant.Token != null)
{
var result = RegistrarPagoEnLinea(participant);
participante.PagoEnLinea = true;
}
else
{
participante.PagoEnLinea = false;
participante.TransaccionFecha = DateTime.Now;
participante.TransaccionCodigo = participant.PaymentRefNumber;
}
participante.PersonaId = CreateNaturalPerson(participant).Id;
participante.InstitucionId = short.Parse(CreateInstitution(participant).ToString());
participante.EventoId = participant.EventId;
participante.TipoParticipanteId = _attendeeTypeRepository.SingleOrDefault(x => x.Nombre == participant.TypeParticipant).Id;
participante.MontoPago = decimal.Parse(participant.Ammount);
participante.Asistio = false;
participante.FechaRegistro = DateTime.Now;
participante.MontoPago = decimal.Parse(participant.Ammount) - 100;
_eventAttendeeRepository.Add(participante);
_eventAttendeeRepository.SaveChanges();
Evento eventParticipant = _eventRepository.Get(participant.EventId);
if (participant.CompanionName != null && !string.IsNullOrEmpty(participant.CompanionName))
{
Persona companion = new Persona();
companion.Nombres = participant.CompanionName;
companion.Apellidos = participant.CompanionLastName;
companion.NumeroDocumento = participant.CompanionIdentity;
companion.Ciudad = participant.AttendeeCity;
companion.Activo = true;
companion.UsuarioCreacion = "demo";
companion.UsuarioModificacion = "demo";
companion.FechaCreacion = DateTime.Now;
companion.FechaModificacion = DateTime.Now;
_personRepository.Add(companion);
_personRepository.SaveChanges();
EventoParticipante companionParticipant = new EventoParticipante();
companionParticipant.PersonaId = companion.Id;
companionParticipant.EventoParticipanteId = participante.Id;
companionParticipant.EventoId = participante.EventoId;
companionParticipant.MontoPago = decimal.Parse((100.00).ToString());
companionParticipant.TipoParticipanteId = 4;
companionParticipant.InstitucionId = participante.InstitucionId;
companionParticipant.Asistio = false;
companionParticipant.FechaRegistro = DateTime.Now;
_eventAttendeeRepository.Add(companionParticipant);
_eventAttendeeRepository.SaveChanges();
}
if (participant.InvoiceIdentity != null && !string.IsNullOrEmpty(participant.InvoiceIdentity))
{
CreateInvoice(participant, participante);
MailHelper.SendMail(MailAction.EventRegisterSuccessWithInvoice, eventParticipant, participant, _countryRepository.Get(participant.AttendeeCountryId).Nombre, _countryRepository.Get((int)participant.InvoiceCountryId).Nombre);
}
else
MailHelper.SendMail(MailAction.EventRegisterSuccess, eventParticipant, participant, _countryRepository.Get(participant.AttendeeCountryId).Nombre);
return 0;
}
catch (Exception e)
{
return 1;
}
}
</code></pre>
<p>As you can see, the method is excessively long. I understand that a method should be in charge of a specific function, so I know that it is wrong from that point.</p>
<p>To try to diminish its extension (and the possibility of errors in it) I have separated certain assignment tasks into methods within the same class, as in the case of <code>CreateNaturalPerson</code> (yes, the method was even longer). I thought to do the same with the IF where the values are assigned to <code>Persona</code> and <code>EventoParticipante</code>, but I think it would be to fall into the same. Is there any design pattern or advice for the above mentioned?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T12:07:08.480",
"Id": "386094",
"Score": "0",
"body": "You call `SaveChanges` twice. What happens if the first call succeeds and the second fails? Your db would be left in an invalid state. Also, using return codes is not a c# conven... | [
{
"body": "<p>This method does too much:</p>\n\n<ul>\n<li>creates <code>EventoParticipante</code></li>\n<li>creates <code>Persona</code> for the <code>companion</code> if necessary</li>\n<li>creates <code>EventoParticipante</code> for the <code>companion</code> if necessary</li>\n<li><code>CreateInvoice</code><... | {
"AcceptedAnswerId": "200583",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T06:46:06.357",
"Id": "200510",
"Score": "3",
"Tags": [
"c#",
".net",
"entity-framework",
"repository"
],
"Title": "Registering an event participant, using Entity Framework and several associated models"
} | 200510 |
<p>I'm looking for the most simple and efficient way to track the number of string elements in a container.</p>
<p>Previously, I used <a href="https://codereview.stackexchange.com/questions/200490/better-container-for-tracking-number-of-string-elements"><code>std::vector</code></a> but I tried changing the container to <code>std::unordered_map</code> since I hear that it can be easier and more performant for my use.</p>
<p><strong>My Code :</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <unordered_map>
class Table
{
public:
void insert(const std::string &name)
{
auto it = data.find(name);
if (it == data.end())
{
data[name] = 1;
return;
}
data[name]++;
}
void remove(const std::string &name)
{
auto it = data.find(name);
if (it == data.end())
return;
if (--data[name] == 0)
data.erase(it);
}
/* get the number of occurrences */
int count(const std::string &name)
{
auto it = data.find(name);
if (it == data.end())
return 0;
return data[name];
}
private:
std::unordered_map<std::string, int> data;
};
int main()
{
Table table;
table.insert("Apple");
table.insert("Apple");
table.insert("Orange");
table.insert("Orange");
table.remove("Orange");
std::cout << "Number of Apples : " << table.count("Apple") << std::endl;
std::cout << "Number of Oranges : " << table.count("Orange") << std::endl;
std::cout << "Number of Lemons : " << table.count("Lemon") << std::endl;
}
</code></pre>
<p><strong>The Result :</strong></p>
<pre><code>Number of Apples : 2
Number of Oranges : 1
Number of Lemons : 0
Program ended with exit code: 0
</code></pre>
<p>Is there a way to improve the class <code>Table</code> so my program can be more efficient than now? </p>
<p>The program seems to work but I used <code>std::unordered_map</code> for the first time so I'm not really sure if my implementation is correctly done.</p>
| [] | [
{
"body": "<pre><code>void insert(const std::string &name)\n{\n auto it = data.find(name);\n if (it == data.end())\n {\n data[name] = 1;\n return;\n }\n data[name]++;\n}\n</code></pre>\n\n<p>If it is available, you should prefer taking <code>std::string_view</code> parameters ov... | {
"AcceptedAnswerId": "200513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T07:05:26.883",
"Id": "200511",
"Score": "4",
"Tags": [
"c++",
"hash-map"
],
"Title": "Tracking the number of string elements using std::unordered_map"
} | 200511 |
<p>I made a text based board game that takes inspiration from DnD/Eldritch Horror (another board game)/Lovecraftian literature. Below you'll see a small excerpt that handles the bulk of the game processes, and there were several things I feel that could have been done better. </p>
<p>One thing I am not particularly proud of and want to find a better solution for, is this last minute feature I thought of that allows the players to change the "doom" or the turn counter in the game. Basically, they can pay resources to change the current doom count, which is changed in the game_handler method by adding the return value of from the process_turn method. Originally, the process_turn method had no such return value, and only returns one for the sake of being able to change the doom counter... I thought of using a global variable for the doom counter instead, but I thought global variables are for constants, which the doom count clearly is not.</p>
<p>Thanks in advance for the feedback, also if you want the game can be played on this quick webpage I put together: <a href="https://jsm209.github.io/Lugmere-s-Loss-Webpage/" rel="nofollow noreferrer">https://jsm209.github.io/Lugmere-s-Loss-Webpage/</a></p>
<pre><code># Pre: Given an integer that represents the current turn,
# Post: Will carry out single player games for each of the players, and produce a scoreboard of final scores at the end.
def game_handler(doom):
# Game setup
player_count = "-1"
while player_count.isdigit() is False:
player_count = input("How many people are playing Lugmere's Loss? ")
if player_count.isdigit() is False:
print("Please enter a number greater than 0.")
players_normal = []
for x in range(0, int(player_count)):
players_normal.append(Player())
i = 0
while i < len(players_normal):
players_normal[i].name = input("What is player " + str(i + 1) + "'s name? ") + " the " + n.generate_suffix()
i += 1
opening_story()
# Regular game play.
players_insane = []
while doom is not 0:
text_box("The doom counter sits at " + str(doom) + "...")
# Player has a normal condition
for player in players_normal:
if has_lost(player) is False:
doom += process_turn(player) # Player actions impact the doom counter.
press_enter()
player.update()
press_enter()
# Player has a disabled condition
elif player in players_insane:
print_slow(player.get_name() + " is currently insane. They try to snap out of it.")
if d.roll(20) >= 15:
print_slow(player.get_name() + " has sucessfully come to their senses!")
player.resources[4] = 50
players_insane.remove(player)
else:
print_slow(player.get_name() + " remains delusional...")
else:
# Checks to see if the player gains a disabled condition
if player.resources[4] == 0:
loss_by_sanity()
print_slow(player.get_name() + " has gone insane...")
players_insane.append(player)
else:
print_slow(player.get_name() + " has to spend a day repairing their broken airship.")
player.add([0, 0, 0, 2, 0, 0, 0])
doom -= 1
# The Maw (End game boss) encounters only players fit to encounter (does not have disabled condition)
for player in players_normal:
if has_lost(player) is False:
text_box(player.get_name() + " encounters The Maw.")
player.score += encounter_maw(player)
else:
text_box(player.get_name() + " is disabled and does not encounter The Maw.")
text_box("FINAL SCORES")
i = 0
while i < len(players_normal):
print_slow(players_normal[i].get_name() + "'s SCORE IS: " + str(players_normal[i].score))
i += 1
# Pre: Given a valid player object,
# Post: Processes one full turn for the player. After getting a course of action from the player, it performs it
# assuming the player has the resources to do so. If the action was not able to be performed (due to a lack of
# resources) it asks the player again for a different decision. It will return an integer based on the player's choices
# to be added to the doom counter.
def process_turn(player):
text_box(player.get_name() + ", you have: ")
print()
player.get_count()
print()
press_enter()
if player.resources[0] < 0:
print_slow(player.get_name() + " is in debt!")
print_slow()
print("How do you spend your day?")
choice = pick_choice(["Mine", "Dock [Costs 10 credits per crew member, including yourself]",
"Recruit [Costs 50 credits]", "Work", "Tamper [Costs 1 Wisdom, Minimum 5 Flux or 5 Crew]",
"Encounter [Minimum 1 Flux and 1 Crew]", "HELP"])
doom_mod = 0
if choice == 1:
player.mine(d)
elif choice == 2 and player.resources[0] >= 10*(player.resources[5]+1):
player.dock(d)
elif choice == 3 and player.resources[0] >= 50:
player.recruit(d)
elif choice == 4:
player.work(d)
elif choice == 5 and (player.resources[5] >= 5 or player.resources[2] >= 5) and player.resources[6] >= 1:
doom_mod += tamper(player, 2)
elif choice == 6 and player.resources[5] > 0 and player.resources[2] > 0:
player.resources[2] -= 1
encounter = exploration_encounters.get_random_encounter()
player.add(encounter.get_outcome())
elif choice == 7:
help()
process_turn(player)
else:
print_slow("You don't have the resources to do that. Please select another course of action.")
process_turn(player)
return doom_mod
# Pre: Given a list of strings that represent a choice the player can make,
# Post: Returns an integer representing the choice the player picked.
def pick_choice(choices):
for x in choices:
print(str(choices.index(x)+1) + ": " + x)
while True:
decision = None
try:
decision = int(input("ENTER 1-" + str(len(choices)) + ": "))
except ValueError or decision not in range(1, len(choices)+1):
print("That isn't an option.")
continue
if decision in range(1, len(choices)+1):
return decision
</code></pre>
| [] | [
{
"body": "<h3>Printing a menu of choices</h3>\n\n<p>This is a poor way to present a menu of choices, and it doesn't fully work:</p>\n\n<blockquote>\n<pre><code>def pick_choice(choices):\n for x in choices:\n print(str(choices.index(x)+1) + \": \" + x)\n while True:\n decision = None\n ... | {
"AcceptedAnswerId": "200522",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T07:27:10.840",
"Id": "200512",
"Score": "3",
"Tags": [
"python",
"game"
],
"Title": "Main processes for a text based board game"
} | 200512 |
<p>As you might know, Python's <code>tarfile</code> does not have the ability to append to the files that compressed with e.g. <code>gz</code> or <code>bz2</code>. I tried to implement this functionality which works fine but operates slowly. The following function accepts a string or bytes object and appends it as a file to an existing tarfile. I'm not sure if this code has the best performance, and it may have issues. I also tried writing files to memory instead of to a temporary directory, but this didn't impact performance.</p>
<pre><code>import os
import tarfile
import tempfile
import time
from pathlib import Path
def append_tar_file(buffer, file_name, output_path, replace=True):
"""
append a buffer to an existing tar file
"""
# extract files
# check for existing file and overwrite if need to
# compress files
if not os.path.isfile(output_path):
return
buffer = buffer.encode("utf-8") if isinstance(buffer, str) else buffer
with tempfile.TemporaryDirectory() as tempdir:
tempdirp = Path(tempdir)
with tarfile.open(output_path, "r:bz2") as tar:
try:
tar.extractall(os.path.abspath(tempdirp))
except Exception as err: #tar file is empty
print(err)
buffer_path = os.path.join(tempdir, os.path.basename(file_name))
if replace or (buffer_path not in list(os.path.abspath(f) for f in tempdirp.iterdir())):
with open(buffer_path, "wb") as f:
f.write(buffer)
with tarfile.open(output_path, "w:bz2") as tar:
for file in tempdirp.iterdir():
try:
tar.add(file, arcname=os.path.basename(os.path.normpath(file)))
except Exception as err:
print(err)
if __name__ == "__main__":
path = "./test.tar.gz"
buffer = "Test String"
filename = "somefile"
for i in range(1, 100):
print(time.time())
append_tar_file(buffer, filename+str(i), path)
</code></pre>
| [] | [
{
"body": "<p>Indeed, the <code>tarfile</code> package doesn't support appending to a compressed tar.\nBut I think you can do better than your current attempt.\nInstead of extracting the content to disk, you could keep it in memory, write and append to a new compressed file, and finally rename the compressed fi... | {
"AcceptedAnswerId": "200517",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T07:50:53.700",
"Id": "200514",
"Score": "8",
"Tags": [
"python",
"performance",
"compression"
],
"Title": "Append to compressed tar file with performance"
} | 200514 |
<p>I am learning c++ and read why we can't use realloc() in std::vector, but i think we can use realloc() for pods, so here is my attempt to write std::vector like class template specialized for PODs</p>
<pre><code>#include <malloc.h>
#include <stdexcept>
#include <type_traits>
namespace gupta {
namespace detail {
namespace podvector {
template <typename T> inline auto malloc(size_t elm_count) {
return ::malloc(elm_count * sizeof(T));
}
template <typename T> inline auto realloc(void *old_block, size_t elm_count) {
return ::realloc(old_block, elm_count * sizeof(T));
}
} // namespace podvector
} // namespace detail
template <typename PodType,
typename = std::enable_if_t<std::is_pod<PodType>::value>>
class podvector {
public:
using value_type = PodType;
using size_type = size_t;
using pointer = value_type *;
using const_value_pointer = const value_type *;
~podvector() {
if (m_memory)
free(m_memory);
}
podvector(size_type initial_size = 0) {
alloc(initial_size);
m_size = initial_size;
}
podvector(size_type initial_size, const value_type &value)
: podvector(initial_size) {
for (auto &v : *this)
v = value;
}
podvector(const podvector &other) : podvector(other.m_size) {
for (size_type i = 0; i < m_size; i++)
m_memory[i] = other.m_memory[i];
}
podvector(const podvector &&other)
: m_memory{std::move(other.m_memory)},
m_capacity{std::move(other.m_capacity)}, m_size{
std::move(other.m_size)} {
// other.m_memory = nullptr;
other.alloc(0);
}
podvector &operator=(const podvector &rhs) {
if (this != &rhs) {
resize(rhs.m_size);
for (size_type i = 0; i < rhs.m_size; i++)
m_memory[i] = rhs[i];
}
return *this;
}
podvector &operator=(podvector &&rhs) {
if (this != &rhs) {
this->~podvector();
m_memory = std::move(rhs.m_memory);
m_capacity = std::move(rhs.m_capacity);
m_size = std::move(rhs.m_size);
// rhs.m_memory = nullptr;
rhs.alloc(0);
}
return *this;
}
void resize(size_type new_size) {
if (new_size > m_size)
change_capacity(new_size);
m_size = new_size;
}
void reserve(size_type new_capacity) {
if (m_capacity < new_capacity)
change_capacity(new_capacity);
}
void push_back(const value_type &new_elm) {
if (m_size + 1 > m_capacity)
change_capacity(std::min(m_capacity * 2, 1));
m_memory[m_size++] = new_elm;
}
void pop_back() { m_size--; }
auto size() const { return m_size; }
auto capacity() const { return m_capacity; }
pointer begin() { return m_memory; }
const_value_pointer begin() const { return m_memory; }
pointer end() { return m_memory + m_size; }
const_value_pointer end() const { return m_memory + m_size; }
value_type &operator[](size_type pos) { return m_memory[pos]; }
const value_type &operator[](size_type pos) const { return m_memory[pos]; }
private:
pointer m_memory;
size_type m_size, m_capacity;
void alloc(size_type capacity) {
m_capacity = capacity;
m_size = 0;
m_memory =
static_cast<pointer>(detail::podvector::malloc<value_type>(capacity));
if (!m_memory)
throw std::bad_alloc{};
}
void change_capacity(size_type new_capacity) {
m_capacity = new_capacity;
void *new_memory =
detail::podvector::realloc<value_type>(m_memory, new_capacity);
if (!new_memory)
throw std::bad_alloc{};
m_memory = static_cast<pointer>(new_memory);
}
};
} // namespace gupta
</code></pre>
| [] | [
{
"body": "<ol>\n<li><code>malloc</code> and <code>realloc</code> live in <code>cstdlib</code>. <code>malloc.h</code> is not a standard header, neither in C++ nor in C, and should not be relied on in any case. </li>\n<li>Also, you're missing <code>#include <utility></code> for <code>std::move</code>.</li>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T08:40:40.677",
"Id": "200516",
"Score": "4",
"Tags": [
"c++",
"vectors"
],
"Title": "std::vector for pods"
} | 200516 |
<p>I have some code that produces a similarity matrix. However, despite feeling happy with the output, I'm not convinced that my code is the most efficient or the most pleasing on the eye.</p>
<p>I'm looking to make it more efficient and tidier, as well as open to advice on what could be implemented to make the end product better.</p>
<pre><code>var data = [
[["Arsenal", 0.0], ["Chelsea", 0.6014876082652767], ["Liverpool", 0.5204181171517794],["ManchesterCity", 0.549210189254557], ["ManchesterUnited", 0.5440890632512689], ["Tottenham", 0.6304670189118691]],
[["Arsenal",0.6014876082652767], ["Chelsea",0.0], ["Liverpool",0.5507313736526684],["ManchesterCity",0.5559069243804156], ["MancheserUnited",0.5231358671618266], ["Tottenham",0.6508134781353688]],
[["Arsenal",0.5204181171517794], ["Chelsea",0.5507313736526684], ["Liverpool",0.0],["ManchesterCity",0.49759390310994533], ["MancheserUnited",0.4787550034617063], ["Tottenham",0.5749363562907429]],
[["Arsenal",0.549210189254557], ["Chelsea",0.5559069243804156], ["Liverpool",0.49759390310994533],["ManchesterCity",0.0,], ["MancheserUnited",0.50215325905151], ["Tottenham",0.5802928689025063]],
[["Arsenal",0.5440890632512689], ["Chelsea",0.5231358671618266], ["Liverpool",0.4787550034617063],["ManchesterCity",0.50215325905151], ["MancheserUnited",0.0], ["Tottenham",0.5497016431211542]],
[["Arsenal",0.6304670189118691], ["Chelsea",0.6508134781353688], ["Liverpool",0.5749363562907429],["ManchesterCity",0.5802928689025063], ["MancheserUnited",0.5497016431211542], ["Tottenham",0.0]]
];
var teams = ["ARS", "CHE", "LIV", "MCI", "MUN", "TOT"]
var cols = data.length;
var rows = data.length;
var cellSize = 55;
var svg = d3.select("body")
.append("svg")
.attr("width", 600 )
.attr("height", 500)
svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * cellSize + ")"
})
.selectAll("rect")
.data(function(d) {return d;})
.enter()
.append("rect")
.attr("fill", function(d) {
if (d[1] == 0) {
return "#2A363B";
} else if (d[1] <= 0.50) {
return "#F8B195";
} else if (d[1] <= 0.55) {
return "#F67280";
} else if (d[1] <= 0.59) {
return "#C06C84";
} else if (d[1] <= 0.62) {
return "#6C5B7B";
} else if (d[1] >= 0.63) {
return "#355C7D";
}})
.attr("x", 100)
.attr("y", function(d, i) {
return i * cellSize ;
})
.attr("width", 50)
.attr("height", 50)
.attr("r", 55);
</code></pre>
<p><a href="https://i.stack.imgur.com/OK1bB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OK1bB.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<p>Here are some advices regarding the D3 part of the code:</p>\n\n<h3>Use scales!</h3>\n\n<p>Your <code>if... else</code> logic for filling the rectangles is cumbersome and luckily unnecessary: you can use a scale, in that case a threshold scale:</p>\n\n<pre><code>var color = d3.scaleThreshold()\n ... | {
"AcceptedAnswerId": "200524",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T10:21:09.160",
"Id": "200518",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"d3.js"
],
"Title": "Similarity matrix in D3"
} | 200518 |
<p>I have this Python code that implements a rectangular numerical integration. It evaluates the (K-1)-dimensional integral for arbitrary integer \$K \geq 1\$</p>
<p>$$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$</p>
<p>where \$F_U\$ corresponds to the cdf function in the code, and \$f_U\$ to the pdf. I implemented it using recursion as follows:</p>
<pre><code> #************************** Import necessary libraries******************************************
import numpy as np
import matplotlib.pyplot as plt
import time
#******************************Set the constant scalars and vectors***************************
start_time = time.time()
KU = 3
eta_dB = 3
eta = 10**(eta_dB/10)
ExpanF = 50
tdB = np.arange(-5,11,4)
tVec = 10**(tdB/10)
thVec = (tVec/eta)*(ExpanF-eta*(KU-1))
N = 10000 # For simulation
du = 0.01
#******************************Define functions to be used***************************************
#Define the CDF of U
def CDF(u):
return 1-1/(u+1)
#Define the PDF of U
def pdf(u):
return 1/((1+u))**2
def FK(h, k):
#print(f'h is {h}, and k is {k}')
if k == 1:
res = CDF(h)
else:
#n_iter = int(h/du)
res = 0
u = 0
while u < h:
res += FK(h-u, k-1)*pdf(u)*du
u += du
return res
#*******************Find the numerical and simulation values of the integral******************
ResultNum = []
ResultSim = []
if (ExpanF-eta*(KU-1)) > 0:
for t in thVec:
# Numerical
ResultNum.append(1-FK(t, KU))
# Simulation
count = 0
for n in range(0, N):
if np.sum(np.random.exponential(1, (1, KU))/np.random.exponential(1, (1, KU))) <= t:
count += 1
ResultSim.append(1-count/N)
</code></pre>
<p>The parameter <code>du</code> is the resolution of the numerical integral, and the smaller, the more accurate the numerical approximation is. However, decreasing <code>du</code> comes at the expense of more computational time using the above code. For example I tried to run the above code on my machine Intel i5 @2.5 GH with 6 GB of RAM for <code>du=0.0001</code>, and it took 15 hours and didn't finish, at which case I had to abort it. </p>
<p>Is there anyway the above code can be optimized to run significantly faster? I tried C++, and I got a 30x speed factor using the same code and algorithm, but I was wondering if I can get a similar or better speed up factor in Python.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T17:56:19.313",
"Id": "386122",
"Score": "0",
"body": "Please fix your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block."
},
{
"Conte... | [
{
"body": "<blockquote>\n <p>I have this Python code that implements a rectangular numerical integration.</p>\n</blockquote>\n\n<p>In what sense \"rectangular\"? Or is that as opposed to contour integration?</p>\n\n<blockquote>\n <p>It evaluates the (K-1)-dimensional integral for arbitrary integer <span class... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T15:40:31.840",
"Id": "200525",
"Score": "7",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"numerical-methods"
],
"Title": "Implementing numerical integration in Python"
} | 200525 |
<p>This code is extremely slow and ideally I would appreciate someone walking me through getting this going on the GPU, but if nobody has time for that which is understandable, any and all optimisations would be most welcome!</p>
<pre><code>Private Sub Picture(source As Image, picturebox As PictureBox)
Dim r As Double
Dim g As Double
Dim b As Double
Dim bmp As New Bitmap(source)
Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.[ReadOnly], bmp.PixelFormat)
Dim ptr As IntPtr = bmpData.Scan0
Dim bytes As Integer = bmpData.Stride * bmp.Height
Dim rgbValues As Byte() = New Byte(bytes - 1) {}
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
Dim linWhiteMult = 1 / (((LinearWhiteTextBox.Text * ((ShoulderStrengthTextBox.Text * LinearWhiteTextBox.Text) + (LinearAngleTextBox.Text * LinearStrengthTextBox.Text)) + (ToeStrengthTextBox.Text * ToeNumeratorTextBox.Text)) _
/ (LinearWhiteTextBox.Text * ((ShoulderStrengthTextBox.Text * LinearWhiteTextBox.Text) + LinearStrengthTextBox.Text) + ToeStrengthTextBox.Text * ToeDenominatorTextBox.Text) - (ToeNumeratorTextBox.Text / ToeDenominatorTextBox.Text)))
'precalculations for optimisation
Dim LaLs = LinearAngleTextBox.Text * LinearStrengthTextBox.Text
Dim TsTn = ToeStrengthTextBox.Text * ToeNumeratorTextBox.Text
Dim TsTd = ToeStrengthTextBox.Text * ToeDenominatorTextBox.Text
Dim Tn_Td = ToeNumeratorTextBox.Text / ToeDenominatorTextBox.Text
Dim list As New List(Of String)
For x As Integer = 0 To bmp.Width - 1
For y As Integer = 0 To bmp.Height - 1
Dim position As Integer = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat) / 8)
b = rgbValues(position)
g = rgbValues(position + 1)
r = rgbValues(position + 2)
'^2.2 lookup table (for optimisation) for gamma correction
b = table.Item(b)
g = table.Item(g)
r = table.Item(r)
'the following is the filmic tone map formula, i.e.
'x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F)) - E/F
r = (((r * ((ShoulderStrengthTextBox.Text * r) + (LaLs)) + (TsTn)) _
/ (r * ((ShoulderStrengthTextBox.Text * r) + LinearStrengthTextBox.Text) + TsTd) - (Tn_Td))) * linWhiteMult
g = (((g * ((ShoulderStrengthTextBox.Text * g) + (LaLs)) + (TsTn)) _
/ (g * ((ShoulderStrengthTextBox.Text * g) + LinearStrengthTextBox.Text) + TsTd) - (Tn_Td))) * linWhiteMult
b = (((b * ((ShoulderStrengthTextBox.Text * b) + (LaLs)) + (TsTn)) _
/ (b * ((ShoulderStrengthTextBox.Text * b) + LinearStrengthTextBox.Text) + TsTd) - (Tn_Td))) * linWhiteMult
If r > 1 Then
r = 1
End If
If g > 1 Then
g = 1
End If
If b > 1 Then
b = 1
End If
rgbValues(position) = Math.Round((b ^ 0.45) * 255)
rgbValues(position + 1) = Math.Round((g ^ 0.45) * 255)
rgbValues(position + 2) = Math.Round((r ^ 0.45) * 255)
Next
Next
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes)
bmp.UnlockBits(bmpData)
' apply the bmp to the avatars and dispose old
Dim OldImage = picturebox.Image
picturebox.Image = bmp
OldImage.Dispose()
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T04:18:30.360",
"Id": "386183",
"Score": "0",
"body": "Friend of mine pointed out that taking the string parsing out of the loop is an obvious way to speed it up - he was right, it's now lightning fast :)"
}
] | [
{
"body": "<p>First, I have to say that you are using good variable names.</p>\n\n<p><strong>Turn Option Strict On</strong></p>\n\n<p>This setting is important, it'll help you see errors and needed conversion.</p>\n\n<p>You'll notice that this isn't possible</p>\n\n<blockquote>\n<pre><code>Dim LaLs = LinearAngl... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T15:52:17.713",
"Id": "200526",
"Score": "3",
"Tags": [
"performance",
"image",
"vb.net",
"graphics"
],
"Title": "Tone Mapping image manipulation"
} | 200526 |
<p>This is a question from <a href="https://www.amazon.de/Cracking-Coding-Interview-Programming-Questions/dp/098478280X" rel="noreferrer">the book "Cracking the Coding Interview"</a>.</p>
<blockquote>
<p>Implement an algorithm to determine if a string has all unique
characters What if you can not use additional data structures?</p>
</blockquote>
<p>I can use <code>std::map</code> but in interview they check logic. Suggest me some improvement for optimization.</p>
<pre><code>#include <iostream>
#include <string>
class Strings
{
static const int SIZE = 26;
char alphabetL[SIZE] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'};
char alphabetS[SIZE] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'};
public:
Strings() = default;
~Strings() = default;
bool isAllUnique(std::string&);
private:
std::string toLower(std::string&);
};
std::string Strings::toLower(std::string& str)
{
for (int i = 0; i < str.length(); i++)
{
for (int j = 0; j < SIZE; j++)
{
if (str[i] == alphabetL[j])
{
str[i] = alphabetS[j];
}
}
}
return str;
}
bool Strings::isAllUnique(std::string& str)
{
int count[SIZE];
for (int k = 0; k < SIZE; k++)
{
count[k] = 0;
}
str = toLower(str);
for (int i = 0; i < str.length(); i++)
{
for (int j = 0; j < SIZE; j++)
{
if (str[i] == alphabetS[j])
{
count[j] = count[j] + 1;
if (count[j] > 1)
{
return false;
}
break;
}
}
}
return true;
}
int main()
{
Strings obj;
std::string str;
std::cout << "Enter String\n";
std::getline(std::cin, str);
bool res = obj.isAllUnique(str);
if (res == true)
{
std::cout << "There are unique characters in string\n";
}
else
{
std::cout << "There are no unique characters in string\n";
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T16:28:31.240",
"Id": "386114",
"Score": "6",
"body": "Please define \"unique characters\" for the purpose of this solution: Are `'a'` and `'A'` the same? Is `'\\0'` or similar allowed as valid characters? What counts as `data struc... | [
{
"body": "<p>While you could approach this problem via a marking algorithm, the simplest way to achieve what you are trying to do is to sort the string and check for adjacent elements of the same type. Luckily, the standard library makes this very easy:</p>\n\n<pre><code>void to_lower(std::string& s) noexc... | {
"AcceptedAnswerId": "200538",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T16:08:45.797",
"Id": "200527",
"Score": "6",
"Tags": [
"c++",
"programming-challenge",
"interview-questions"
],
"Title": "Check if a string has all unique characters"
} | 200527 |
<p>On my application, I have a JavaScript cycle that updates tag contents on my page regularly:</p>
<pre><code><script type="text/javascript">
var players = [];
players.push($('#p0'));
players.push($('#p1'));
players.push($('#p2'));
players.push($('#p3'));
i=0;
/*
* cycle through the players.
*/
function cyclePlayer() {
players[i].parents(".card-header").addClass('border-success');
players[i].load('play.php?p='+i);
i = ++i % players.length;
$('#deck').load('play.php?deck=1');
$('#pile').load('play.php?pile=1');
$('#feedback').load('play.php?feedback=1');
}
PlayerLoop = setInterval('cyclePlayer()', 1500 );
$("#stop").click(function(){
clearInterval(PlayerLoop);
});
$('#reset').click(function() {
$('#deck').load('play.php?reset=1');
location.reload();
});
</script>
</code></pre>
<p>The server code that is being called looks like this:</p>
<pre><code><?php
require '../vendor/autoload.php';
session_start();
use Svc\Myapp\FrontHandler;
$myApp = new FrontHandler();
if (isset($_GET['p']) && !isset($_SESSION['winner'])) {
echo $myApp->playerTurn();
}
if (isset($_GET['deck'])) {
echo $myApp->deckUpdate();
}
if (isset($_GET['pile'])) {
echo $myApp->pileUpdate();
}
if (isset($_GET['feedback'])) {
echo $myApp->feedbackUpdate();
}
</code></pre>
<p>Is this production quality code? Is there a way to refactor it to improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T16:29:43.073",
"Id": "386115",
"Score": "0",
"body": "Considering your `<?php` tag never closes, I would say no."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T19:43:40.520",
"Id": "386137",
... | [
{
"body": "<p>My answer focuses on the ajax requests.</p>\n\n<p>Why 4 requests at each 1500 milliseconds <strong>to the same file</strong> (<code>play.php</code>)?</p>\n\n<p>I would do only one request and I would \"cycle\" on a delay starting from the success callback... instead of a fixed interval, which does... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T16:17:05.047",
"Id": "200528",
"Score": "3",
"Tags": [
"javascript",
"php",
"jquery",
"game",
"ajax"
],
"Title": "Update game content via AJAX"
} | 200528 |
<p>I created a generator function to iterate through all possible dice rolls, and then applied it the ability score generating methods in Pathfinder RPG. (Obviously, there are more efficient ways to approach probability outcome analysis from a number theoretic perspective, but this allows generic and quick analysis without too much mathematical understanding of the particular situation.)</p>
<p>My question is, using this iterator, is there any way to generically split the iterator into different numbers of dice? My current approach feels sloppy and is definitely not scalable to more varied numbers of dice. Obviously, I could just use separate dice iterators, but that would be a generally less efficient approach.</p>
<p>Also, as always, any other feedback is appreciated, even PEP 8 stylistic feedback.</p>
<p><strong>math_supplement.py</strong></p>
<pre><code>from fractions import Fraction
def dice_outcomes(num, min=1, max=6):
'''
A generator function returning all outcomes of num dice as lists. Dice values are inclusively between min (default 1) and max (default 6).
'''
output = [min] * num
try:
while True:
yield output
i = 0
while True:
output[i] += 1
if output[i] <= max:
break
output[i] = min
i += 1
except IndexError:
return
def sample_space_report(stats, size):
'''
Reports on stats relative to a sample space.
stats
a dict, with each key being an outcome and the
size
the sample space
'''
probsum = 0
for outcome, occurences in stats.items():
prob = Fraction(occurences, size)
probsum += prob
print(f'{outcome}: {prob} ({float(prob):.2%})')
print(f'Validation sum = {probsum}')
</code></pre>
<p><strong>Pathfinder_ability_score_probability.py</strong></p>
<pre><code>from collections import Counter
from math_supplement import dice_outcomes, sample_space_report
class AbilityScoreStats:
def __init__(self, roll_handler, sample_space):
self.roll_handler = roll_handler
self.sample_space = sample_space
self.outcomes = Counter()
def add(self, l):
self.outcomes[self.roll_handler(l)] += 1
MIN = 1
MAX = 6
DICE_FACES = MAX - MIN + 1
ability_score_methods = {'Standard':
AbilityScoreStats(lambda rolls: sum(rolls) - min(rolls),
DICE_FACES ** 4),
'Classic':
AbilityScoreStats(lambda rolls: sum(rolls),
DICE_FACES ** 3),
'Heroic':
AbilityScoreStats(lambda rolls: sum(rolls) + 6,
DICE_FACES ** 2)
}
for rolls in dice_outcomes(2, min=MIN, max=MAX):
ability_score_methods['Heroic'].add(rolls)
for dice_three in range(1,7):
working_rolls = rolls + [dice_three]
ability_score_methods['Classic'].add(working_rolls)
for dice_four in range(1,7):
working_rolls = rolls + [dice_three, dice_four]
ability_score_methods['Standard'].add(working_rolls)
for name, method in ability_score_methods.items():
print(f' {name}:')
sample_space_report(method.outcomes, method.sample_space)
</code></pre>
| [] | [
{
"body": "<p>Your <code>dice_outcomes</code> function is not generic enough. It works for you with your use case but consider the following call:</p>\n\n<pre><code>list(dice_outcomes(3))\n</code></pre>\n\n<p>the result is surprising:</p>\n\n<pre><code>[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1,... | {
"AcceptedAnswerId": "200553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T16:52:49.690",
"Id": "200530",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"dice"
],
"Title": "Systematically analyzing dice roll outcomes"
} | 200530 |
<p>this is a follow up of:<a href="https://codereview.stackexchange.com/questions/199931/text-based-game-hunt-the-wumpus-version-2">Text based game “Hunt the Wumpus” Version 2</a></p>
<p>this code was used as a base to turn this game into a gui game with fltk: <a href="https://codereview.stackexchange.com/questions/201833/hunt-the-wumpus-gui-fltk">Hunt the Wumpus GUI (FLTK)</a></p>
<p>I took the suggestions made there and corrected the code. I think now it got a lot more simple. </p>
<p>Please let me know if you still find something smelly in the code. After this is reviewd i will turn this into a GUI game were the dungeon is displayed.</p>
<p><b>wumpus.h</b></p>
<pre><code>#pragma once
#include <array>
#include <vector>
namespace wumpus {
using Room_number = int;
class Dungeon {
public:
Dungeon();
void indicate_hazards();
bool shoot_arrow(std::vector<int> tar_rooms);
bool move_wumpus();
bool move_player(Room_number target_room);
Room_number select_room_to_move();
std::array<Room_number, 3> get_neighbour_rooms() const;
void show_state_of_dungeon(); //only used for debug
private:
struct Room {
std::array <Room*, 3> neighbors{ nullptr }; //pointer to 3 rooms next to this room
Room_number room_number{ 0 };
bool has_wumpus{ false };
bool has_pit{ false };
bool has_bat{ false };
bool has_player{ false };
};
static constexpr int count_of_pits = 3;
static constexpr int count_of_bats = 3;
int arrows = 5;
std::array<Room, 20> rooms
{
{
{ &rooms[1] ,&rooms[4], &rooms[19] },
{ &rooms[0] ,&rooms[2], &rooms[17] },
{ &rooms[1] ,&rooms[3], &rooms[15] },
{ &rooms[2] ,&rooms[4], &rooms[13] },
{ &rooms[0] ,&rooms[3], &rooms[5] },
{ &rooms[4] ,&rooms[6], &rooms[12] },
{ &rooms[5] ,&rooms[7], &rooms[19] },
{ &rooms[6] ,&rooms[8], &rooms[11] },
{ &rooms[7] ,&rooms[9], &rooms[18] },
{ &rooms[8] ,&rooms[10], &rooms[16] },
{ &rooms[9] ,&rooms[11], &rooms[14] },
{ &rooms[7] ,&rooms[10], &rooms[12] },
{ &rooms[5] ,&rooms[11], &rooms[13] },
{ &rooms[3] ,&rooms[12], &rooms[14] },
{ &rooms[10] ,&rooms[13], &rooms[15] },
{ &rooms[2] ,&rooms[14], &rooms[16] },
{ &rooms[9] ,&rooms[15], &rooms[17] },
{ &rooms[1] ,&rooms[16], &rooms[18] },
{ &rooms[8] ,&rooms[17], &rooms[19] },
{ &rooms[0] ,&rooms[6], &rooms[18] },
}
};
};
int get_random(int min, int max);
void hunt_the_wumpus();
void instructions();
std::vector<Room_number> select_rooms_to_shoot();
}
</code></pre>
<p><b>wumpus.cpp</b></p>
<pre><code>#include <iostream>
#include <random>
#include <string>
#include <sstream>
#include "wumpus.h"
namespace wumpus {
Dungeon::Dungeon()
{
// create room numbers
std::array<Room_number,20> random_room_numbers;
for (size_t i = 0; i < rooms.size(); ++i) {
random_room_numbers[i] = i + 1;
}
//generate random numbers to use to put room numbers random
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(random_room_numbers.begin(), random_room_numbers.end(),g);
// add room numbers randomly
for (size_t i = 0; i < rooms.size(), i < random_room_numbers.size(); ++i) {
rooms[i].room_number = random_room_numbers[i];
}
std::size_t i{ 0 };
rooms[i++].has_player = true;
rooms[i++].has_wumpus = true;
for (auto pits{ count_of_pits }; pits; --pits) {
rooms[i++].has_pit = true;
}
for (auto bats{ count_of_bats }; bats; --bats) {
rooms[i++].has_bat = true;
}
std::shuffle(rooms.begin(), rooms.end(), g);
}
void Dungeon::indicate_hazards()
{
bool is_first_bat = true;
bool is_first_pit = true;
// find the player
auto player_room{ std::find_if(rooms.begin(), rooms.end(), [](const Room &r) { return r.has_player; }) };
for (auto& x : player_room->neighbors) {
if (x->has_wumpus) {
std::cout << "I smell the wumpus\n";
}
if (is_first_pit && x->has_pit) {
is_first_pit = false;
std::cout << "I feel a breeze\n";
}
if (is_first_bat && x->has_bat) {
is_first_bat = false;
std::cout << "I hear a bat\n";
}
}
std::cout << "You are in room " << player_room->room_number << "\n"
<< "You have "<<arrows<< " arrow(s) left\n"
<< "Tunnels lead to rooms "
<< player_room->neighbors[0]->room_number << ", "
<< player_room->neighbors[1]->room_number << " and "
<< player_room->neighbors[2]->room_number << "\n"
<< "what do you want to do? (M)ove or (S)hoot?\n";
}
bool Dungeon::shoot_arrow(std::vector<int> target_rooms)
//trys to shoot in the supplied tar rooms an arrow
//if the wumpus is hit returns true to indicate victory
//moves the wumpus on fail
{
--arrows;
// find the player
auto player_room{ std::find_if(rooms.begin(), rooms.end(), [](const Room &r) { return r.has_player; }) };
for (const auto& target : target_rooms){
bool room_reached = false;
for (const auto& neigbour : player_room->neighbors) {
if (neigbour->room_number == target) {
room_reached = true;
if (rooms[neigbour->room_number - 1].has_wumpus) {
std::cout << "!!!!!!YOU WON!!!!!!: You killed the Wumpus in room " << rooms[neigbour->room_number - 1].room_number << "\n";
return true;
}
break;
}
}
if (!room_reached) {
std::cout << "Room " << target << " could not be reached from arrow\n";
return false;
}
}
if (arrows == 0) {
std::cout << "You lost: You ran out of arrows";
return true;
}
return false;
}
bool Dungeon::move_wumpus()
{
auto direction = get_random(0, 3);
if (direction == 3) { // 25% chance that wumpus won't move
return false;
}
// find the wumpus
auto wumpus_room{ std::find_if(rooms.begin(), rooms.end(), [](const Room &r) { return r.has_wumpus; }) };
// move him
wumpus_room->has_wumpus = false;
auto new_room = wumpus_room->neighbors[direction];
new_room->has_wumpus = true;
if (new_room->has_player) {
std::cout << "You lost: Wumpus enters your room and eats you\n";
return true;
}
return false;
}
bool Dungeon::move_player(Room_number target_room_number)
//trys to move player to the selected room
//if deadly hazard like pit or wumpus is found return game over = true;
//if bat is found choose new random room free from hazards to put the player
{
// find the player
auto player_room{ std::find_if(rooms.begin(), rooms.end(), [](const Room &r) { return r.has_player; }) };
for (auto& x : player_room->neighbors) {
if (x->room_number == target_room_number) {
if (x->has_wumpus) {
std::cout << "You lost: You got eaten by the Wumpus\n";
return true;
}
else if (x->has_pit) {
std::cout << "You lost: You fell in a bottomless pit\n";
return true;
}
else if (x->has_bat) {
std::cout << "Gigantic bat appeared!!!\n";
std::cout << "You got dragged to a new room\n";
//Only put player in empty room
Room* bat_destionation_room = nullptr;
do{
bat_destionation_room = &rooms[get_random(0, rooms.size() - 1)];
} while (bat_destionation_room->has_wumpus || bat_destionation_room->has_pit || bat_destionation_room->has_bat || bat_destionation_room->has_player);
player_room->has_player = false;
bat_destionation_room->has_player = true;
return false;
}
else {
player_room->has_player = false;
auto target_room = &rooms[target_room_number];
target_room->has_player = true;
return false;
}
}
}
std::cerr << "Dungeon::move_player: Unknown target room entered";
return false;
}
Room_number Dungeon::select_room_to_move()
{
for (;;) {
std::cout << "To where??\n";
Room_number target = 0;
std::cin >> target;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(999, '\n');
continue;
}
auto neighbor = get_neighbour_rooms();
if (target == neighbor[0] || target == neighbor[1] || target == neighbor[2])
return target;
}
}
std::array<Room_number, 3> Dungeon::get_neighbour_rooms() const
{
// find the player
auto player_room{ std::find_if(rooms.begin(), rooms.end(), [](const Room &r) { return r.has_player; }) };
return std::array<Room_number, 3>{
player_room->neighbors[0]->room_number,
player_room->neighbors[1]->room_number,
player_room->neighbors[2]->room_number
};
}
void Dungeon::show_state_of_dungeon()
{
auto print_rooms = rooms;
std::sort(print_rooms.begin(), print_rooms.end(), [](const Room &a, const Room &b) { return b.room_number > a.room_number; });
for (const auto&room : print_rooms) {
std::cout << "Room " << room.room_number << " connects to: ";
for (const auto&neighbor : room.neighbors) {
if (neighbor != nullptr) {
std::cout << neighbor->room_number << " ";
}
else {
std::cout << "np" << " ";
}
}
std::cout << " ";
if (room.has_wumpus) {
std::cout << "wumpus:" << room.has_wumpus << " ";
}
if (room.has_pit) {
std::cout << "pit:" << room.has_pit << " ";
}
if (room.has_bat) {
std::cout << "bat:" << room.has_bat << " ";
}
if (room.has_player) {
std::cout << "player:" << room.has_player << " ";
}
std::cout << "\n";
}
}
//-------------------------------------------------------------
//Helper functions
//-------------------------------------------------------------
int get_random(int min, int max)
{
static std::random_device rd;
static std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(min, max);
return distribution(mt);
}
void hunt_the_wumpus()
{
instructions();
for (;;) // restart game
{
Dungeon dungeon;
dungeon.show_state_of_dungeon();
for (;;) { // current room handle
dungeon.indicate_hazards();
std::string in;
std::cin >> in;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(999, '\n');
continue;
}
bool game_over = false;
if (in == "m" || in == "M" || in == "Move" || in == "move") {
game_over = dungeon.move_player(dungeon.select_room_to_move());
}
else if (in == "s" || in == "S" || in == "Shoot" || in == "shoot") {
game_over = dungeon.shoot_arrow(select_rooms_to_shoot());
if (game_over == true) {
break;
}
game_over = dungeon.move_wumpus();
}
else if (in == "cheat") { // secret menue to show dungeon state
dungeon.show_state_of_dungeon();
}
if (game_over == true) {
break;
}
}
std::cout << "Press any key to start a new game or (q)uit to end game\n";
std::string in;
std::cin >> in;
if (in == "q" || in == "Q" || in == "Quit" || in == "quit")
break;
}
}
void instructions()
{
std::cout <<R"(Welcome to "Hunt the Wumpus"!
The wumpus lives in a cave of rooms.Each room has 3 tunnels leading to
other rooms. (Look at a dodecahedron to see how this works - if you don't know
what a dodecahedron is, ask someone).
Hazards
Bottomless pits - two rooms have bottomless pits in them. If you go there, you
fall into the pit(and lose!)
Super bats - two other rooms have super bats.If you go there, a bat grabs you
and takes you to some other room at random. (Which may be troublesome).
Wumpus
The wumpus is not bothered by hazards(he has sucker feet and is too big for a
bat to lift).Usually he is asleep.Two things wake him up : you shooting an
arrow or you entering his room."
If the wumpus wakes he moves(p = .75) one room or stays still(p = .25).After
that, if he is where you are, he eats you up and you lose!"
Each turn you may move or shoot a crooked arrow.
Moving: you can move one room(thru one tunnel).
Arrows : you have 5 arrows.You lose when you run out.Each arrow can go from 1
to 3 rooms.You aim by telling the computer the rooms you want the arrow to go
to.If the arrow can't go that way (if no tunnel) it moves at random to the
next room.If the arrow hits the wumpus, you win.If the arrow hits you, you lose.
Warnings
When you are one room away from a wumpus or hazard, the computer says :
Wumpus: "I smell the wumpus"
Bat : "I hear a bat"
Pit : "I feel a breeze"
"Press any key to start")";
char c;
std::cin.get(c);
}
std::vector<Room_number> select_rooms_to_shoot()
{
for(;;){
std::cout << "Enter the rooms you want to shoot the arrow (e.g. 2-3-12, e.g. 4-5, e.g. 2)\n";
std::string input;
std::cin >> input;
std::istringstream ist{ input };
std::vector<int> target_rooms;
bool bad_input = false;
while (!ist.eof()) {
int room_number;
ist >> room_number;
if (ist.fail()) {
bad_input = true;
break;
}
target_rooms.push_back(room_number);
if (target_rooms.size() == 3 || ist.eof())
break;
char seperator;
ist >> seperator;
if (ist.fail()) {
bad_input = true;
break;
}
if ((seperator != '-') || (target_rooms.size() > 3)) {
bad_input = true;
break;
}
}
if (bad_input) {
continue;
}
else {
return target_rooms;
}
}
}
}
</code></pre>
<p><b> main.cpp</b></p>
<pre><code>#include <iostream>
#include "wumpus.h"
int main()
try {
wumpus::hunt_the_wumpus();
}
catch (std::runtime_error& e) {
std::cerr << e.what() << "\n";
std::cin.get();
}
catch (...) {
std::cerr << "unknown error\n";
std::cin.get();
}
</code></pre>
| [] | [
{
"body": "<p>I highly recommend you compile your code with clang and use all of its facilities (like sanitizer, which didn't find anything, so good job). Compiling your code with <code>-Wall -Wextra -pedantic -pedantic-errors</code> results in 81 warnings!!</p>\n\n<p>To be fair, some of those warnings are styl... | {
"AcceptedAnswerId": "200566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T16:58:49.707",
"Id": "200532",
"Score": "5",
"Tags": [
"c++",
"game"
],
"Title": "Text based game “Hunt the Wumpus” Version 3"
} | 200532 |
<p>The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result
the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given
numerical IDs starting from the corner, as follows:</p>
<p>| 7</p>
<p>| 4 8</p>
<p>| 2 5 9</p>
<p>| 1 3 6 10</p>
<p>Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground. </p>
<p>For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners). </p>
<p>Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a string representation of the number.</p>
<p>Here is my solution:</p>
<pre><code>y = int(input())
x = int(input())
sum_in_x = 1
for i in range(x):
sum_in_x = sum_in_x + range(x)[i]
in_sum =i + 2
sum_in_y = sum_in_x
for j in range(y - 1):
sum_in_y = sum_in_y + in_sum
in_sum += 1
print(sum_in_y)
</code></pre>
<p>It works and generates the needed solutions, but I am trying to understand if there are better ways of doing this. </p>
| [] | [
{
"body": "<p>Your current algorithm is very inefficient. I would use the following algorithmic approach:</p>\n\n<pre><code>def answer(x, y):\n y_diff = y - 1\n corner = x + y_diff\n id = corner * (corner + 1) // 2\n id -= y_diff\n return str(id)\n</code></pre>\n\n<p>This method takes advantage o... | {
"AcceptedAnswerId": "200544",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T17:48:18.500",
"Id": "200535",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"community-challenge"
],
"Title": "Finding the position in a triangle for the given challenge"
} | 200535 |
<p>I created a Student Management System based on these directions:</p>
<ul>
<li>Ask the user how many new students will be added to the database</li>
<li>The user should be prompted to enter the name and the year for each student</li>
<li>The student should have a 5-digit unique ID with the first number being their grade level</li>
<li>A student can enroll in the following courses: History 101, Mathematics 101, English 101, Chemistry 101, & Computer Science 101</li>
<li>Each course costs $600</li>
<li>The student should be able to view their balance and pay their tuition</li>
<li>To see the status of the student, we should see their name, ID, courses enrolled, and balance</li>
</ul>
<p>I wanted to get other people's opinions on:</p>
<ol>
<li>How are my comments for this program this is my first using JavaDoc style comments?</li>
<li>What ways could I refactor the addCourses and payForCourses methods to make smaller and cleaner?</li>
<li>Should I be using <code>double</code> or <code>float</code> instead of <code>BigDecimal</code> for the tuition?</li>
<li>How can I reduce the code in my main method?</li>
<li>Any general comments/concerns about the code?</li>
</ol>
<pre class="lang-java prettyprint-override"><code>import java.math.RoundingMode;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.math.BigDecimal;
public class Student {
private String firstName;
private String lastName;
private String id;
private List<String> courses;
private BigDecimal tuition;
private Scanner keyboard = new Scanner(System.in);
private Student(String fName, String lastName) {
this.firstName = fName;
this.lastName = lastName;
}
private Student() {
}
//Getters and Setters
private BigDecimal getTuition() { return tuition; }
private void setTuition(BigDecimal money) {
this.tuition = money;
}
private String getName() { return firstName + " " + lastName; }
private void setFirstName(String firstName) { this.firstName = firstName; }
private void setLastName(String lastName) { this.lastName = lastName; }
private String getId() { return id; }
private void setId(String id) { this.id = id; }
private List<String> getCourses() { return courses; }
private void setCourses(List<String> courses) { this.courses = courses; }
/**
* Creates a id using a number from 1 - 4 given by the user and a random string of length 4.
*/
private void makeID()
{
String grade;
boolean checked = false;
while (!checked)
{
System.out.println("Enter your school year 1. Freshman, 2. Sophomore, 3.Junior and 4. Senior ");
grade = keyboard.nextLine();
if (grade.length() == 1 && Integer.parseInt(grade) > 0 && Integer.parseInt(grade) < 5)
{
setId(grade.concat(randomString()));
checked = true;
} else {
System.out.println("The input you enter is incorrect please try again");
}
}
}
/**
* Returns a randomly generated 4 character string that will combined with a number entered by the user to make the student id.
*
* @return The four character random string
*/
private String randomString()
{
String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
int great = AB.length();
int temp;
String codeword = "";
for (int i = 0; i < 4; i++)
{
temp = (int) (random.nextFloat() * great);
codeword = codeword.concat(Character.toString(AB.charAt(temp)));
}
return codeword;
}
/**
* A payment system that allows the user to make multiple payments on their tuition
*/
private void payForCourses()
{
String answer;
BigDecimal payment;
BigDecimal moneyLeftOver;
while (getTuition().compareTo(BigDecimal.ZERO) > 0)
{
System.out.println("Your current balance is $" + getTuition());
System.out.println("Do you want pay off you balance right now");
answer = keyboard.nextLine();
if (answer.toLowerCase().equals("yes"))
{
System.out.println("How much would you like to pay right now");
if (keyboard.hasNextBigDecimal())
{
payment = keyboard.nextBigDecimal();
payment = payment.setScale(2, RoundingMode.HALF_UP);
keyboard.nextLine();
if ((payment.compareTo(BigDecimal.ZERO) > 0) && payment.compareTo(getTuition()) <= 0)
{
moneyLeftOver = getTuition().subtract(payment);
setTuition(moneyLeftOver);
} else if (payment.compareTo(getTuition()) > 0) {
System.out.println("The value you have given is greater than your tuition");
} else if (payment.compareTo(BigDecimal.ZERO) < 0) {
System.out.println("You gave an negative number as a payment value. Please enter a positive value next time");
}
} else {
keyboard.nextLine();
System.out.println("You entered the wrong input so please input a number next time.");
}
} else if (answer.toLowerCase().equals("no")) {
break;
} else {
System.out.println("You gave the wrong input either enter yes or no");
}
}
}
/**
* Gives the student the class they entered the corresponding number for a class
*
* @param classes - A list that contains the classes a student has at the moment.
* @param courseNumber - A number that represent a particular class.
*/
private void chooseCourses(List<String> classes, int courseNumber)
{
switch (courseNumber)
{
case 1:
if (checkDups(classes, "History 101"))
classes.add("History 101");
break;
case 2:
if (checkDups(classes, "Mathematics 101"))
classes.add("Mathematics 101");
break;
case 3:
if (checkDups(classes, "English 101"))
classes.add("English 101");
break;
case 4:
if (checkDups(classes, "Chemistry 101"))
classes.add("Chemistry 101");
break;
case 5:
if (checkDups(classes, "Computer Science 101"))
classes.add("Computer Science 101");
break;
default:
System.out.println("You gave the wrong input");
break;
}
}
/**
* Allows the user to add classes keeping track of classes they already added and setting the new tuition the user has.
*/
private void addCourses()
{
List<String> classes = new LinkedList<>();
setCourses(classes);
String answer;
int nextCourse;
BigDecimal size;
BigDecimal cost;
System.out.println("Do you want to add any courses? yes or no");
answer = keyboard.nextLine();
while (!answer.toLowerCase().equals("no"))
{
if (answer.toLowerCase().equals("yes"))
{
System.out.println("Which classes would you like to add now? Please choose from the following selection. " +
"Choose the number for the courses");
System.out.println("1. History 101");
System.out.println("2. Mathematics 101");
System.out.println("3. English 101");
System.out.println("4. Chemistry 101");
System.out.println("5. Computer Science 101");
if (keyboard.hasNextInt())
{
nextCourse = keyboard.nextInt();
keyboard.nextLine();
chooseCourses(classes, nextCourse);
} else {
System.out.println("You put in the wrong input: Enter a number 1 - 5 for each class");
keyboard.nextLine();
}
} else {
System.out.println("You put in the wrong input: Enter either yes or no next time");
}
System.out.println("Do you want to add any more courses?");
answer = keyboard.nextLine();
}
size = new BigDecimal(classes.size());
cost = new BigDecimal(600);
cost = cost.multiply(size);
setTuition(cost);
}
/**
* Make sure every class in a given list in unique.
*
* @param list - The list containing the student's current classes
* @param word - The string that being checked to see if it is unique in the list
* @return Whether or not the string is already in the list
*/
private boolean checkDups(List<String> list, String word)
{
for (String temp : list)
{
if (word.equals(temp))
{
System.out.println("You are already enrolled in that course");
return false;
}
}
return true;
}
/**
* Prints out each student's name, id, courses, and the current balance for tuition
*
* @param studentList - All the students enrolled and in the list
*/
private void displayInfo(Student[] studentList)
{
for (Student student : studentList)
{
System.out.println("Student Name: " + getName());
System.out.println("Student ID: " + student.getId());
if (student.getCourses().size() > 0) {
System.out.println("Student's Current Courses:" + student.getCourses());
} else {
System.out.println("Student's Current Courses: The student isn't enrolled in any courses");
}
System.out.println("Student's Current Balance: $" + student.getTuition());
System.out.println("------------------------------------------------------");
}
}
public static void main(String[] args) {
try {
int size;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students you wish to add to the system");
size = keyboard.nextInt();
keyboard.nextLine();
Student[] students = new Student[size];
Student student;
String firstName = "";
String lastName = "";
for (int i = 0; i < size; i++)
{
student = new Student(firstName, lastName);
students[i] = student;
System.out.println("Please enter your first name for Student ");
firstName = keyboard.nextLine();
student.setFirstName(firstName);
System.out.println("Please enter your last name");
lastName = keyboard.nextLine();
student.setLastName(lastName);
student.makeID();
student.addCourses();
student.payForCourses();
if (i == size - 1)
student.displayInfo(students);
}
} catch (NegativeArraySizeException e) {
System.out.println("You can't use a negative number for size");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T23:56:14.207",
"Id": "386162",
"Score": "1",
"body": "You are [correct](https://stackoverflow.com/a/285707) in using `BigDecimal` for storing monetary values. You should look into using `java.util.concurrent.ThreadLocalRandom` for `... | [
{
"body": "<p>A single student class managing the other students seems odd somehow. In fact, this has lead to a couple of bugs in your code. For example, in the <code>displayInfo</code> method you are iterating and printing all the students' information one by one, but you are always printing this.getName() ins... | {
"AcceptedAnswerId": "200565",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T19:11:14.697",
"Id": "200540",
"Score": "5",
"Tags": [
"java"
],
"Title": "Student Management System"
} | 200540 |
<p><strong>Problem Statement:</strong></p>
<blockquote>
<p>The Christmas tree is comprised of the following Parts Stand Each Part
is further comprised of Branches. Branches are comprised of Leaves.</p>
<p>How the tree appears as a function of days should be understood. Basis
that print the tree as it appears on the given day. Below are the
rules that govern how the tree appears on a given day. Write a program
to generate such a Christmas tree whose input is number of days.</p>
</blockquote>
<p><strong>Rules</strong></p>
<blockquote>
<p>1.If tree is one day old you cannot grow. Print a message "You cannot generate christmas tree"</p>
<p>2.Tree will die after 20 days; it should give a message "Tree is no more"</p>
<p>3.Tree will have one part less than the number of days.</p>
<p>E.g.</p>
<p><em>On 2nd day tree will have 1 part and one stand.</em></p>
<p><em>On 3rd day tree will have 2 parts and one stand</em></p>
<p><em>On 4th day tree will have 3 parts and one stand and so on.</em></p>
<p>4.Top-most part will be the widest and bottom-most part will be the narrowest.</p>
<p>5.Difference in number of branches between top-most and second from top will be 2</p>
<p>6.Difference in number of branches between second from top and bottom-most part will be 1</p>
<p>Below is an illustration of how the tree looks like on 4th day</p>
<p><a href="https://i.stack.imgur.com/4ZCnB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ZCnB.png" alt="enter image description here"></a></p>
</blockquote>
<p><strong>Input Format:</strong></p>
<blockquote>
<p>First line of input contains number of days denoted by N</p>
</blockquote>
<p><strong>Output Format:</strong></p>
<blockquote>
<p>Print Christmas Tree for given N</p>
<p>OR</p>
<p>Print "You cannot generate christmas tree" if N <= 1</p>
<p>OR</p>
<p>Print "Tree is no more" if N > 20</p>
</blockquote>
<p><strong>Constraints:</strong></p>
<blockquote>
<p>0<= N <=20</p>
</blockquote>
<p><strong>Sample Input and Output</strong></p>
<blockquote>
<p>Input: 2</p>
<p>Output:( below)</p>
<p><a href="https://i.stack.imgur.com/AYydJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AYydJ.png" alt="enter image description here"></a></p>
</blockquote>
<p><strong>The code:</strong></p>
<pre><code>#include<stdio.h>
int main(){
int i,j,leaves=1,day,rest,branches,max_leaves;
scanf("%d",&day);
//Check for exceptions
if(day<=1){
printf("You cannot generate christmas tree");
return 0;
}
else if(day>20){
printf("Tree is no more");
return 0;
}
// printf("Heres Your Christmas Tree:\n\n");
// For first part
branches=day+1;
max_leaves = 1+(branches-1)*2; // Arithmetic Progression
for(i=1;i<=branches;i++){
for(j=i;j<=max_leaves/2;j++){
printf(" ");
}
for(j=1;j<=leaves;j++){
printf("*");
}
printf("\n");
leaves=leaves+2;
}
// For remaining parts
branches=branches-2;
for(rest=1;rest<=day-2;rest++){
leaves=3;
for(i=2;i<=branches+1;i++){
for(j=i;j<=max_leaves/2;j++){
printf(" ");
}
for(j=1;j<=leaves;j++){
printf("*");
}
printf("\n");
leaves=leaves+2;
}
branches--;
}
// For stand
for(i=1;i<=2;i++){
for(j=1;j<=max_leaves/2;j++){
printf(" ");
}
printf("*\n");
}
return 0;
}
</code></pre>
<p>The code is working fine as can be checked on <a href="https://ideone.com/8W1jDF" rel="nofollow noreferrer">IDEOne</a>.</p>
| [] | [
{
"body": "<h1>Keep the scope of variables to a minimum</h1>\n\n<p>Since C99 we are allowed to mix declaration and code. At the moment, you have <code>i</code>, <code>j</code>, <code>rest</code> and so on in scope, even if <code>day</code> is out of the specification. That can lead to hard to find errors, for e... | {
"AcceptedAnswerId": "200578",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T19:23:51.517",
"Id": "200541",
"Score": "4",
"Tags": [
"algorithm",
"c",
"programming-challenge",
"ascii-art"
],
"Title": "Generate Christmas Tree"
} | 200541 |
<p>I made a simple dungeon generator in C# using MonoGame that works by placing rooms in a grid and connecting them via "tunnels". I would like feedback on how this could be improved in terms of efficiency and code style. Also, please ignore the <code>Render()</code> function in <code>DungeonGenerator.cs</code> as it is only temporary.</p>
<p>Here is one example of a generated dungeon:<a href="https://i.stack.imgur.com/MXQ2Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MXQ2Q.png" alt="A simple dungeon"></a></p>
<p><strong>SimpleRoomGenerator.cs</strong></p>
<pre><code>using System;
namespace Roguelike
{
public class SimpleRoomGenerator : DungeonGenerator
{
private struct Room
{
public const int MinWidth = 5;
public const int MinHeight = 5;
public const int MaxHeight = 9;
public const int MaxWidth = 9;
public int XPos { get; set; }
public int YPos { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int CentreX { get { return XPos + (Width / 2); } }
public int CentreY { get { return YPos + (Height / 2); } }
}
public const int NumRooms = 10;
public SimpleRoomGenerator(int width, int height) : base(width, height)
{
}
public override void Generate()
{
dungeon = new int[width, height];
Room previousRoom = new Room();
for (int i = 0; i < NumRooms; i++)
{
Room room = new Room();
room.XPos = random.Next(0, width - Room.MaxWidth);
room.YPos = random.Next(0, height - Room.MaxHeight);
room.Width = random.Next(Room.MinWidth, Room.MaxWidth);
room.Height = random.Next(Room.MinHeight, Room.MaxHeight);
for (int y = room.YPos; y < room.YPos + room.Height; y++)
{
for (int x = room.XPos; x < room.XPos + room.Width; x++)
{
dungeon[x, y] = 1;
}
}
if (i > 0)
{
int startX = Math.Min(room.CentreX, previousRoom.CentreX);
int startY = Math.Min(room.CentreY, previousRoom.CentreY);
int endX = Math.Max(room.CentreX, previousRoom.CentreX);
int endY = Math.Max(room.CentreY, previousRoom.CentreY);
if (random.Next(1) == 0)
{
for (int x = startX; x < endX; x++)
dungeon[x, previousRoom.CentreY] = 1;
for (int y = startY; y < endY + 1; y++)
dungeon[room.CentreX, y] = 1;
}
else
{
for (int y = startY; y < endY + 1; y++)
dungeon[previousRoom.CentreX, y] = 1;
for (int x = startX; x < endX; x++)
dungeon[x, room.CentreY] = 1;
}
}
previousRoom = room;
}
}
public override void Update()
{
}
}
}
</code></pre>
<p><strong>DungeonGenerator.cs</strong></p>
<pre><code>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace Roguelike
{
public abstract class DungeonGenerator
{
public const int TileWidth = 8;
public const int TileHeight = 8;
protected Random random;
protected int[,] dungeon;
protected int width;
protected int height;
public DungeonGenerator(int width, int height)
{
this.width = width;
this.height = height;
random = new Random();
dungeon = new int[width, height];
}
public abstract void Generate();
public abstract void Update();
public void Render(SpriteBatch spriteBatch, ContentManager content)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (dungeon[x, y] != 0)
spriteBatch.Draw(content.Load<Texture2D>(dungeon[x, y].ToString()), new Rectangle(x * TileWidth, y * TileHeight, TileWidth, TileHeight), Color.White);
}
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>I would make the random generator static and public to make it accessible from various classes (e.g. from rooms):</p>\n\n<pre><code>public abstract class DungeonGenerator\n{\n public static readonly Random Random = new Random();\n ...\n}\n</code></pre>\n\n<p>Then I would generalize the conc... | {
"AcceptedAnswerId": "202724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T19:35:16.700",
"Id": "200543",
"Score": "7",
"Tags": [
"c#",
"game",
"monogame"
],
"Title": "Simple dungeon generator"
} | 200543 |
<p>Given a graph and a starting vertex print the value of each vertex in a breadth first order.</p>
<p>Let's code out a general BFS algorithm printing each vertex's value in a BFS order. We are given a graph in the form of an adjacency list, as well as a starting vertex.</p>
<p>To analyze the complexity of a graph, we need to consider the number of vertices (V) and the number of Edges (E) as independent variables. Also, we need to consider the type of edge representation for the graph. We will go over the analysis for adjacency list.</p>
<pre class="lang-none prettyprint-override"><code>Pseudocode
1. Create a queue to hold neighbor vertices and add the start vertex.
2. Create a set to track visited vertices and add the start vertex.
3. While queue is not empty
4. Dequeue from the queue and set to current.
5. Loop through all the vertex's neighbors.
6. For each neighbor, check if the vertex has been visited.
7. If not visited, then add it to the queue and add mark it as visited.
8. Operate on current
9. Once the queue is empty, we have completed the BFS
</code></pre>
<p>Here's the code in JavaScript:</p>
<pre class="lang-js prettyprint-override"><code>function graphBFS(graph, start) {
let queue = new Queue(); // 1
let visited = new Set(); // 1
let current; // 1
let neighbors; // 1
queue.enqueue(start); // 1
visited.add(start); // 1
// while loop will run a total of V times
while (queue.length > 0) { // 1 (for break condition)
current = queue.dequeue(); // 1
neighbors = graph.neighbors(current); // 1 (for adjacency list)
// the for loop will run based on d (degree) on average is E/V
for (let i = 0; i < neighbors.length; i++) { // 1
if (!visited.has(neighbors[i]) { // 1
queue.enqueue(neighbors[i]); // 1
visited.add(neighbors[i]); // 1
}
// <-- operating on the current vertex will add additional time
}
}
}
</code></pre>
| [] | [
{
"body": "<h1>Code review</h1>\n<h2>Fail</h2>\n<p>You should ensure your code is at least able to be parsed before you ask for review. I will assume it an oversight (that even your code formater was glaringly pointing out) and review assuming the missing token.</p>\n<h2>Incomplete</h2>\n<p>As an exercise the r... | {
"AcceptedAnswerId": "200559",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T20:48:08.657",
"Id": "200548",
"Score": "0",
"Tags": [
"javascript",
"breadth-first-search"
],
"Title": "Print BFS implementation in JavaScript"
} | 200548 |
<p>Merge two sorted lists</p>
<pre><code># Input: lst1 {List}
# Input: lst2 {List}
# Output: {List}
#
# Example: merge([1, 4, 7], [2, 3, 6, 9]) => [1, 2, 3, 4, 6, 7, 9]
#
def merge(items1, items2):
# merge 2 list
# divide and conquer
# combine - step2
("\n"
" while left_index is not the length of left_array and right_index is not the length of right_array\n"
" if left_array[left_index] < right_array[right_index]\n"
" add left_array[left_index] to merged array\n"
" left_index + 1\n"
" else\n"
" add right_array[right_index] to merged_array\n"
" right_index + 1 ")
# if we've passed the end of either list, then extend the sorted list
# with what remains in the other
left_pointer = 0
right_pointer = 0
sorted_list = []
while len(sorted_list) < len(items1) + len(items2):
left_item = items1[left_pointer]
right_item = items2[right_pointer]
if left_item < right_item:
sorted_list.append(left_item)
left_pointer += 1
else:
sorted_list.append(right_item)
right_pointer += 1
if right_pointer >= len(items2):
sorted_list.extend(items1[left_pointer:])
break
if left_pointer >= len(items1):
sorted_list.extend(items2[right_pointer:])
break
return sorted_list
</code></pre>
<p>test cases that i am working on</p>
<pre><code>print('merge tests')
test_count = [0, 0]
def test():
results = merge([1, 4, 7], [2, 3, 6, 9])
return (len(results) == 7 and
results[0] == 1 and
results[1] == 2 and
results[2] == 3 and
results[3] == 4 and
results[4] == 6 and
results[5] == 7 and
results[6] == 9)
expect(test_count, 'should return [1, 2, 3, 4, 6, 7, 9] when merging [1, 4, 7]', test)
def test():
results = merge([], [2, 3, 6, 9])
return (len(results) == 4 and
results[0] == 2 and
results[1] == 3 and
results[2] == 6 and
results[3] == 9)
expect(test_count, 'should handle inputs when left argument is empty array', test)
def test():
results = merge([1, 4, 7], [])
return (len(results) == 3 and
results[0] == 1 and
results[1] == 4 and
results[2] == 7)
expect(test_count, 'should handle inputs when right argument is empty array', test)
def test():
results = merge([], [])
return len(results) == 0
expect(test_count, 'should handle two empty arrays as inputs', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
class TestObject(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
return self.x < other.x
def __str__(self):
return "LTO (%d, %d)" % (self.x, self.y)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T21:42:47.530",
"Id": "386149",
"Score": "0",
"body": "In the tests, I can't see any reason to avoid simple list equality: e.g. `results == [1,2,3,4,6,7,9]`"
}
] | [
{
"body": "<p>One obvious improvement is to clean up your tests. You could just test</p>\n\n<pre><code>results = merge([1, 4, 7], [2, 3, 6, 9])\nreturn results == [1, 2, 3, 4, 6, 7, 9]\n</code></pre>\n\n<p>Technically this also tests that <code>results</code> is a list, which is arguably an implementation detai... | {
"AcceptedAnswerId": "200568",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T21:00:53.620",
"Id": "200550",
"Score": "4",
"Tags": [
"python",
"unit-testing",
"mergesort"
],
"Title": "Merge two sorted lists in Python"
} | 200550 |
<p>Question: Merge k sorted Arrays</p>
<p>My main concerns about my code are:</p>
<ol>
<li><p>Performance: is it optimized and is my description of the time and complexity correct. How should I annotate the space and time complexity at every step of the code? </p></li>
<li><p>What effect do generators have on the time and space complexity?</p></li>
<li><p>Is my code self-documenting, modular, and readable and how can it be written better? </p></li>
</ol>
<p>Solution: </p>
<ol>
<li><p>convert the sorted arrays into a Set data structures O(N)</p></li>
<li><p>create a generator function which takes in the iterative values, converts them into the values type, while removing the first value as an argument to be passed to the resulting iterations.</p></li>
<li><p>I iterate over the remaining sets O(N)</p></li>
<li><p>I Use another generator function to merge the values O(N*N)-> O(N^2)</p></li>
<li><p>In the merge generator, I set three-pointers and iterate them over the
combined lengths of the two target arrays, the accumulated array setA with the next sequential array setB. I then iterate the ri pointer over the space of both arrays</p></li>
<li><p>In the merge generator, I check if setA pointer is > than the length of all possible setA, this leaves setB at its current pointer as the only viable solution set. I yeld its value inside the generator space. I also default to the pointer at SetB if the value at SetA is larger than that at SetB. Otherwise, the value at SetA is at a higher priority and I yield setA's value to the solution space of the generator at ri.</p></li>
<li><p>in the merge generator space setA is the accumulation placeholder </p></li>
<li><p>as I yield the pass in the mergeSortedSets generator I have to lazy load the yielded values</p></li>
</ol>
<p>because of that, I think the run-time complexity is at worst O(N^3) (I think this might be wrong) </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function* mergeSortedSets(iterative, sets = iterative.values(), pass = sets.next().value) {
for (let set of sets) {
yield pass = [...merge(pass, set)]
}
}
function* merge(setA, setB) {
for (let ri = 0, ai = 0, bi = 0; ri < setA.length + setB.length; ri++) {
if (ai >= setA.length || setA[ai] > setB[bi]) yield setB[bi++];
else yield setA[ai++];
}
}
let reduce = mergeSortedSets(new Set([
[1, 4, 5],
[1, 3, 4],
[2, 6],
[2, 3, 4]
].map(iterative => iterative)))
for (let result of reduce) {
console.log(result)
}</code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T21:51:31.643",
"Id": "200554",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"generator"
],
"Title": "Merge K sorted Arrays (JavaScript using generators)"
} | 200554 |
<p>I came across problem 54 on projecteuler.net and decided to give it a go using ReactJS. I have had Angular experience prior to this. I wrote a couple of fully tested components. I think that they only have one purpose each, but they're still very big. I did my best code-wise because it's also a project where I want to show off the things I learned from a programming book about clean code. Any feedback would be greatly appreciated. I'll start with the first component I created and end it with the last.</p>
<p>Playing card</p>
<pre><code>import React from 'react';
import propTypes from 'prop-types';
import { isNumeric } from '../../Helper';
import './Playing-Card.scss';
const cardSuites = {
D: 'diamonds',
S: 'spades',
H: 'hearts',
C: 'clubs',
};
const cardCourts = {
K: 'king',
J: 'jack',
Q: 'queen',
A: 'ace',
T: '10',
};
const cardValues = {
ace: '14',
king: '13',
queen: '12',
jack: '11',
};
const PlayingCard = ({ cardSymbol }) => {
const url = convertCardSymbolToUrl(cardSymbol);
return <img alt="playing-card" className="playing-card" src={url} />;
};
PlayingCard.propTypes = { cardSymbol: propTypes.string.isRequired };
export const convertCardSymbolToUrl = cardSymbol => `/cards/${getCardCourt(cardSymbol)}_of_${getCardSuite(cardSymbol)}.svg`;
export const getCardSuite = cardSymbol => cardSuites[cardSymbol[1]];
export const getCardCourt = cardSymbol => {
const courtSymbol = cardSymbol[0];
if (isNumeric(courtSymbol)) {
return String(courtSymbol);
}
return String(cardCourts[courtSymbol]);
};
export const getCardValue = cardCourt => {
if (isNumeric(cardCourt)) {
return Number(cardCourt);
}
return Number(cardValues[cardCourt]);
};
export default PlayingCard;
</code></pre>
<p>Hand</p>
<pre><code>import React from 'react';
import propTypes from 'prop-types';
import { generateUniqueKeysForItems } from '../../Helper';
import PlayingCard, { getCardCourt, getCardValue, getCardSuite } from '../Playing-Card/Playing-Card';
const Hand = ({ cards }) => {
let cardsArray = cards.split(' ');
cardsArray = generateUniqueKeysForItems(cardsArray);
return cardsArray.map(card => <PlayingCard key={card.id} cardSymbol={card.value} />);
};
Hand.propTypes = { cards: propTypes.string.isRequired };
export const calculateHandValue = cardsArray => {
let cardsFrequency = calculateCardsFrequency(cardsArray);
cardsFrequency = sortFrequencyDesc(cardsFrequency);
const individualCardValues = calculateIndividualCardValues(cardsFrequency);
let handValue = 9;
const cardsCombinations = [
hasRoyalFlush,
hasStraightFlush,
hasFourOfAKind,
hasFullHouse,
hasFlush,
hasStraight,
hasThreeOfAKind,
hasTwoPairs,
hasTwoOfAKind,
];
for (let i = 0; i < cardsCombinations.length; i += 1) {
const isCombinationValid = cardsCombinations[i];
if (isCombinationValid(cardsArray)) {
break;
}
handValue -= 1;
}
return [handValue, individualCardValues];
};
export const calculateIndividualCardValues = cardsFrequency =>
Array.from(cardsFrequency.keys()).map(key => getCardValue(key));
export const hasRoyalFlush = cardsArray => {
const cardCourtsRequired = ['10', 'jack', 'queen', 'king', 'ace'];
let qualifies = true;
if (!hasSameSuits(cardsArray)) {
return false;
}
cardsArray.forEach(card => {
const court = getCardCourt(card);
if (cardCourtsRequired.indexOf(court) === -1) {
qualifies = false;
}
});
return qualifies;
};
export const hasStraightFlush = cardsArray =>
hasSameSuits(cardsArray) && hasIncrementalCourts(cardsArray);
export const hasStraight = cardsArray => hasIncrementalCourts(cardsArray);
export const hasFlush = cardsArray => hasSameSuits(cardsArray);
export const hasFourOfAKind = cardsArray => hasXOfAKind(cardsArray, 4);
export const hasThreeOfAKind = cardsArray => hasXOfAKind(cardsArray, 3);
export const hasTwoOfAKind = cardsArray => hasXOfAKind(cardsArray, 2);
const hasXOfAKind = (cardsArray, x) => {
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(x) !== -1;
};
export const hasTwoPairs = cardsArray => {
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
let numberOfPairs = 0;
frequencyArray.forEach(frequencyNumber => {
if (frequencyNumber === 2) {
numberOfPairs += 1;
}
});
return numberOfPairs === 2;
};
export const hasFullHouse = cardsArray => {
const cardsFrequency = calculateCardsFrequency(cardsArray);
const frequencyArray = Array.from(cardsFrequency.values());
return frequencyArray.indexOf(3) !== -1 && frequencyArray.indexOf(2) !== -1;
};
export const hasSameSuits = cardsArray => {
const hasEqualSuits = (card1, card2) => getCardSuite(card1) === getCardSuite(card2);
for (let i = 1; i < cardsArray.length; i += 1) {
const card = cardsArray[i];
const previousCard = cardsArray[i - 1];
if (!hasEqualSuits(card, previousCard)) {
return false;
}
}
return true;
};
export const hasIncrementalCourts = cardsArray => {
const hasIncrementalCardValues = (card1, card2) =>
getCardValue(getCardCourt(card1)) + 1 === getCardValue(getCardCourt(card2));
const sortedCards = sortByCardValueAsc(cardsArray);
for (let i = 1; i < sortedCards.length; i += 1) {
const card = sortedCards[i];
const previousCard = sortedCards[i - 1];
if (!hasIncrementalCardValues(previousCard, card)) {
return false;
}
}
return true;
};
export const calculateCardsFrequency = cardsArray => {
const cardFrequency = new Map();
cardsArray.forEach(card => {
const court = String(getCardCourt(card));
if (cardFrequency.get(court) != null) {
cardFrequency.set(court, cardFrequency.get(court) + 1);
} else {
cardFrequency.set(court, 1);
}
});
return cardFrequency;
};
export const sortFrequencyDesc = cardsFrequency =>
new Map([...cardsFrequency.entries()].sort((a, b) => {
const aCardCourt = a[0];
const aFrequency = a[1];
const bCardCourt = b[0];
const bFrequency = b[1];
if (aFrequency < bFrequency) {
return 1;
}
if (aFrequency === bFrequency && getCardValue(aCardCourt) < getCardValue(bCardCourt)) {
return 1;
}
return -1;
}));
export const sortByCardValueAsc = cardsArray => {
cardsArray.sort((card1, card2) => {
const court1 = getCardCourt(card1);
const court2 = getCardCourt(card2);
if (getCardValue(court1) > getCardValue(court2)) {
return 1;
}
if (getCardValue(court1) < getCardValue(court2)) {
return -1;
}
return 0;
});
return cardsArray;
};
export default Hand;
</code></pre>
<p>Round</p>
<pre><code>import React from 'react';
import propTypes from 'prop-types';
import { connect } from 'react-redux';
import Hand, { calculateHandValue } from '../Hand/Hand';
import './Round.scss';
const Round = ({ cards, incrementScore }) => {
const playerHands = splitCards(cards);
if (playerHands[0] === '') {
return <div />;
}
const winner = determineWinner(playerHands[0], playerHands[1]);
incrementScore(`player${winner}`);
return (
<div className="round-root">
<div className={(winner === 1) ? 'winner' : ''}>
<Hand cards={playerHands[0]} />
</div>
<div className={(winner === 2) ? 'winner' : ''}>
<Hand cards={playerHands[1]} />
</div>
</div>
);
};
Round.propTypes = {
cards: propTypes.string.isRequired,
incrementScore: propTypes.func.isRequired,
};
const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({
incrementScore: playerName => {
dispatch({
type: 'INCREMENT_SCORE',
payload: {
name: playerName,
},
});
},
});
export const splitCards = cards => {
const playerHands = [];
playerHands.push(cards.substr(0, Math.ceil(cards.length / 2) - 1));
playerHands.push(cards.substr(Math.ceil(cards.length / 2)));
return playerHands;
};
export const determineWinner = (player1Cards, player2Cards) => {
const p1HandValue = calculateHandValue(player1Cards.split(' '));
const p2HandValue = calculateHandValue(player2Cards.split(' '));
let winner = compareFirstTuples(p1HandValue, p2HandValue);
if (winner === 0) {
winner = compareSecondTuples(p1HandValue, p2HandValue);
if (winner === 0) {
throw Error('No winner could be determined');
}
}
return winner;
};
export const compareFirstTuples = (p1HandValue, p2HandValue) => {
if (p1HandValue[0] === p2HandValue[0]) { return 0; }
return (p1HandValue[0] > p2HandValue[0]) ? 1 : 2;
};
export const compareSecondTuples = (p1HandValue, p2HandValue) => {
const p1Tuple = p1HandValue[1];
const p2Tuple = p2HandValue[1];
let winner = 0;
const minLength = Math.min(p1Tuple.length, p2Tuple.length);
for (let i = 0; i < minLength; i += 1) {
if (p1Tuple[i] > p2Tuple[i]) {
winner = 1;
break;
}
if (p1Tuple[i] < p2Tuple[i]) {
winner = 2;
break;
}
}
return winner;
};
export default connect(mapStateToProps, mapDispatchToProps)(Round);
</code></pre>
<p>Game-Room</p>
<pre><code>import React from 'react';
import propTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import './Game-Room.scss';
import { connect } from 'react-redux';
import Game from '../Game/Game';
import WinnerDetails from '../Winner-Details/Winner-Details';
const possibleSuits = ['D', 'S', 'H', 'C'];
const possibleCourts = ['2', '3', '4', '5', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
const GameRoom = ({ setMatches, matches, players, resetScore }) => {
const { player1, player2 } = players;
let winner = null;
if (player1.score > 0 || player1.score > 0) {
winner = (player1.score > player2.score)
? player1 : player2;
}
const readTextFile = event => {
const input = event.target;
const reader = new FileReader();
reader.onload = processGamesFile;
reader.onload = () => {
resetScore();
setMatches(processGamesFile(reader.result));
};
reader.readAsText(input.files[0]);
};
const processGamesFile = gamesFile => {
const retrievedMatches = gamesFile.split('\n');
retrievedMatches.pop();
return retrievedMatches;
};
return (
<div className="game-room-root">
<Button variant="contained" color="primary" className="main-button left">
<input type="file" onChange={event => { readTextFile(event); }} />
</Button>
<Button
variant="contained"
color="primary"
onClick={() => {
resetScore();
setMatches(generateMatches(100));
}}
className="main-button right"
>
Generate Games
</Button>
<WinnerDetails winner={winner} />
<Game matches={matches} />
</div>
);
};
GameRoom.propTypes = {
setMatches: propTypes.func.isRequired,
resetScore: propTypes.func.isRequired,
players: propTypes.shape({}).isRequired,
matches: propTypes.arrayOf(propTypes.string).isRequired,
};
const mapStateToProps = state => ({
matches: state.gamesReducer,
players: state.playerReducer,
});
const mapDispatchToProps = dispatch => ({
setMatches: games => {
dispatch({
type: 'SET_GAMES',
payload: games,
});
},
resetScore: () => {
dispatch({
type: 'RESET_SCORE',
});
},
});
export const generateMatches = numberOfGames => {
const games = [];
for (let i = 0; i < numberOfGames; i += 1) {
const round = generateRound();
games.push(round);
}
return games;
};
export const generateRound = () => {
let cards = '';
let numberOfCards = 0;
while (numberOfCards < 10) {
const card = createRandomCard();
if (cards.indexOf(card) === -1) {
cards += `${card} `;
numberOfCards += 1;
}
}
cards = cards.slice(0, -1);
return cards;
};
const createRandomCard = () => getRandomCourt() + getRandomSuit();
const getRandomSuit = () => possibleSuits[Math.floor(Math.random() * possibleSuits.length)];
const getRandomCourt = () => possibleCourts[Math.floor(Math.random() * possibleCourts.length)];
export default connect(mapStateToProps, mapDispatchToProps)(GameRoom);
</code></pre>
<p>Components Winner-detail and Game are emitted because they're small enough. Game is just a container for rounds.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T23:34:43.750",
"Id": "386160",
"Score": "0",
"body": "Please post a short problem description along with your question. Otherwise, it will be hard for us to judge your code properly with regards to correctness and suitability for th... | [
{
"body": "<p>I agree that specific questions we can answer would be helpful. That being said, a few comments:</p>\n\n<ul>\n<li><p>Some would disagree, but I'd separate the View/display code from the game code (model). You can build out all the mechanics of cards (GameRoom, Hand, PlayingCard, etc.) <em>without<... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T21:54:54.510",
"Id": "200555",
"Score": "0",
"Tags": [
"javascript",
"algorithm",
"playing-cards",
"react.js",
"redux"
],
"Title": "Playing cards with ReactJS"
} | 200555 |
<p>I'm pretty new to C, started learning it less than a month ago, the only language I had previous experience was Javascript.</p>
<p>Anyways, I wrote a library for dealing with CLI flags. It's not a serious project by any means, I wrote it for practice and fun.</p>
<p>It's composed of a source file and a header file (with declarations etc..). I'll list these functions then I'll try to describe them briefly. I didn't use array subscripting as I'm trying to gain a serious understanding of how pointers work etc...</p>
<p><code>libflagutil.c</code>:</p>
<pre><code>#include "../flagutil.h" //make sure definitions match declarations and protos etc..
#include "../butil.h" //terminal text styling
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool flag_present(int argc, char **argv, const char *flag) {
/* a single flag is defined as present IF:
- an arg that exactly matches the provided `flag` string is found
- an arg that exactly matches the provided `flag` string BUT includes an `=` (and optionally somed data)
after it is found
*/
bool present = false;
for(char **cur_flag = argv; cur_flag < argv + argc; cur_flag++) {
if(strncmp(flag, *cur_flag, strlen(flag)) == 0 && (*(*cur_flag + strlen(flag)) == '=' || *(*cur_flag + strlen(flag)) == '\0')) {
present = true;
}
}
return present;
}
const Flag *flag_get(int argc, char **argv, const char *flag) {
/* gets the value of the provided flag. flag must begin with 2 consecutive hyphens (`--`)
- value of the flag may be provided within the flag itself by providing an `=` and some value after it
- OR it may be provided in an argument after the said flag
- the function looks for the value in that order
- doesn't check if the flag itself exists. use flag_present prior to calling
this function.
*/
if(*flag != '-' || !(*(flag + 1))) {
printf("Invalid flag structure for flag " bold("%s") " passed to get_flag.\n", flag);
return NULL;
}
static Flag internal; //static buffer of last-fetched flag
for(char **cur_flag = argv; cur_flag < argv + argc; cur_flag++) {
if(strncmp(flag, *cur_flag, strlen(flag)) == 0) {
char *char_after_flag = *cur_flag + strlen(flag);
if(*char_after_flag == '=' && *(char_after_flag + 1) != '\0') {
internal.data = char_after_flag + 1;
internal.location = (const char **) cur_flag;
strncpy(internal.name, flag, strlen(flag) + 1);
} else if(cur_flag + 1 && **(cur_flag + 1) != '-') {
internal.data = *(cur_flag + 1);
internal.location = (const char **) cur_flag;
strncpy(internal.name, flag, strlen(flag) + 1);
}
}
}
return &internal;
}
void flag_startswith(int argc, char **argv, const char *start_string, Flag *storage) {
/* assumes that storage is large enough to accomodate all valid flags */
//TODO: handle `=` within flag_string, for now function doesn't work with those flags
for(char **flag = argv; flag < argv + argc; flag++) {
if(**flag != '-') {
continue;
} //First char isn't a `-`, skip arg
if(*(*flag + 1) == '-') {
if(strncmp(*flag + 2, start_string, strlen(start_string)) == 0) {
char flag_string[2 + strlen(*flag + 2) + 1];
strcpy(flag_string, "--");
strcpy(flag_string + 2, *flag + 2);
*storage = *f_get(flag_string);
}
} else {
if(strncmp(*flag + 1, start_string, strlen(start_string)) == 0) {
char flag_string[1 + strlen(*flag + 1) + 1];
strcpy(flag_string, "-");
strcpy(flag_string + 1, *flag + 1);
*storage = *f_get(flag_string);
}
}
storage++;
}
}
char *flag_nextarg(signed int argc, char **argv) {
//oversimplify fetching args from argv... (kinda useless)
static size_t counter = 0;
return *(argv + (counter++));
}
</code></pre>
<p><code>flagutil.h</code>:</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "./butil.h"
#pragma once
/*define these yourself if you'd like to use short version but use non-"standard"
names for main's 2 args
*/
#ifndef FLAGUTIL_ARGC_NAME
#define FLAGUTIL_ARGC_NAME argc
#endif
#ifndef FLAGUTIL_ARGV_NAME
#define FLAGUTIL_ARGV_NAME argv
#endif
/* expose functions as short versions taking less arguments, for easier usage */
#define f_present(s) flag_present(FLAGUTIL_ARGC_NAME, FLAGUTIL_ARGV_NAME, s)
#define f_get(s) flag_get(FLAGUTIL_ARGC_NAME, FLAGUTIL_ARGV_NAME, s)
#define f_startswith(s, g) flag_startswith(FLAGUTIL_ARGC_NAME, FLAGUTIL_ARGV_NAME, s, g);
#define f_nextarg() flag_nextarg(FLAGUTIL_ARGC_NAME, FLAGUTIL_ARGV_NAME)
struct flag {
char name[100];
const char *data;
const char **location; //actual pointer within argv
};
typedef struct flag Flag;
//prototypes:
bool flag_present(int, char **, const char *);
const Flag *flag_get(int, char **, const char *);
void flag_startswith(int, char **, const char *, Flag *);
char *flag_easyArg(int, char **);
</code></pre>
<p>Currently all of the functions accept <code>argc</code> and <code>argv</code> as their first 2 arguments, but <code>flagutil.h</code> exposes these functions as macros with shorter names taking only the necessary arguments, and automatically feeding <code>argc</code> and <code>argv</code> (also defined as macros for compatibility in case of non-standard parameter names inside <code>main</code>). </p>
<p>All of the functions (except <code>flag_startswith</code>) take flag names in the form <code>-flagName</code> or <code>--flagName</code>. </p>
<p>Data is passed to flags in the form of <code>-flagName=DATA</code> or <code>-flagName DATA</code>. </p>
<p><code>bool flag_present(...)</code>: Returns <code>true</code> if provided flag exists within <code>argv</code>, false otherwise. </p>
<p><code>const Flag *flag_get(...)</code>: Returns a pointer to an internal static struct which holds data about a certain flag. The actual struct is defined in <code>flagutil.h</code> and holds the name of the flag, its data (if it has any) and a pointer to its location inside of <code>argv</code>.</p>
<p><code>void flag_startswith(...)</code>: Stores struct representations of all flags that start with <code>start_string</code> inside of provided array.</p>
<p><code>char *flag_nextarg(...)</code>: Pretty pointless, wrote it for fun.</p>
<p>I realize some of these functions are unsafe, sometimes broken etc.. but so far they get the job done and I'll be looking to improve them further. I'm looking for general advice, best practices, stuff to avoid, etc... I've tested it only with GCC and linux64 and it compiles without any warnings (<code>-Wall, -Wextra</code>).</p>
<p>Please disregard the use of <code>bil()</code> and <code>bold()</code>, they're macros for styling text inside the terminal..</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T11:59:22.857",
"Id": "386229",
"Score": "2",
"body": "Few more things but something eye catching is that `static` field. Imagine you're writing a `curl` clone and you have `struct flag* method = flag_get(argc, argv, \"X\"); struct f... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T21:55:42.147",
"Id": "200556",
"Score": "3",
"Tags": [
"c",
"library"
],
"Title": "Library for managing CLI flags"
} | 200556 |
<p>I'm a programming newbie. In fact, this is my second code ever (after Hello World). I did a lot of reading actually, here on Stack Overflow, and other websites. I would like to know if there's a way to further improve this code.</p>
<pre><code>#include <iostream>
#include <string>
using std::cout; using std::cin;
int main()
{
cout << "Calculator..... \n";
cout << "Type '3a3'to exit... \n";
double a=0 ,b=0;
char op = 'a'; //operator // 'a' is the exit operator, the value of the integers doesn't matter
int ch = 0; //while loop checker
do
{
cin >> a >> op >> b;
if (op == '/' && b == 0)
{
cout << "Division By Zero, Please Retry \n" ;
goto retry;
}
switch (op)
{
case '+':
cout << a << " + "<< b << " = " << a+b << "\n";
ch = 0 ;
break;
case '-':
cout << a << " - "<< b << " = " << a-b << "\n";
ch = 0 ;
break;
case 'x':
case '*':
cout << a << " * "<< b << " = " << a*b << "\n";
ch = 0 ;
break;
case '/':
cout << a << " / "<< b << " = " << a/b << "\n";
ch = 0;
break;
case 'a':
ch = 1;
break;
default:
ch = 0;
cout << "Invalid operator, Please retry \n";
}
retry: ;
}while (ch != 1);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T18:29:26.300",
"Id": "386167",
"Score": "1",
"body": "Side note: There isn't much you can do to optimize this. Whenever you are taking input from a user, there is no way the user can type fast enough to keep up with the computer. No... | [
{
"body": "<p>Some advice on best practice:</p>\n\n<ul>\n<li>Declare (and define) variables as close as possible to the location they're used.</li>\n<li>Use expressive names for variables, functions and types.</li>\n<li>Do proper error handling, the user can't be trusted.</li>\n<li>Use appropriate data types.</... | {
"AcceptedAnswerId": "200571",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-29T18:04:17.670",
"Id": "200560",
"Score": "4",
"Tags": [
"c++",
"beginner",
"calculator"
],
"Title": "Simple C++ calculator"
} | 200560 |
<p>I've written a Vim function that formats the file using shfmt. I'd like to know if there is a way I can improve this script.</p>
<p>I am bothered by the fact that I can't think of a way to do this without editing the file in the subprocess and reloading the file. Is there a way to do the equivalent of <code>%!shfmt -options</code>?</p>
<pre><code>if exists("g:loaded_shfmt") || &compatible || ! executable('shfmt')
finish
endif
let s:save_cpoptions = &cpoptions
set cpoptions&vim
let s:switches = join(['-w', '-s', '-i', '2', '-bn', '-ci', '-sr'])
function! s:shFormat()
let l:filename = @%
let l:out = system('shfmt ' . s:switches . ' ' . l:filename)
edit!
endfunction
nnoremap <silent> <Leader>fb :call <SID>shFormat()<CR>
let &cpoptions = s:save_cpoptions
let g:loaded_shfmt = 1
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T00:36:36.670",
"Id": "200562",
"Score": "2",
"Tags": [
"formatting",
"child-process",
"vimscript"
],
"Title": "VIm function that runs file through shfmt"
} | 200562 |
<p>I'm trying to have a custom WPF control whose content is defined in XAML but avoiding the use of a <code>UserControl</code>. This is because a UserControl makes it impossible to add <code>x:Name</code> to its content: <a href="https://stackoverflow.com/questions/751325/how-to-create-a-wpf-usercontrol-with-named-content/3413382">https://stackoverflow.com/questions/751325/how-to-create-a-wpf-usercontrol-with-named-content/3413382</a></p>
<p>My files are laid out like this:</p>
<pre><code>.
│ App.config
│ App.xaml
│ App.xaml.cs
│ MainWindow.xaml
│ MainWindow.xaml.cs
│ WpfScratch.csproj
│
├───bin
│ ├───Debug
│ │ │ WpfScratch.exe
│ │ │ WpfScratch.exe.config
│ │ │ WpfScratch.pdb
│ │ │
│ │ └───Controls
│ └───Release
├───Controls
. MyPanel.cs
. MyPanel.xaml
</code></pre>
<p>and the source of the relevant ones is:</p>
<h3><code>MyPanel.cs</code></h3>
<pre><code>public class MyPanel : Control
{
static MyPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyPanel), new FrameworkPropertyMetadata(typeof(MyPanel)));
}
public MyPanel()
{
var templateUri = new Uri("/WpfScratch;component/Controls/MyPanel.xaml", UriKind.Relative);
Template = (ControlTemplate) Application.LoadComponent(templateUri);
}
public static readonly DependencyProperty BodyProperty = DependencyProperty.Register("Body", typeof(object), typeof(MyPanel), new PropertyMetadata(default(object)));
public object Body
{
get => GetValue(BodyProperty);
set => SetValue(BodyProperty, value);
}
public static readonly DependencyProperty FooterProperty = DependencyProperty.Register("Footer", typeof(object), typeof(MyPanel), new PropertyMetadata(default(object)));
public object Footer
{
get => GetValue(FooterProperty);
set => SetValue(FooterProperty, value);
}
}
</code></pre>
<h3><code>MyPanel.xaml</code></h3>
<pre><code><ControlTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfScratch.Controls"
TargetType="local:MyPanel" >
<DockPanel LastChildFill="True" x:Name="Content">
<Border BorderThickness="2"
BorderBrush="Aqua"
DockPanel.Dock="Bottom">
<ContentPresenter x:Name="Footer"
Content="{Binding Footer, RelativeSource={RelativeSource TemplatedParent}}"
Margin="0, 10" />
</Border>
<Border BorderThickness="2"
BorderBrush="Magenta">
<ContentPresenter x:Name="Body"
Content="{Binding Body, RelativeSource={RelativeSource TemplatedParent}}" />
</Border>
</DockPanel>
</ControlTemplate>
</code></pre>
<h3><code>MainWindow.xaml</code></h3>
<pre><code><Window x:Class="WpfScratch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfScratch"
xmlns:controls="clr-namespace:WpfScratch.Controls"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<controls:MyPanel x:Name="HelloWorldPanel">
<controls:MyPanel.Body>
<Label x:Name="HelloLabel">Hello!</Label>
</controls:MyPanel.Body>
<controls:MyPanel.Footer>
<Label x:Name="WorldLabel">World!</Label>
</controls:MyPanel.Footer>
</controls:MyPanel>
</Window>
</code></pre>
<hr>
<p>My main concern is the loading of the XAML file, i.e.:</p>
<pre><code> var templateUri = new Uri("/WpfScratch;component/Controls/MyPanel.xaml", UriKind.Relative);
Template = (ControlTemplate) Application.LoadComponent(templateUri);
</code></pre>
<ol>
<li>Is <code>Application.Load()</code> the way to go? UWP seems to deprecate it in favour of <code>XAMLReader.Load()</code>, but I'm not sure how I would get the correct stream for that. I tried digging into the sources of Application.LoadComponent and there's some logic involved with processing pack URIs</li>
<li>The URI is a hardcoded mouthful and seems not very resilient to refactoring. Is there a terse way of saying "hey my XAML file is right next to this one"?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T11:01:13.187",
"Id": "386220",
"Score": "0",
"body": "I can't see where the name is being used. Am I overlooking something? Is it used in code which you haven't included in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0... | [
{
"body": "<p>The conventional way of attaching default template to custom control is to specify default style inside a special resource dictionary. For this approach to work three conditions should be met:</p>\n\n<p>1) Resource dictionary should be located at <code>Themes/Generic.xaml</code>. There you should ... | {
"AcceptedAnswerId": "200577",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T08:51:44.537",
"Id": "200572",
"Score": "5",
"Tags": [
"c#",
"wpf",
"xaml"
],
"Title": "Loading a XAML file related to a control programmatically?"
} | 200572 |
<p>I've created a service that connects to Dropbox and makes it possible to download and upload files, create and list folders and remove file or folder.</p>
<p>Full code is available on GitHub: <a href="https://github.com/MajewskiKrzysztof/spring-boot-dropbox" rel="nofollow noreferrer">https://github.com/MajewskiKrzysztof/spring-boot-dropbox</a></p>
<p><strong>DropboxConfiguration</strong></p>
<pre><code>@Configuration
class DropboxConfiguration {
@Value("${dropbox.accessToken}")
private String accessToken;
@Bean
public DbxClientV2 dropboxClient() {
DbxRequestConfig config = DbxRequestConfig.newBuilder("example-app").build();
return new DbxClientV2(config, accessToken);
}
}
</code></pre>
<p><strong>DropboxServiceImpl</strong></p>
<pre><code>@Service
class DropboxServiceImpl implements DropboxService {
private final DbxClientV2 client;
public DropboxServiceImpl(DbxClientV2 client) {
this.client = client;
}
@Override
public InputStream downloadFile(String filePath) throws DropboxException {
return handleDropboxAction(() -> client.files().download(filePath).getInputStream(),
String.format("Error downloading file: %s", filePath));
}
@Override
public FileMetadata uploadFile(String filePath, InputStream fileStream) throws DropboxException {
return handleDropboxAction(() -> client.files().uploadBuilder(filePath).uploadAndFinish(fileStream),
String.format("Error uploading file: %s", filePath));
}
@Override
public CreateFolderResult createFolder(String folderPath) {
return handleDropboxAction(() -> client.files().createFolderV2(folderPath), "Error creating folder");
}
@Override
public FolderMetadata getFolderDetails(String folderPath) throws DropboxException {
return getMetadata(folderPath, FolderMetadata.class, String.format("Error getting folder details: %s", folderPath));
}
@Override
public FileMetadata getFileDetails(String filePath) throws DropboxException {
return getMetadata(filePath, FileMetadata.class, String.format("Error getting file details: %s", filePath));
}
@Override
public ListFolderResult listFolder(String folderPath, Boolean recursiveListing, Long limit) throws DropboxException {
ListFolderBuilder listFolderBuilder = client.files().listFolderBuilder(folderPath);
if (Objects.nonNull(recursiveListing)) {
listFolderBuilder.withRecursive(recursiveListing);
}
if (Objects.nonNull(limit)) {
listFolderBuilder.withLimit(limit);
}
return handleDropboxAction(listFolderBuilder::start, String.format("Error listing folder: %s", folderPath));
}
@Override
public ListFolderResult listFolderContinue(String cursor) throws DropboxException {
return handleDropboxAction(() -> client.files().listFolderContinue(cursor), "Error listing folder");
}
@Override
public void deleteFile(String filePath) {
handleDropboxAction(() -> client.files().deleteV2(filePath), String.format("Error deleting file: %s", filePath));
}
@Override
public void deleteFolder(String folderPath) {
handleDropboxAction(() -> client.files().deleteV2(folderPath), String.format("Error deleting folder: %s", folderPath));
}
private <T> T handleDropboxAction(DropboxActionResolver<T> action, String exceptionMessage) {
try {
return action.perform();
} catch (Exception e) {
String messageWithCause = String.format("%s with cause: %s", exceptionMessage, e.getMessage());
throw new DropboxException(messageWithCause, e);
}
}
@SuppressWarnings("unchecked")
private <T> T getMetadata(String path, Class<T> type, String message) {
Metadata metadata = handleDropboxAction(() -> client.files().getMetadata(path),
String.format("Error accessing details of: %s", path));
checkIfMetadataIsInstanceOfGivenType(metadata, type, message);
return (T) metadata;
}
private <T> void checkIfMetadataIsInstanceOfGivenType(Metadata metadata, Class<T> validType, String exceptionMessage) {
boolean isValidType = validType.isInstance(metadata);
if (!isValidType) {
throw new DropboxException(exceptionMessage);
}
}
}
</code></pre>
<p><strong>DropboxIntTest</strong></p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootSharepointRestApplication.class)
public class DropboxIntTest {
private static final String TEST_FOLDER_PATH = "/Test Folder";
private static final String TEST_FILE_PATH = String.format("%s/%s", TEST_FOLDER_PATH, "testFile.txt");
private static final Integer TEST_FILE_SIZE = 17;
@Autowired
private DropboxService dropboxService;
@Rule
public final ExpectedException exceptions = ExpectedException.none();
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void createTestFolder() throws Exception {
dropboxService.createFolder(TEST_FOLDER_PATH);
File tempUploadFile = temporaryFolder.newFile("testFile.txt");
FileUtils.writeStringToFile(tempUploadFile, "test file content", "UTF-8");
String testFilePath = String.format("%s/%s", TEST_FOLDER_PATH, "testFile.txt");
dropboxService.uploadFile(testFilePath, new FileInputStream(tempUploadFile));
}
@After
public void deleteTestFolder() {
dropboxService.deleteFolder(TEST_FOLDER_PATH);
}
@Test
public void downloadFile_shouldReturnNotEmptyInputStream() throws Exception {
InputStream inputStream = dropboxService.downloadFile(TEST_FILE_PATH);
assertThat(inputStream.available()).isEqualTo(TEST_FILE_SIZE);
}
@Test
public void downloadFile_shouldThrowExceptionIfFileNotExists() {
exceptions.expect(DropboxException.class);
dropboxService.downloadFile("not-existing-file");
}
@Test
public void uploadFile_shouldReturnUploadedFileDetails() throws Exception {
File tempUploadFile = temporaryFolder.newFile("teamLogo.png");
String filePath = String.format("%s/%s", TEST_FOLDER_PATH, tempUploadFile.getName());
FileMetadata fileMetadata = dropboxService.uploadFile(filePath, new FileInputStream(tempUploadFile));
assertThat(fileMetadata.getId()).isNotBlank();
}
@Test
public void uploadFile_shouldCreateFolderIfNotExists() throws Exception {
File tempUploadFile = temporaryFolder.newFile("teamLogo.png");
String filePath = String.format("%s/%s/%s", TEST_FOLDER_PATH, "not existing folder", tempUploadFile.getName());
dropboxService.uploadFile(filePath, new FileInputStream(tempUploadFile));
FolderMetadata folderDetails = dropboxService
.getFolderDetails(String.format("%s/%s", TEST_FOLDER_PATH, "not existing folder"));
assertThat(folderDetails.getId()).isNotBlank();
}
@Test
public void createFolder_shouldCreateFolder() {
String folderPath = String.format("%s/%s", TEST_FOLDER_PATH, "new folder");
CreateFolderResult folder = dropboxService.createFolder(folderPath);
FolderMetadata folderDetails = dropboxService.getFolderDetails(folderPath);
assertThat(folderDetails.getId()).isNotBlank();
assertThat(folderDetails.getId()).isEqualToIgnoringCase(folder.getMetadata().getId());
}
@Test
public void createFolder_shouldThrowExceptionIfFolderAlreadyExists() {
String folderPath = String.format("%s/%s", TEST_FOLDER_PATH, "new folder");
dropboxService.createFolder(folderPath);
exceptions.expect(DropboxException.class);
dropboxService.createFolder(folderPath);
}
@Test
public void getFolderDetails_shouldReturnFolderDetails() {
FolderMetadata folderDetails = dropboxService.getFolderDetails(TEST_FOLDER_PATH);
assertThat(folderDetails.getId()).isNotBlank();
assertThat(folderDetails.getName()).isNotBlank();
assertThat(folderDetails.getPathDisplay()).isNotBlank();
}
@Test
public void getFolderDetails_shouldThrowExceptionIfFolderNotExists() {
exceptions.expect(DropboxException.class);
dropboxService.getFolderDetails("/not existing folder");
}
@Test
public void getFileDetails_shouldReturnFileDetails() {
FileMetadata fileDetails = dropboxService.getFileDetails(TEST_FILE_PATH);
assertThat(fileDetails.getId()).isNotBlank();
assertThat(fileDetails.getPathDisplay()).isNotBlank();
assertThat(fileDetails.getName()).isNotBlank();
assertThat(fileDetails.getSize()).isEqualTo(TEST_FILE_SIZE.longValue());
assertThat(fileDetails.getServerModified()).isNotNull();
assertThat(fileDetails.getServerModified()).isBefore(new Date());
}
@Test
public void getFileDetails_shouldThrowExceptionIfFileNotExists() {
exceptions.expect(DropboxException.class);
dropboxService.getFileDetails("/not-existing-file.pdf");
}
@Test
public void listFolder_shouldReturnFolderItems() throws Exception {
File tempUploadFile1 = temporaryFolder.newFile("testFile2.txt");
FileUtils.writeStringToFile(tempUploadFile1, "test file content", "UTF-8");
String testFilePath1 = String.format("%s/%s", TEST_FOLDER_PATH, "testFile2.txt");
dropboxService.uploadFile(testFilePath1, new FileInputStream(tempUploadFile1));
File tempUploadFile2 = temporaryFolder.newFile("testFile3.txt");
FileUtils.writeStringToFile(tempUploadFile2, "test file content", "UTF-8");
String testFilePath2 = String.format("%s/%s/%s", TEST_FOLDER_PATH, "inner folder", "testFile3.txt");
dropboxService.uploadFile(testFilePath2, new FileInputStream(tempUploadFile2));
ListFolderResult listFolderResult = dropboxService.listFolder(TEST_FOLDER_PATH, true, 10L);
assertThat(listFolderResult.getEntries()).hasSize(5);
List<FileMetadata> files = listFolderResult.getEntries().stream()
.filter(entity -> entity instanceof FileMetadata)
.map(entity -> (FileMetadata) entity)
.collect(Collectors.toList());
assertThat(files).hasSize(3);
List<FolderMetadata> folders = listFolderResult.getEntries().stream()
.filter(entity -> entity instanceof FolderMetadata)
.map(entity -> (FolderMetadata) entity)
.collect(Collectors.toList());
assertThat(folders).hasSize(2);
}
@Test
public void listFolder_shouldTrowExceptionIfFolderNotExists() {
exceptions.expect(DropboxException.class);
dropboxService.listFolder("/not existing folder", true, 10L);
}
@Test
public void listFolderContinue_shouldListNextPathOfItems() throws Exception {
File tempUploadFile = temporaryFolder.newFile("testFile2.txt");
FileUtils.writeStringToFile(tempUploadFile, "test file content", "UTF-8");
String testFilePath1 = String.format("%s/%s", TEST_FOLDER_PATH, "testFile2.txt");
dropboxService.uploadFile(testFilePath1, new FileInputStream(tempUploadFile));
ListFolderResult listFolderResult = dropboxService.listFolder(TEST_FOLDER_PATH, false, 1L);
assertThat(listFolderResult.getEntries()).hasSize(1);
String cursor = listFolderResult.getCursor();
listFolderResult = dropboxService.listFolderContinue(cursor);
assertThat(listFolderResult.getEntries()).hasSize(1);
cursor = listFolderResult.getCursor();
listFolderResult = dropboxService.listFolderContinue(cursor);
assertThat(listFolderResult.getEntries()).hasSize(0);
}
@Test
public void listFolderContinue_shouldThrowExceptionIfWrongCursorProvided() {
exceptions.expect(DropboxException.class);
dropboxService.listFolderContinue(UUID.randomUUID().toString());
}
@Test
public void deleteFile_shouldDeleteFile() {
FileMetadata fileDetails = dropboxService.getFileDetails(TEST_FILE_PATH);
assertThat(fileDetails.getId()).isNotBlank();
dropboxService.deleteFile(TEST_FILE_PATH);
exceptions.expect(DropboxException.class);
dropboxService.getFileDetails(TEST_FILE_PATH);
}
@Test
public void deleteFile_shouldThrowExceptionIfFileNotExists() {
exceptions.expect(DropboxException.class);
dropboxService.deleteFolder("/not-existing-file");
}
@Test
public void deleteFolder_shouldDeleteFolder() {
String testFolder = String.format("%s/%s", TEST_FOLDER_PATH, "test folder");
dropboxService.createFolder(testFolder);
FolderMetadata folderDetails = dropboxService.getFolderDetails(testFolder);
assertThat(folderDetails.getId()).isNotBlank();
dropboxService.deleteFolder(testFolder);
exceptions.expect(DropboxException.class);
dropboxService.getFolderDetails(testFolder);
}
@Test
public void deleteFolder_shouldThrowExceptionIfFolderNotExists() {
exceptions.expect(DropboxException.class);
dropboxService.deleteFolder("/not-existing-folder");
}
}
</code></pre>
<p><strong>DropboxException</strong></p>
<pre><code>public class DropboxException extends RuntimeException {
public DropboxException(String message) {
super(message);
}
public DropboxException(String message, Exception cause) {
super(message, cause);
}
}
</code></pre>
<p><strong>DropboxActionResolver</strong></p>
<pre><code>@FunctionalInterface
interface DropboxActionResolver<T> {
T perform() throws Exception;
}
</code></pre>
<p>What do you think of it?</p>
| [] | [
{
"body": "<p>For the most part it looks fine. There are a few parts that may be changed. For example, I think that the handle <code>handleDropboxAction</code> method and the usage of the <code>DropboxActionResolver</code> functional interface might be a bit of an overkill. </p>\n\n<p>You could achieve the exac... | {
"AcceptedAnswerId": "200584",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T10:25:47.757",
"Id": "200576",
"Score": "2",
"Tags": [
"java",
"spring",
"junit"
],
"Title": "Dropbox Java Spring Boot connector"
} | 200576 |
<p>I have been starting to learn MVVM to give my WPF projects better structure.</p>
<p>I have to sample classes, <code>DeviceModel</code> and <code>DeviceViewModel</code>. Currently it is set up so that the model is exposed as a property within the view model. The model can then be bound to directly in the view.</p>
<pre><code>public DeviceModel Device
{
get { return device; }
set
{
device = value;
OnPropertyChanged();
}
}
</code></pre>
<p>I am looking for feedback to taking this approach over alternative approaches in MVVM. Specifically more traditional approaches such as exposing each of the model's properties as properties within the view model that then just update the values stored in the model.</p>
<p>An example of this would look like the following.</p>
<pre><code>public string DeviceName
{
get {return device.DeviceName; }
set
{
device.DeviceName = value;
OnPropertyChanged();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T07:42:59.997",
"Id": "386348",
"Score": "0",
"body": "I'm afraid I do not have enough rep to vote to take this question off hold but I believe I have edited the question so that it meets site requirements"
}
] | [
{
"body": "<p>Models typically do not implement <code>INotifyPropertyChanged</code> interface. So binding directly to model properties has two main consequences:</p>\n\n<p>1) <a href=\"https://blog.jetbrains.com/dotnet/2014/09/04/fighting-common-wpf-memory-leaks-with-dotmemory/\" rel=\"nofollow noreferrer\">It ... | {
"AcceptedAnswerId": "200586",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T13:09:00.210",
"Id": "200581",
"Score": "-1",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "Model Exposure with MVVM"
} | 200581 |
<p>This is my first nontrivial multi-threaded program. It recursively searches through a tree (<code>haystack</code>) to find the leaf where <code>needle = true</code>. It implements a thread pool and allows threads to exit early when another thread finds the answer.</p>
<p>It's worth noting that when using more than the main thread the program runs ~30 times slower, though I don't think this is due to something wrong in my code, just that threads are not really suited to this problem</p>
<p>I am especially interested in how well my code handles the threading aspect of the problem, thanks for having a look</p>
<pre><code>#include <vector>
#include <random>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <list>
#include <thread>
class haystack_search;
class haystack {
private:
friend haystack_search;
static std::mt19937 rng;
haystack * left;
haystack * right;
int depth;
bool needle;
public:
haystack(int layers, bool has_needle) {
if(layers > 0) {
depth = layers;
//if this haystack has the needle, a rondom side gets the needle
bool which = rng() & 0x01;
left = new haystack(layers - 1, which ? has_needle : 0);
right = new haystack(layers - 1, which ? 0 : has_needle);
needle = 0;
} else {
depth = 0;
left = nullptr;
right = nullptr;
needle = has_needle;
}
}
haystack(const haystack&) = delete;
haystack(haystack&& steal) {
right = steal.right;
left = steal.left;
rng = std::move(steal.rng);
needle = steal.needle;
depth = steal.depth;
steal.right = nullptr;
steal.left = nullptr;
steal.depth = 0;
}
~haystack() {
if(left != nullptr) {
delete left;
}
if (right != nullptr) {
delete right;
}
}
bool get(int index) {
if(depth > 0) {
//go right if the correct order bit is set (highest bit at top level, lowest bit at low level)
return (index >> (depth - 1)) & 0x01 ? right->get(index) : left->get(index);
} else {
return needle;
}
}
};
std::mt19937 haystack::rng;
class haystack_search {
private:
struct request_info {
haystack * hay;
int index;
};
std::atomic<bool> needle_found;
std::atomic<int> needle_index;
std::atomic<bool> kill_switch;
std::vector<std::thread> pool;
std::atomic<int> available_threads;
std::atomic<int> max_threads;
std::mutex recieve_mutex;
std::mutex requests_mutex;
std::condition_variable receive;
std::list<request_info> requests;
void thread_body() {
std::unique_lock<std::mutex> lock(recieve_mutex);
while (1) {
receive.wait(lock, [this](){
std::unique_lock<std::mutex> req_lock(requests_mutex);
return !requests.empty();
});
if(kill_switch)
break;
std::unique_lock<std::mutex> req_lock(requests_mutex);
haystack * hay = requests.front().hay;
int index = requests.front().index;
requests.pop_front();
req_lock.unlock();
lock.unlock();
search_branch(hay, index);
lock.lock();
++available_threads;
}
}
int call_thread(haystack * hay, int index) {
std::unique_lock<std::mutex> lock(recieve_mutex);
if(available_threads > 0) {
--available_threads;
std::unique_lock<std::mutex> req_lock(requests_mutex);
requests.push_back({hay,index});
req_lock.unlock();
receive.notify_one();
return 1;
} else {
return 0;
}
}
void search_branch(haystack * hay, int index) {
if(needle_found) {
return;
}
if(hay->depth == 0) {
if(hay->needle) {
needle_found = true;
needle_index = index;
}
return;
}
if(!call_thread(hay->right, (index << 1) + 1)) {
//if right, low bit should be set
search_branch(hay->right, (index << 1) + 1);
}
//if left, low bit should be cleared
search_branch(hay->left, (index << 1));
}
public:
haystack_search(const haystack_search&) = delete;
haystack_search(int max_thread_count) {
max_threads = max_thread_count;
available_threads = max_thread_count;
kill_switch = false;
for(int i = 0; i < max_thread_count; ++i) {
pool.push_back(std::thread(thread_body,this));
}
}
~haystack_search() {
std::unique_lock lock(recieve_mutex);
kill_switch = true;
std::unique_lock<std::mutex> req_lock(requests_mutex);
requests.push_back({0,0});//dummy
req_lock.unlock();
lock.unlock();
receive.notify_all();
for(std::thread& t : pool) {
t.join();
}
}
int search(haystack * hay) {
needle_found = false;
search_branch(hay, 0);
while(available_threads != max_threads) {
//wait until all threads are completed
std::this_thread::yield();
}
if(needle_found) {
return needle_index;
} else {
return -1;
}
}
};
</code></pre>
<p>This is a sample main that uses the code</p>
<pre><code>#include <iostream>
#include <chrono>
#include <cassert>
int main(int argc, char ** argv) {
int thread_count = 0;
if(argc == 2) {
try {
thread_count = std::stoi(argv[1]);
} catch (const std::exception& e) {
std::cout << "could not parse number of threads";
return 1;
}
} else {
std::cout << "invalid number of arguments (input number of threads)";
return 1;
}
using clock = std::chrono::high_resolution_clock;
clock::time_point start;
clock::time_point end;
std::vector<haystack*> hays;
for(size_t i = 0; i < 100; ++i) {
haystack* to_add = new haystack(14, 1);
hays.push_back(to_add);
}
std::cout << "starting " << thread_count + 1 << "-threaded search...\n";
haystack_search hsN(thread_count);
start = clock::now();
for(size_t i = 0; i < hays.size(); ++i) {
int index = hsN.search(hays[i]);
assert(hays[i]->get(index));
}
end = clock::now();
std::cout << "finished with time " << (float)(end - start).count()*clock::duration::period::num/clock::duration::period::den << "\n";
return 0;
}
</code></pre>
| [] | [
{
"body": "<h3>Overall Organization</h3>\n<p>It seems to me, that <code>haystack_search</code> is really at least three fundamentally different kinds of things, all rolled into one.</p>\n<p>One is the logic for doing the search. That probably should be in this class.\nThe second is a thread pool manager. That s... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T13:28:23.530",
"Id": "200582",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"tree"
],
"Title": "Multi-threaded tree search"
} | 200582 |
<p>I recently finished writing an HoloLens proof-of-concept program. It involves generating a user interface based on a connection with an OPC server. OPC involves industrial PLCs, one or more PLCs send their data to an OPC server, and the OPC-client connects and process all the information in the form of JSON.</p>
<p>An example is this:</p>
<pre><code>string json = "{\"PC_Station\": [{\"PLC_1\": {\"DB1\": {\"test123\": 30}, \"STOP\": false, \"START\": true, \"Start_1\": false, \"Stop_1\": true, \"Led1\": false, \"Led2\": false, \"Led3\": false, \"Counter\": 3880, \"Sliderval\": 60}}]}";
</code></pre>
<p>The code I've made generates a canvas with a panel. All the variables inside the JSON code get added to the panel in the form of a UI/Image. The function <code>updateTags()</code> continuously updates the data that gets sent using UDP. It functions like I want it to, but I'm wondering if there's a way to reduce the amount of code.</p>
<pre><code>using UnityEngine;
using System;
using System.IO;
using System.Text;
using System.Linq;
using HoloToolkit.Unity;
using System.Collections.Generic;
using UnityEngine.UI;
using Newtonsoft.Json;
using System.Collections;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
#if !UNITY_EDITOR
using Windows.Networking.Sockets;
using Windows.Networking.Connectivity;
using Windows.Networking;
#endif
public class UDPCommunication : Singleton<UDPCommunication>
{
// Connection variables
private string port = "8000";
private string externalIP = "172.16.24.251";
private string externalPort = "8001";
public static int size = 0;
public static List<Dictionary<string, string>> abc = new List<Dictionary<string, string>>();
public static List<string> varz;
public GameObject mainGameobject;
public GameObject upd1;
public GameObject upd2;
public GameObject upd3;
public GameObject upd4;
public GameObject canvas;
public GameObject Panel;
public GameObject image;
public GameObject imagetext;
public GameObject numbertext;
public Image testimg;
private GameObject getImageTags;
private GameObject getNumberTags;
private GameObject[] canvases;
private GameObject[] panels;
private GameObject[] tiles;
private GameObject[] texts;
private float scaler = 0.0125f;
// UI/Text elements
const string TurnOn = "on";
private uint sliderVal;
// Sets up a Queue
private string receivedmsg;
public readonly static Queue<Action> ExecuteOnMainThread = new Queue<Action>();
private void Awake()
{
}
IEnumerator updateTags()
{
yield return new WaitUntil(() => receivedmsg != null);
//string json = "{\"PC_Station\": [{\"PLC_1\": {\"DB1\": {\"test123\": 30}, \"STOP\": false, \"START\": true, \"Start_1\": false, \"Stop_1\": true, \"Led1\": false, \"Led2\": false, \"Led3\": false, \"Counter\": 3880, \"Sliderval\": 60}}]}";
//string json1 = "{\"PC_Station\": [{\"PLC_0\": {\"DB1\": {\"test123\": 0}, \"STOP\": false,\"Frap\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}},{\"PLC_1\": {\"DB1\": {\"test123\": 55}, \"STOP\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}}]}";
while (true)
{
var data = JToken.Parse(receivedmsg);
foreach (var value in data)
{
foreach (JArray arr in value)
{
for (int i = 0; i < arr.Count; i++)
{
foreach (var item in arr[i])
{
var itemproperties = item.Parent;
foreach (JToken token in itemproperties)
{
var prop = token as JProperty;
var plc = (JObject)prop.Value;
string canvass = "Canvas" + i.ToString();
upd1 = transform.Find(canvass).gameObject;
upd2 = transform.Find("Canvas" + i + "/Panel").gameObject;
foreach (KeyValuePair<string, JToken> val in plc)
{
var plcvarkey = val.Key;
var plcvarvalue = val.Value;
if (plcvarvalue is JObject)
{
foreach (KeyValuePair<string, JToken> plcvvobj in (JObject)plcvarvalue)
{
upd4 = transform.Find("Canvas" + i + "/Panel/" + plcvvobj.Key + "/" + plcvvobj.Key + "value").gameObject;
upd4.GetComponent<Text>().text = plcvvobj.Value.ToString();
}
}
else
{
upd3 = transform.Find("Canvas" + i + "/Panel/" + plcvarkey).gameObject;
//upd3.GetComponent<Image>().color = Color.green;
if (plcvarvalue.ToString() == "True")
{
upd3.GetComponent<Image>().color = Color.green;
}
if (plcvarvalue.ToString() == "False")
{
upd3.GetComponent<Image>().color = Color.red;
}
if (Regex.IsMatch(plcvarvalue.ToString(), @"^\d+$"))
{
upd4 = transform.Find("Canvas" + i + "/Panel/" + plcvarkey + "/" + plcvarkey + "value").gameObject;
upd4.GetComponent<Text>().text = plcvarvalue.ToString();
}
}
}
}
}
}
}
}
yield return new WaitForSeconds(0.5f);
}
}
#if !UNITY_EDITOR
// Socket initialization
DatagramSocket socket;
#endif
#if !UNITY_EDITOR
IEnumerator initGUI()
{
yield return new WaitUntil(() => receivedmsg != null);
createUserInterface(receivedmsg);
Debug.Log("left initgui");
}
// use this for initialization
async void Start()
{
/*StartCoroutine(SendSliderValue());
Button btn_on = led1_button_on.GetComponent<Button>();
Button btn_off = led1_button_off.GetComponent<Button>();
Button btn1_on = led3_button_on.GetComponent<Button>();
Button btn1_off = led3_button_off.GetComponent<Button>();
btn_on.onClick.AddListener(delegate {TaskWithParameters("Led1 on"); });
btn_off.onClick.AddListener(delegate {TaskWithParameters("Led1 off"); });
btn1_on.onClick.AddListener(delegate {TaskWithParameters("Led3 on"); });
btn1_off.onClick.AddListener(delegate {TaskWithParameters("Led3 off"); });*/
//string json = "{\"PC_Station\": [{\"PLC_0\": {\"DB1\": {\"test123\": 0}, \"STOP\": false,\"Frap\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}},{\"PLC_1\": {\"DB1\": {\"test123\": 55}, \"STOP\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}}]}";
Debug.Log("Waiting for a connection...");
socket = new DatagramSocket();
socket.MessageReceived += Socket_MessageReceived;
//createUserInterface(receivedmsg);
HostName IP = null;
try
{
var icp = NetworkInformation.GetInternetConnectionProfile();
IP = Windows.Networking.Connectivity.NetworkInformation.GetHostNames()
.SingleOrDefault(
hn =>
hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
== icp.NetworkAdapter.NetworkAdapterId);
await socket.BindEndpointAsync(IP, port);
}
catch (Exception e)
{
Debug.Log(e.ToString());
Debug.Log(SocketError.GetStatus(e.HResult).ToString());
return;
}
SendMessage("test");
StartCoroutine(initGUI());
StartCoroutine(updateTags());
}
void TaskWithParameters(string message)
{
Debug.Log("sending Message");
SendMessage(message);
}
private async System.Threading.Tasks.Task SendMessage(string message)
{
using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(externalIP), externalPort))
{
using (var writer = new Windows.Storage.Streams.DataWriter(stream))
{
var data = Encoding.UTF8.GetBytes(message);
writer.WriteBytes(data);
await writer.StoreAsync();
Debug.Log("Sent: " + message);
}
}
}
#else
// Use this for initialization.
void Start()
{
}
#endif
// Update is called once per frame.
void Update()
{
// Dequeues items until there are no more items on the queue.
while (ExecuteOnMainThread.Count > 0)
{
ExecuteOnMainThread.Dequeue().Invoke();
}
}
IEnumerator SendSliderValue()
{
Debug.Log("entered slider class");
GameObject theplayer = GameObject.Find("Hololens-Slider");
TubeSliderManager test = theplayer.GetComponent<TubeSliderManager>();
while (true)
{
sliderVal = test.CurrentValue;
string s = "Slidervalue" + sliderVal.ToString();
SendMessage(s);
yield return new WaitForSeconds(0.5f);
}
}
#if !UNITY_EDITOR
//this method gets called when a message is received
private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
{
// Read the received message.
Stream streamIn = args.GetDataStream().AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
receivedmsg = await reader.ReadLineAsync();
//Debug.Log("MESSAGE: " + message);
// if the count is zero, the message will be relayed to the setStuff method, which processes the string continuously.
// The message contains a JSON string which is received from the server.
if (ExecuteOnMainThread.Count == 0)
{
ExecuteOnMainThread.Enqueue(() =>
{
//Debug.Log(receivedmsg);
//pass msg to function here
});
}
}
#endif
public void createUserInterface(string jsonstring)
{
Debug.Log("entered create UI");
var root = JToken.Parse(jsonstring);
IterateJtoken(root);
canvases = new GameObject[abc.Count];
panels = new GameObject[abc.Count];
for (int i = 0; i < abc.Count; i++)
{
canvases[i] = Instantiate(canvas, transform.position, transform.rotation);
canvases[i].name = "Canvas" + i;
canvases[i].transform.SetParent(mainGameobject.transform, false);
canvases[i].transform.position += new Vector3(i * 14, 0, 30);
panels[i] = Instantiate(Panel, transform.position, transform.rotation);
panels[i].name = "Panel";
panels[i].transform.SetParent(canvases[i].transform, false);
for (int z = 0; z < abc[i].Count; z++)
{
tiles = new GameObject[abc[i].Count];
texts = new GameObject[abc[i].Count];
tiles[z] = Instantiate(image, transform.position, transform.rotation);
tiles[z].name = abc[i].ElementAt(z).Key;
tiles[z].transform.SetParent(panels[i].transform, false);
texts[z] = Instantiate(imagetext, transform.position, transform.rotation);
texts[z].name = abc[i].ElementAt(z).Key + "text";
texts[z].transform.SetParent(tiles[z].transform, false);
texts[z].GetComponent<Text>().text = abc[i].ElementAt(z).Key;
texts[z].transform.position += new Vector3(44 * scaler, -4 * scaler, 0);
if (Regex.IsMatch(abc[i].ElementAt(z).Value, @"^\d+$"))
{
numbertext = Instantiate(imagetext, transform.position, transform.rotation);
numbertext.name = abc[i].ElementAt(z).Key + "value";
numbertext.transform.SetParent(tiles[z].transform, false);
texts[z].transform.position += new Vector3(0, 19.5f * scaler, 0);
numbertext.transform.position += new Vector3(77 * scaler, -18.5f * scaler, 0);
}
}
}
}
public void IterateJtoken(JToken jtoken)
{
foreach (var value in jtoken)
{
foreach (JArray test in value)
{
for (int i = 0; i < test.Count; i++)
{
foreach (var item in test[i])
{
var itemproperties = item.Parent;
foreach (JToken token in itemproperties)
{
if (token is JProperty)
{
var prop = token as JProperty;
//Console.WriteLine(prop.Name); //PLC name
var plc = (JObject)prop.Value;
Dictionary<string, string> variables = new Dictionary<string, string>();
foreach (KeyValuePair<string, JToken> val in plc)
{
if (val.Value is JObject)
{
JObject nestedobj = (JObject)val.Value;
foreach (JProperty nestedvariables in nestedobj.Properties())
{
size++;
//variables[nestedvariables.Name] = nestedvariables.Value.ToString();
var nestedVariableName = nestedvariables.Name;
var nestedVariableValue = nestedvariables.Value;
variables.Add(nestedVariableName, nestedVariableValue.ToString());
//Console.WriteLine(nestedVariableName+" "+nestedVariableValue);
}
}
else
{
size++;
//variables[val.Key] = val.Value.ToString();
var variableName = val.Key;
var variableValue = val.Value;
variables.Add(variableName, variableValue.ToString());
//Console.WriteLine(variableName+" "+variableValue);
}
}
abc.Add(new Dictionary<string, string>(variables));
}
}
}
}
}
}
}
}
</code></pre>
<p>The code's actually quite simple. For the function <code>createUserInterface</code>, I generate a few public <code>Gameobjects</code>, canvas, Panel, image and <code>imagetext</code>. At the start of the function, the function <code>IterateJtoken()</code> gets called. This function deserializes the JSON String I mentioned in the above example. It fills up the public List of dictionaries which I've named 'abc'. Based on how the List is filled, the <code>createUserInterface</code> builds a user interface with the following hierarchy (manager is the empty gameobject I attach the script to):</p>
<p><a href="https://i.stack.imgur.com/3GT6q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3GT6q.png" alt="enter image description here"></a></p>
<p>As for the updateTags function, the public string I've called <code>receivedmsg</code> gets updated every 0.5 seconds. For instance, if a tag is true, the image turns green and for false it turns red.</p>
<p>An example:</p>
<p><a href="https://i.stack.imgur.com/DmkcZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DmkcZ.png" alt="enter image description here"></a></p>
<p>As you can see in the picture above, if I input the following string:</p>
<pre><code>string json1 = "{\"PC_Station\": [{\"PLC_0\": {\"DB1\": {\"test123\": 0}, \"STOP\": false,\"Frap\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}},{\"PLC_1\": {\"DB1\": {\"test123\": 55}, \"STOP\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}}]}";
</code></pre>
<p>The code will generate 2 canvases with each their own panel and all the variables like 'test123' as images.</p>
<p>I would like to know if there is a way to make the methods <code>updateTags()</code>, <code>createUserInterface()</code> and <code>IterateJToken()</code> more efficiently.</p>
| [] | [
{
"body": "<h2>Naming</h2>\n\n<p>The class is named <code>UDPCommunication</code>, but it does <code>createUserInterface</code>, among other things. This shows that some of the code should probably be part of another class, or that at least the class name does not fit well.</p>\n\n<hr>\n\n<p><code>abc</code>, <... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T14:25:58.977",
"Id": "200588",
"Score": "7",
"Tags": [
"c#",
"performance",
"json",
"unity3d"
],
"Title": "HoloLens Unity program"
} | 200588 |
<p>Python 2 is the predecessor of Python 3. Released in 2000, versions go up to 2.7.x.</p>
<p>According to <a href="https://www.python.org/dev/peps/pep-0404/" rel="nofollow noreferrer">PEP 404</a>, there will be no 2.8. Python 2.7 will be <a href="https://www.python.org/dev/peps/pep-0373/#maintenance-releases" rel="nofollow noreferrer">supported till 2020</a> and likely EOL afterwards.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T14:50:52.310",
"Id": "200589",
"Score": "0",
"Tags": null,
"Title": null
} | 200589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.