body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I am writing the solution of Dijkstra's algorithm in JS. This is what has happened so far. I need to make it so that the choice of nodes is by recursion. Tell me how to do this better.</p>
<pre><code>const size = 6;
сonst maxInt = 999999;
const graph = [
[null, maxInt, 50, 20, maxInt, 30],
[null, maxInt, maxInt, maxInt, 10, maxInt],
[null, maxInt, 20, maxInt, 40, maxInt],
[null, maxInt, maxInt, maxInt, maxInt, maxInt],
[null, maxInt, 20, maxInt, 25, maxInt]
];
const nodeParams = (distance, path, visited) => {
this.dist = distance;
this.path = path;
this.visited = visited;
};
let node = [];
for(let i = 1;i < size;i++) {
node[i] = [];
for(let j = 1;j < size;j++) {
node[i][j] = nodeParams(maxInt, 0, false);
}
};
const dijkstra = () => {
for(let source = 1; source < size; source++) {
node[source][source].dist = 0;
let minNode, nextNode;
for(let i = 1; i < size - 1; i++) {
minNode = i === 1 ? source : nextNode;
node[source][minNode].visited = true;
nextNode = null;
for(let w = 1; w < size; w++) {
if (!node[source][w].visited) {
if (node[source][minNode].dist + graph[minNode][w] < node[source][w].dist) {
node[source][w].dist = node[source][minNode].dist + graph[minNode][w];
node[source][w].path = minNode;
}
if(nextNode === null) {
nextNode = w;
}
}
}
}
}
};
dijkstra ();
let shortestPathString = '';
const getEachPathNode = (source, destination) => {
if(destination != source && destination > 0) {
getEachPathNode(source, array[source][destination].path);
shortestPathString += ' ' + array[source][destination].path;
}
}
const getShortestPath = (source, destination) => {
shortestPathString = 'Самый короткий путь от ' + source + ' до ' + destination + ': ';
if (array[source][destination].dist == maxInt) {
shortestPathString += 'не связаны';
} else {
getEachPathNode(source, destination);
shortestPathString += ' ' + destination;
}
shortestPathString += '. Расстояние: ' + array[source][destination].dist;
console.log(shortestPathString);
}
for(let i = 1; i < size; i++) {
for(let j = 1; j < size; j++) {
getShortestPath(i, j);
}
}
</code></pre>
<p>If there are any comments on the code, I'll be very glad to hear them too. This code does not go into any project, I just just study programming and try to set myself tasks and solve them.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-01T09:13:52.487",
"Id": "391121",
"Score": "0",
"body": "Something is wrong with this code. Are you sure it's working? The function `nodeParams` modifies `this` which is actually `window` here, and then returns `undefined`. You use the... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T03:11:49.383",
"Id": "202010",
"Score": "2",
"Tags": [
"javascript",
"matrix"
],
"Title": "Dijkstra in JavaScript"
} | 202010 |
<p>This is a drill from the Programming Principles and Practice Using C++. I managed to get it to work but somehow it doesn't feel right to me. I 'd appreciate any pointers on how to simplify/improve the solution.</p>
<p>Especially when it comes to best check if '|' was entered. I feel that creating two extra string variables and then converting them to int using <code>std::stoi</code> is very inefficient. I am new to C++ so please excuse the ignorance. Appreciate any feedback.</p>
<h3>Question</h3>
<blockquote>
<p>Write a program that in a while loop reads 2 integers and prints them. Carry on until the user enters '|'.</p>
</blockquote>
<pre><code>#include<iostream>
#include<string>
int main(){
int a, b;
std::string _a, _b;
while (true){
std::cout << "Enter two numbers." << std::endl;
std::cin >> _a >> _b;
if (_a == "|" || _b == "|"){break;};
a = std::stoi(_a);
b = std::stoi(_b);
std::cout << "You entered " << a << " and " << b << std::endl;
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<pre><code> std::cout << \"Enter two numbers.\" << std::endl;\n</code></pre>\n\n<p>You are looking to accept <em>integers</em>, not just numbers (i.e. \\$1.0, 1e0, 0b1, 0x1\\$).</p>\n\n<p>Avoid <code>std::endl</code>. <a href=\"https://en.cppreference.com/w/cpp/io/manip/endl\" rel... | {
"AcceptedAnswerId": "202019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T03:34:25.077",
"Id": "202011",
"Score": "4",
"Tags": [
"c++",
"beginner",
"programming-challenge"
],
"Title": "Reading integers while break condition not met in C++"
} | 202011 |
<p>I'm in the process of creating a simple SDL2 wrapper for a breakout clone. The real learning objectives for this project are:</p>
<p>Learn how to manage resources properly via wrappers
Learn more about SDL2
I'm building these wrapper as I step through Lazy Foo's tutorial and wanted to get some feedback on how I'm doing, and what other things I could be doing.</p>
<p>Here's my SDL_Surface wrapper so far:</p>
<pre><code>// Surface.h
#pragma once
#include <iostream>
#include <SDL.h>
#include <string>
#include "Window.h"
namespace SDL2 {
class Surface
{
private:
SDL_Surface* ScreenSurface = nullptr;
bool IsWindowSurface = false;
std::string ImagePath = "";
public:
// This function creates a Surface object associated with a Window (gets cleaned when Window is destroyed)
Surface(SDL2::Window& window);
Surface(std::string path);
// Move constructor
Surface(Surface&& source);
// Disable copy constructor
Surface(const Surface& source) = delete;
~Surface();
// Disable copy by assignment
Surface& operator=(const Surface& source) = delete;
// Move assignment
Surface& operator=(Surface&& source);
void FillRect();
void Update(SDL2::Window& window);
bool LoadBMP();
// TODO: Add more parameters at future SDL2 tutorial
void BlitSurface(SDL2::Surface& destination);
};
}
// Surface.cpp
#include "Surface.h"
SDL2::Surface::Surface(SDL2::Window& window) :
ScreenSurface{ SDL_GetWindowSurface(window.GetSDLWindow()) },
IsWindowSurface{ true }
{
}
SDL2::Surface::Surface(std::string path) :
ImagePath{ path },
IsWindowSurface{ false }
{
}
SDL2::Surface::Surface(Surface && source) :
ScreenSurface{ source.ScreenSurface },
IsWindowSurface{ source.IsWindowSurface },
ImagePath{ source.ImagePath }
{
source.ScreenSurface = nullptr;
source.IsWindowSurface = false;
source.ImagePath = "";
}
SDL2::Surface::~Surface()
{
// If surface is not associated with Window, need free the surface with SDL2 call
if (!IsWindowSurface) {
SDL_FreeSurface(ScreenSurface);
}
}
SDL2::Surface & SDL2::Surface::operator=(Surface && source)
{
if (&source == this)
return *this;
// If surface is not associated with Window, need free the surface with SDL2 call
if (!IsWindowSurface) {
SDL_FreeSurface(ScreenSurface);
}
ScreenSurface = source.ScreenSurface;
IsWindowSurface = source.ScreenSurface;
ImagePath = source.ImagePath;
// Return source to stable state
source.ScreenSurface = nullptr;
source.IsWindowSurface = false;
source.ImagePath = "";
return *this;
}
// TODO: Define SDL_Rect parameter and Color parameter (make wrappers for these)
void SDL2::Surface::FillRect()
{
SDL_FillRect(ScreenSurface, NULL, SDL_MapRGB(ScreenSurface->format, 0x00, 0x00, 0xFF));
}
void SDL2::Surface::Update(SDL2::Window& window)
{
SDL_UpdateWindowSurface(window.GetSDLWindow());
}
// This function is called after a non-window surface is created. Check on this return value for success/fail.
bool SDL2::Surface::LoadBMP()
{
// Load image from path
ScreenSurface = SDL_LoadBMP(ImagePath.c_str());
if (!ScreenSurface) {
std::cout << "Unable to load image " << ImagePath << " SDL Error: " << SDL_GetError() << '\n';
return false;
}
return true;
}
// The source Surface is `this`. This function applies the image to the destination surface (though not updated on the screen)
void SDL2::Surface::BlitSurface(SDL2::Surface & destination)
{
// Args: Source, FUTURE, Destination, FUTURE
SDL_BlitSurface(this->ScreenSurface, NULL, destination.ScreenSurface, NULL);
}
</code></pre>
<p>Any pointers would be much appreciated!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T05:30:31.420",
"Id": "389149",
"Score": "0",
"body": "Which [tutorial](http://lazyfoo.net/tutorials/SDL/) are you referring to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T05:54:27.483",
"Id":... | [
{
"body": "<p>Wrapping SDL_Surface like this to get automatic cleanup in the destructor is a good idea. However, the current implementation makes a few assumptions that aren't necessarily correct.</p>\n\n<hr>\n\n<h2>Surface Creation</h2>\n\n<p>There are lots of ways to get hold of a surface. Getting it from a <... | {
"AcceptedAnswerId": "202032",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T03:47:26.060",
"Id": "202012",
"Score": "5",
"Tags": [
"c++",
"sdl"
],
"Title": "Simple C++ SDL2 Wrapper for small game"
} | 202012 |
<p>I try to split URLs into segments. These segments got two information, their name and their own URL.</p>
<p>The last segment in the segments list should not have the URL property because it's the current URL from the browser. There is no need for it.</p>
<p>I created this code which works really fine</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const directoryPath = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';
const segments = directoryPath.split('/');
const info = segments.map((segment, index) => {
const item = {
name: segment
};
if (index < segments.length - 1) {
let route = '';
for (let i = 0; i <= index; i++) {
route += `/${segments[i]}`;
}
item.url = route;
}
return item;
});
console.log(info);</code></pre>
</div>
</div>
</p>
<p>I don't know if this is the only way doing this, maybe there is a more optimized way. I don't know if I really need the for-loop because at the top of the code I split the URL into segments and after that I create smaller URLs out of it.</p>
<p>Is there a better / easier way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T07:38:18.877",
"Id": "389159",
"Score": "1",
"body": "Welcome to Code Review! You're asking for a better way. Better how? Faster? Easier to read? More reusable?"
}
] | [
{
"body": "<p>Have some consideration about the naming you're using.</p>\n\n<p>You speack about <em>url</em>, but in your code you're handling <em>paths</em> and then they become <em>routes</em>.</p>\n\n<p>It' would be better if you focus on what is the main idea here and choose the names accordingly.</p>\n\n<p... | {
"AcceptedAnswerId": "202068",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T06:46:47.080",
"Id": "202020",
"Score": "4",
"Tags": [
"javascript",
"url"
],
"Title": "Split URL into segments"
} | 202020 |
<p>Presently my program is working properly, but how do i implement this program without using nested while loop(one while loop within another while loop).This is a kids way of programming and my office colleague doesn't want me to write code like this.So is there a different way for implementing this program or a proper way of implementing the while loops seen in the above code??</p>
<p>This IS MY CURRENT CODE:</p>
<pre><code>package Snomed.Snomed;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import catalog.Root;
public class Snomedinfo {
public void snomedinfoinsert() {
Root oRoot = null;
ResultSet oRsSelect = null;
PreparedStatement oPrStmt = null;
PreparedStatement oPrStmt2 = null;
PreparedStatement oPrStmtSelect = null;
String strSql = null;
String snomedcode = null;
ResultSet oRs = null;
String refid = null;
String id = null;
String effectivetime = null;
String active = null;
String moduleid = null;
String conceptid = null;
String languagecode = null;
String typeid = null;
String term = null;
String caseSignificanceid = null;
try {
oRoot = Root.createDbConnection(null);
strSql = "SELECT id FROM snomed_conceptdata WHERE active=1 ";
oPrStmt2 = oRoot.con.prepareStatement(strSql);
oRsSelect = oPrStmt2.executeQuery();
String strSql2 = "SELECT * FROM snomed_descriptiondata WHERE conceptid =? AND active=1 ";
oPrStmtSelect = oRoot.con.prepareStatement(strSql2);
String sql = "INSERT INTO snomedinfo_data (refid,id,effectivetime,active,moduleid,conceptid,languagecode,typeid,term,caseSignificanceid) VALUES( ?, ?, ?,?,?,?,?,?,?,?)";
oPrStmt = oRoot.con.prepareStatement(sql);
while (oRsSelect.next()) //first while loop
{
snomedcode = Root.TrimString(oRsSelect.getString("id"));
oPrStmtSelect.setString(1, snomedcode);
oRs = oPrStmtSelect.executeQuery();
while (oRs.next()) //second while loop
{
refid = Root.TrimString(oRs.getString("refid"));
id = Root.TrimString(oRs.getString("id"));
effectivetime = Root.TrimString(oRs.getString("effectivetime"));
active = Root.TrimString(oRs.getString("active"));
moduleid = Root.TrimString(oRs.getString("moduleid"));
conceptid = Root.TrimString(oRs.getString("conceptid"));
languagecode = Root.TrimString(oRs.getString("languagecode"));
typeid = Root.TrimString(oRs.getString("typeid"));
term = Root.TrimString(oRs.getString("term"));
caseSignificanceid = Root.TrimString(oRs.getString("caseSignificanceid"));
oPrStmt.setString(1, refid);
oPrStmt.setString(2, id);
oPrStmt.setString(3, effectivetime);
oPrStmt.setString(4, active);
oPrStmt.setString(5, moduleid);
oPrStmt.setString(6, conceptid);
oPrStmt.setString(7, languagecode);
oPrStmt.setString(8, typeid);
oPrStmt.setString(9, term);
oPrStmt.setString(10, caseSignificanceid);
oPrStmt.executeUpdate();
}
}
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
} finally {
oRsSelect = Root.EcwCloseResultSet(oRsSelect);
oRs = Root.EcwCloseResultSet(oRs);
oPrStmt = Root.EcwClosePreparedStatement(oPrStmt);
oPrStmt = Root.EcwClosePreparedStatement(oPrStmt2);
oPrStmt = Root.EcwClosePreparedStatement(oPrStmtSelect);
oRoot = Root.closeDbConnection(null, oRoot);
}
}
public static void main(String args[]) throws Exception {
Snomedinfo a = new Snomedinfo();
a.snomedinfoinsert();
}
}
</code></pre>
<p>NOTE:I am allowed to use while loop but not in a nested way.And for your kind information the two tables 'snomed_conceptdata' and 'snomed_descriptiondata' has more than 1300000 rows of data present in them . </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T11:18:34.657",
"Id": "389179",
"Score": "1",
"body": "Your question is missing context about what your code should do. In its current form its off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-2... | [
{
"body": "<p>Do you have to use Java? In SQL: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>INSERT INTO snomedinfo_data \n (refid, id, effectivetime, active, moduleid, conceptid,\n languagecode, typeid, term, caseSignificanceid)\n SELECT sd.refid, sd.id, sd.effectivetime, sd.active, sd.modul... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T10:08:03.523",
"Id": "202037",
"Score": "-3",
"Tags": [
"java",
"sql",
"mysql",
"jdbc"
],
"Title": "Is there a different way of implementing this program without using nested while loop?"
} | 202037 |
<p>I'm building my own application and have just started by building my own router since none seemed to be fulfilling my requests. Also, they seemed to have an overly complicated design. There are ofcourse still things to do, like allowing it to be called by a simple 'GET' parameter and such.</p>
<p>First let me describe 3 essential parts:</p>
<p>Runtime is a simple collection container. It stores the environment parameters for easy access by other parties.</p>
<p>The function "fn_get_schema" gets an array of data from a single PHP file. This allows me to store huge arrays of data to prevent calling the database without a reason.</p>
<p>The dispatch field in the database is only set for fixed pages (which are always present), such as the login page, the registration page, etc. The code for this has not been added yet. Same applies for the 'host', this would allow multiple hosts in a single backend in the future.</p>
<p>Please let me know what you think and if I am on the right track:</p>
<pre><code><?php
namespace Core;
class Router {
private $server;
private $formattedURI;
private $host;
/**
* Create router in one call from config.
*
* @param $request
*/
public function __construct(&$request)
{
$this->server = $request;
$this->getHost();
}
/**
* Formats the request into an array which is 'readable'
*/
public function compileRoute() {
if (!isset($this->server['REQUEST_URI']) || empty($this->server['REQUEST_URI']) || $this->server['REQUEST_URI'] == '' || $this->server['REQUEST_URI'] == '/') {
$this->dispatch('index', 'view');
}
$request_uri = $this->server['REQUEST_URI'];
$request_uri = ltrim($request_uri, '/');
$request_uri = rtrim($request_uri, '/');
$this->formattedURI = explode("/", $request_uri);
// We set an index to check 'breadcrumb-able' next level items
$index = 1;
foreach ($this->formattedURI as $uri) {
$name_information = Core::$app['db']->getRow('SELECT * FROM seo_names WHERE name = ?s', $uri);
$objects = fn_get_schema('routes', 'objects');
// If the object does not exist, dispatch exceptions.page_not_found
if (!isset($objects[$name_information['object_type']])) {
$this->dispatch('exceptions', 'page_not_found');
} else {
$current_object = $objects[$name_information['object_type']];
}
// If item is breadcrumb-able and the url has another level, continue
if ($current_object['breadcrumb_compatible'] && isset($this->formattedURI[$index])) {
continue;
}
// Set the unique ID for the object
$_REQUEST[$current_object['handler']] = $name_information['object_id'];
$this->dispatch(
$current_object['controller'],
$current_object['mode'],
(isset($current_object['action'])) ? $current_object['action'] : NULL
);
$index++;
}
}
/**
* Gets the host and sets it to the private variable
*/
private function getHost() {
$possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
$sourceTransformations = array(
"HTTP_X_FORWARDED_HOST" => function($value) {
$elements = explode(',', $value);
return trim(end($elements));
}
);
$host = '';
foreach ($possibleHostSources as $source)
{
if (!empty($host)) break;
if (empty($_SERVER[$source])) continue;
$host = $_SERVER[$source];
if (array_key_exists($source, $sourceTransformations))
{
$host = $sourceTransformations[$source]($host);
}
}
// Remove port number from host
$host = preg_replace('/:\d+$/', '', $host);
Core::$app['runtime']->set('host', $host);
$this->host = trim($host);
}
/**
* Used to set the variables and execute the dispatch by stacking the controllers
*
* @param $controller
* @param $mode
* @param null $action
*/
private function dispatch($controller, $mode, $action = NULL) {
Core::$app['runtime']->set('controller', $controller);
Core::$app['runtime']->set('mode', $mode);
if (!empty($action)) {
Core::$app['runtime']->set('action', $action);
}
if (AREA === 'A') {
$controller_env = 'backend';
} else {
$controller_env = 'frontend';
}
/** @noinspection PhpIncludeInspection */
include DIR_ROOT . '/app/controllers/' . $controller_env . '/' . $controller . '.php';
}
}
</code></pre>
<p>My database structure is as follows:</p>
<pre><code>CREATE TABLE `seo_names` (
`name` varchar(250) NOT NULL DEFAULT '',
`object_id` int(11) unsigned NOT NULL DEFAULT '0',
`object_type` char(1) NOT NULL DEFAULT '',
`dispatch` varchar(64) NOT NULL DEFAULT '',
`path` varchar(255) NOT NULL DEFAULT '',
`lang_code` char(2) NOT NULL DEFAULT '',
PRIMARY KEY (`object_id`,`object_type`,`dispatch`,`lang_code`),
KEY `name` (`name`,`lang_code`),
KEY `type` (`name`,`object_type`,`lang_code`),
KEY `dispatch` (`dispatch`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code></pre>
<p>My schema (fn_get_schema) looks as follows:</p>
<pre><code>$schema = array(
'p' => array(
'handler' => 'product_id',
'breadcrumb_compatible' => false,
'controller' => 'products',
'mode' => 'view'
),
'c' => array(
'handler' => 'category_id',
'breadcrumb_compatible' => true,
'controller' => 'categories',
'mode' => 'view'
)
);
return $schema;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T06:14:20.470",
"Id": "391993",
"Score": "0",
"body": "Where is `AREA` defined? What possible value would it have besides `A` and why does that value signify that a backend controller should be used?"
},
{
"ContentLicense": "... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T10:20:03.503",
"Id": "202038",
"Score": "1",
"Tags": [
"php"
],
"Title": "Is this a good functioning router class?"
} | 202038 |
<p>I'm trying to make something like Python's <code>argparse</code> in C.</p>
<p>I created this <code>Argument</code> struct and functions; is my code good so far?</p>
<h2>Argument.h:</h2>
<pre><code>#ifndef ARGUMENT_H
#define ARGUMENT_H
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct Argument{
char **names;
char *action;
char *metavar;
char *nargs;
char *type;
char **choices;
char *defaultValue;
bool required;
char *help;
};
struct Argument Argument_new(char**,char*,char*,char*,char*,char**,char*,bool*,char*);
#endif
</code></pre>
<h2>Argument.c:</h2>
<pre><code>#include "argument.h"
const char *Argument_ACTIONS[]={
"default",
"store_true",
"store_false",
"show_help",
"show_version",
NULL
};
const char *Argument_NARGS_PATTERNS[]={
"([1-9]\\d*)?\\+",
"[1-9]\\d*",
"[1-9]\\d*-[1-9]\\d*"
};
struct Argument Argument_new(char **names,char *action,char *metavar,char *nargs,char *type,char **choices,char *defaultValue,bool *required,char *help){
struct Argument self;
size_t namesCount=0;
char **namesStart=names;
while(*names++){
namesCount++;
}
int i;
self.names=malloc(namesCount*sizeof(*names));
for(i=0,names=namesStart;*names;names++,i++){
if(false/*not match(*names,"^-{1,2}(?!-)")*/){
//error
}else{
self.names[i]=malloc(strlen(*names)+1);
strcpy(self.names[i],*names);
}
}
if(action==NULL){
self.action=malloc(strlen(Argument_ACTIONS[0])+1);
strcpy(self.action,Argument_ACTIONS[0]);
}else{
bool good=false;
const char **ptr=Argument_ACTIONS;
while(*ptr){
if(strcmp(action,*ptr)==0){
good=true;
break;
}
ptr++;
}
if(!good){
//error
}else{
self.action=malloc(strlen(action)+1);
strcpy(self.action,action);
}
}
if(metavar==NULL){
self.metavar=malloc(strlen(self.names[namesCount-1])+1);
strcpy(self.metavar,self.names[namesCount-1]);
char *ptr=self.metavar;
while(*ptr){
*ptr=(char)toupper(*ptr);
ptr++;
}
}else{
self.metavar=malloc(strlen(metavar)+1);
strcpy(self.metavar,metavar);
}
if(nargs==NULL){
self.nargs=malloc(strlen("1")+1);
strcpy(self.nargs,"1");
}else{
if(false/*not match(*nargs,???)*/){
//error
}else{
self.nargs=malloc(strlen(nargs)+1);
strcpy(self.nargs,nargs);
}
}
if(type==NULL){
self.type=malloc(strlen("string")+1);
strcpy(self.type,"string");
}else{
if(false/*not match(*type,"^(string|((\+|-)?int((>|<|>=|<=|!=)-?[1-9]\d+)?))$")*/){
//error
}else{
self.type=malloc(strlen(type)+1);
strcpy(self.type,type);
}
}
if(choices==NULL){
self.choices=malloc(sizeof(NULL));
self.choices=NULL;
}else{
size_t choicesCount=0;
char **choicesStart=choices;
while(*choices++){
choicesCount++;
}
self.choices=malloc(choicesCount*sizeof(*choices));
for(i=0,choices=choicesStart;*choices;choices++,i++){
self.choices[i]=malloc(strlen(*choices)+1);
strcpy(self.choices[i],*choices);
}
}
if(defaultValue==NULL){
if(self.choices==NULL){
self.defaultValue=malloc(sizeof(NULL));
self.defaultValue=NULL;
}else{
self.defaultValue=malloc(strlen(self.choices[0])+1);
strcpy(self.defaultValue,self.choices[0]);
}
}else{
self.defaultValue=malloc(strlen(defaultValue)+1);
strcpy(self.defaultValue,defaultValue);
}
self.required=malloc(sizeof(bool));
if(self.action==Argument_ACTIONS[0]){
if(self.defaultValue!=NULL){
self.required=false;
}else if(required!=NULL){
self.required=required;
}else{
self.required=true;
}
}else{
self.required=false;
}
if(help==NULL){
self.help=malloc(sizeof("")+1);
strcpy(self.help,"");
}else{
self.help=malloc(sizeof(strlen(help))+1);
strcpy(self.help,help);
}
return self;
}
</code></pre>
<p>I want to know what can be done better and "cleaner".</p>
| [] | [
{
"body": "<h1>Includes</h1>\n\n<p>The interface needs only <code><stdbool.h></code> - the rest of the standard headers only need to be included in the implementation file.</p>\n\n<h1>Interface</h1>\n\n<p>The declaration isn't very helpful:</p>\n\n<pre><code>struct Argument Argument_new(char**,char*,char*... | {
"AcceptedAnswerId": "202045",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T10:31:58.713",
"Id": "202041",
"Score": "1",
"Tags": [
"c",
"parsing",
"console"
],
"Title": "C - Argparse (Argument struct)"
} | 202041 |
<p>I have written a VBA code in excel (basically through combining various codes from others -_-") to list out the path, file name, file size & extension of all files under a folder and the sub-folders there-under.</p>
<p>Is it possible to improve the efficiency for collecting the same info?</p>
<pre><code>Sub MainList()
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
Cells(3, 1) = Now()
Call ListFilesInFolder(xDir, True)
Cells(5, 1) = Now()
End Sub
Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFile As Object
Dim rowIndex As Long
Dim folder_index As Integer
Dim file_extension As String
Dim file_type As String
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
folder_index = Range("B65536").End(xlUp).row + 1
rowIndex = Range("F65536").End(xlUp).row + 1
Cells(folder_index, 2).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFolder.Path, TextToDisplay:=xFolder.Path
For Each xFile In xFolder.Files
file_extension = LCase(xFileSystemObject.GetExtensionName(xFile.Path))
If file_extension = "pdf" Then
file_type = "PDF"
ElseIf Left(file_extension, 3) = "doc" Then
file_type = "DOC"
ElseIf Left(file_extension, 2) = "xl" Then
file_type = "XLS"
ElseIf Left(file_extension, 3) = "msg" Then
file_type = "MSG"
ElseIf Left(file_extension, 3) = "zip" Then
file_type = "ZIP"
ElseIf Left(file_extension, 3) = "ppt" Then
file_type = "PPT"
Else
file_type = ""
End If
Cells(rowIndex, 6).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFolder.Path, TextToDisplay:=xFolder.Path
Cells(rowIndex, 7).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFile.Path, TextToDisplay:=xFile.Name
Cells(rowIndex, 8).Formula = file_type
Cells(rowIndex, 9).Formula = xFile.Size
Cells(rowIndex, 10).Formula = xFile.DateLastModified
Cells(rowIndex, 11).Formula = file_extension
rowIndex = rowIndex + 1
Next xFile
If xIsSubfolders Then
For Each xSubFolder In xFolder.SubFolders
ListFilesInFolder xSubFolder.Path, True
Next xSubFolder
End If
Set xFile = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
End Sub
</code></pre>
| [] | [
{
"body": "<p>I just realized the code will run much faster by setting Application.Settings to false. Is there any way to further enhance the efficiency?</p>\n\n<p>Here is the revised codes...</p>\n\n<blockquote>\n<pre><code>Sub MainList()\n\nApplication.ScreenUpdating = False\nApplication.EnableEvents = False\... | {
"AcceptedAnswerId": "202100",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T10:39:48.753",
"Id": "202042",
"Score": "1",
"Tags": [
"vba",
"file"
],
"Title": "VBA - faster way to list out files in a folder & subfolders"
} | 202042 |
<p>I wrote a small type-rich MKS Unit system for the consistent and safe calculation of physical units in everyday use.</p>
<p>I realized some operators' implementations via the <a href="https://en.wikipedia.org/wiki/Barton%E2%80%93Nackman_trick" rel="nofollow noreferrer">Barton-Nackman trick</a> while defining types via an unique template parameter fixed upon object construction. This prevents e.g. the addition of inconsistent units etc.</p>
<pre><code>#include <string>
#include <sstream>
template<typename Value>
struct OperatorFacade {
friend constexpr bool operator!=(Value const &lhs, Value const &rhs)
noexcept {
return !(lhs==rhs);
}
friend constexpr bool operator>(Value const &lhs, Value const &rhs) noexcept {
return rhs < lhs;
}
friend constexpr bool operator<=(Value const &lhs, Value const &rhs)
noexcept {
return !(rhs > lhs);
}
friend constexpr bool operator>=(Value const &lhs, Value const &rhs)
noexcept {
return !(rhs < lhs);
}
friend constexpr auto &operator<<(std::ostream &os, Value const other)
noexcept {
return os << static_cast<long double>(other);
}
friend constexpr auto operator-(Value const &lhs,
Value const &rhs) noexcept {
return Value{lhs} -= rhs;
}
friend constexpr auto operator+(Value const &lhs,
Value const &rhs) noexcept {
return Value{lhs} += rhs;
}
};
// Type-safety at compile-time
template<int M = 0, int K = 0, int S = 0>
struct MksUnit {
enum { metre = M, kilogram = K, second = S };
};
template<typename U = MksUnit<>> // default to dimensionless value
class Value final : public OperatorFacade<Value<U>> {
public:
constexpr explicit Value() noexcept = default;
constexpr explicit Value(long double magnitude) noexcept
: magnitude_{magnitude} {}
//constexpr auto &magnitude() noexcept { return magnitude_; }
constexpr explicit operator long double() const noexcept {
return
magnitude_;
}
friend bool operator==(Value const &lhs, Value const &rhs) {
return static_cast<long double>(lhs)==static_cast<long double>(rhs);
}
friend bool operator<(Value const &lhs, Value const &rhs) {
return static_cast<long double>(lhs) < static_cast<long double>(rhs);
}
auto &operator+=(Value const &other) {
magnitude_ += static_cast<long double>(other);
return *this;
}
auto &operator-=(Value const &other) {
magnitude_ -= static_cast<long double>(other);
return *this;
}
auto const &operator*(long double scalar) const {
magnitude_ *= scalar;
return *this;
}
friend auto &operator*(long double scalar, Value const &other) {
return other.operator*(scalar);
}
private:
long double mutable magnitude_{0.0};
};
// Some handy alias declarations
using DimensionlessQuantity = Value<>;
using Length = Value<MksUnit<1, 0, 0>>;
using Area = Value<MksUnit<2, 0, 0>>;
using Volume = Value<MksUnit<3, 0, 0>>;
using Mass = Value<MksUnit<0, 1, 0>>;
using Time = Value<MksUnit<0, 0, 1>>;
using Velocity = Value<MksUnit<1, 0, -1>>;
using Acceleration = Value<MksUnit<1, 0, -2>>;
using Frequency = Value<MksUnit<0, 0, -1>>;
using Force = Value<MksUnit<1, 1, -2>>;
using Pressure = Value<MksUnit<-1, 1, -2>>;
using Momentum = Value<MksUnit<1, 1, -1>>;
// A couple of convenient factory functions
constexpr auto operator "" _N(long double magnitude) {
return Force{magnitude};
}
constexpr auto operator "" _ms2(long double magnitude) {
return Acceleration{magnitude};
}
constexpr auto operator "" _s(long double magnitude) {
return Time{magnitude};
}
constexpr auto operator "" _Ns(long double magnitude) {
return Momentum{magnitude};
}
constexpr auto operator "" _m(long double magnitude) {
return Length{magnitude};
}
constexpr auto operator "" _ms(long double magnitude) {
return Velocity{magnitude};
}
constexpr auto operator "" _kg(long double magnitude) {
return Mass{magnitude};
}
constexpr auto operator "" _1s(long double magnitude) {
return Frequency{magnitude};
}
// Arithmetic operators for consistent type-rich conversions of SI-Units
template<int M1, int K1, int S1, int M2, int K2, int S2>
constexpr auto operator*(Value<MksUnit<M1, K1, S1>> const &lhs,
Value<MksUnit<M2, K2, S2>> const &rhs) noexcept {
return Value<MksUnit<M1 + M2, K1 + K2, S1 + S2>>{
static_cast<long double>(lhs)*static_cast<long double>(rhs)};
}
template<int M1, int K1, int S1, int M2, int K2, int S2>
constexpr auto operator/(Value<MksUnit<M1, K1, S1>> const &lhs,
Value<MksUnit<M2, K2, S2>> const &rhs) noexcept {
return Value<MksUnit<M1 - M2, K1 - K2, S1 - S2>>{
static_cast<long double>(lhs)/static_cast<long double>(rhs)};
}
// Scientific constants
auto constexpr speedOfLight = 299792458.0_ms;
auto constexpr gravitationalAccelerationOnEarth = 9.80665_ms2;
void applyMomentumToSpacecraftBody(Momentum const &impulseValue) {};
int main(){
std::cout << "Consistent? " << 10.0_ms - 5.0_m << std::endl;
}
</code></pre>
<p>Do you mind taking a look and tell me what you think and where I can improve?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T12:34:07.823",
"Id": "389187",
"Score": "1",
"body": "No candela or ampere? :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T14:10:15.217",
"Id": "389205",
"Score": "0",
"body": "Pleas... | [
{
"body": "<h1><code>Value</code> issues</h1>\n\n<ul>\n<li><p><code>friend bool operator==(const Value& lhs, const Value& rhs)</code> can be <code>noexcept</code>. Also, why use those <code>static_cast</code>s instead of simply comparing <code>lhs.magnitude == rhs.magnitude</code>? That's why it's a <co... | {
"AcceptedAnswerId": "202055",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T10:50:53.070",
"Id": "202043",
"Score": "4",
"Tags": [
"c++",
"template-meta-programming",
"type-safety",
"unit-conversion"
],
"Title": "SI type safe unit calculations"
} | 202043 |
<p>I have programmed Tic Tac Toe in C. How can I improve the code? I have been told that <code>system("cls")</code> is not secure, but I don't know any other way of clearing the screen.</p>
<h3>main.c:</h3>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define BOOL short int
#define TRUE 1
#define FALSE 0
#define NUMBER_OF_ROWS 3
#define NUMBER_OF_COLUMNS 3
void setup_grid(char (*grid)[NUMBER_OF_COLUMNS]);
void display_grid(char (*grid)[NUMBER_OF_COLUMNS]);
void add_piece(char (*grid)[NUMBER_OF_COLUMNS], char, char);
BOOL space_is_empty(char (*grid)[NUMBER_OF_COLUMNS], char);
BOOL three_in_a_row(char (*grid)[NUMBER_OF_COLUMNS], char);
int main()
{
char grid[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
setup_grid(grid);
char player = '1';
char player_piece = 'O';
char space;
int space_int;
int piece_count = 0;
BOOL program_is_running = TRUE;
BOOL input_loop;
while(program_is_running)
{
system("cls");
display_grid(grid);
do
{
printf("Player %c: ", player);
space = getchar();
getchar(); // For the \n char.
printf("\n");
space_int = space - '0';
if(space_int < 1 || space_int > 9)
{
printf("Please enter an integer from 1-9\n");
input_loop = TRUE;
}
else if(space_is_empty(grid, space))
{
add_piece(grid, player_piece, space);
piece_count++;
input_loop = FALSE;
}
else
{
printf("That space is already taken.\n");
input_loop = TRUE;
}
}
while(input_loop);
if(three_in_a_row(grid, player_piece))
{
system("cls");
display_grid(grid);
printf("Player %c won!", player);
program_is_running = FALSE;
}
else if(piece_count >= 9)
{
system("cls");
display_grid(grid);
printf("It is a draw.\n");
program_is_running = FALSE;
}
else if(player == '1')
{
player = '2';
player_piece = 'X';
}
else
{
player = '1';
player_piece = 'O';
}
}
getchar();
return 0;
}
void setup_grid(char (*grid)[NUMBER_OF_COLUMNS])
{
int count = 1;
for(int y = 0; y < NUMBER_OF_ROWS; y++)
{
for(int x = 0; x < NUMBER_OF_COLUMNS; x++, count++)
{
grid[y][x] = count + '0';
}
}
}
void display_grid(char (*grid)[NUMBER_OF_COLUMNS])
{
printf("\n");
for(int y = 0; y < NUMBER_OF_ROWS; y++)
{
for(int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
printf(" %c ", grid[y][x]);
}
printf("\n");
}
printf("\n");
}
void add_piece(char (*grid)[NUMBER_OF_COLUMNS], char player, char space)
{
for(int y = 0; y < NUMBER_OF_ROWS; y++)
for(int x = 0; x < NUMBER_OF_COLUMNS; x++)
if(grid[y][x] == space)
grid[y][x] = player;
}
BOOL space_is_empty(char (*grid)[NUMBER_OF_COLUMNS], char space)
{
for(int y = 0; y < NUMBER_OF_ROWS; y++)
for(int x = 0; x < NUMBER_OF_COLUMNS; x++)
if(grid[y][x] == space)
return TRUE;
return FALSE;
}
BOOL three_in_a_row(char (*grid)[NUMBER_OF_COLUMNS], char player)
{
// Horizontal check.
for(int y = 0; y < NUMBER_OF_ROWS; y++)
{
for(int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
if(grid[y][x] == player)
{
if(x == 2)
return TRUE;
}
else
break;
}
}
// Vertical check.
for(int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
for(int y = 0; y < NUMBER_OF_ROWS; y++)
{
if(grid[y][x] == player)
{
if(y == 2)
return TRUE;
}
else
break;
}
}
// Diagonal check.
// Top left to bottom right.
if(grid[0][0] == player && grid[1][1] == player && grid[2][2] == player)
return TRUE;
// Bottom left to top right
if(grid[2][0] == player && grid[1][1] == player && grid[0][2] == player)
return TRUE;
return FALSE;
}
</code></pre>
| [] | [
{
"body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Prefer <code>stdbool.h</code> to defining your own <code>BOOL</code> type</h2>\n\n<p>There is a header <code>stdbool.h</code> that has been part of the standard since C99. It's generally better to rely on standard types rather than... | {
"AcceptedAnswerId": "202061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T11:59:01.817",
"Id": "202051",
"Score": "2",
"Tags": [
"c",
"tic-tac-toe"
],
"Title": "Text-based Tic Tac Toe in C"
} | 202051 |
<p>As a beginner, I'd like to see if anyone can suggest any better way of coding the below, as I'm duplicating code and nesting identical if statements as part of the following problem.</p>
<p>I'm grabbing data from a REST API, which is returned in JSON format. However, the query may fail. One cause of failure is that the authorization token obtained earlier has expired. In this case, I want to get a new token, and retry the query. Then I need to reprocess the response, which may still be a failure (but, this time, not because of an expired token).</p>
<p>So, I've written this, but I'm thinking there might be a more elegant way to write it to avoid code repeats:</p>
<pre><code># Firstly, I get the data, which returns a dict from a JSON response
response = get_data(authorization)
if response["responseStatus"] == "FAILURE":
# I believe I need to check this in a separate if statement
# because even though there's always a responseStatus key
# it will only contain an errors key if the former equals FAILURE
if response["errors"][0]["type"] == 'INVALID_SESSION_ID':
print("Session expired, initiating new session.")
# I call the function that grabs a new Authorization token
authorization = get_authorization(username, password)
# Then I call again the function that gets the data
response = get_data(authorization)
# And now I need to look again for a possible failure
if response["responseStatus"] == "FAILURE":
print(response["errors"])
else:
print(response["errors"])
# Here I couldn't do a simple else because I need to process
# success for either calls of get_data() above (before or
# inside the if block)
if response["responseStatus"] == "SUCCESS":
process_data()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T12:36:56.540",
"Id": "389188",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ... | [
{
"body": "<p><strong>EDIT:</strong> <em>Answer updated to use a while-loop rather than recursion, as noted in the comments. I also recently learned about the max recursion depth in Python being a good argument against recursion in the first place.</em></p>\n\n<p>One way you could solve this is by separating th... | {
"AcceptedAnswerId": "202088",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T12:34:09.897",
"Id": "202052",
"Score": "0",
"Tags": [
"python",
"beginner",
"json",
"error-handling",
"rest"
],
"Title": "Python client to fetch JSON data from REST API, retrying on failure"
} | 202052 |
<p>Below is an example on how to scroll two canvasses in two separate frames simultaneously. The trick is on how to pass on <code>*args</code> from the bindings to function <code>onscroll</code> for scrolling and <code>onresize</code> for changing the dimensions of the rectangle using <code>lambda</code> in the commands: <code>Scrollbar(frame3, orient='vertical', command=lambda *args: onscroll('axis', *args))</code> and <code>Button(frame3, text='reduce ', command=lambda *args: onresize(False, *args))</code>.</p>
<p>Is this the best way to handle this?</p>
<pre><code>import tkinter as tk
from tkinter import Frame, Canvas, Scrollbar, Button
global size_x, size_y, canvas1, canvas2, block1, block2
size_x = size_y = 150
block1 = block2 = ''
def onscroll(axis, *args):
global canvas1, canvas2
print(f'axis: {axis} and args are {[*args]} ',
end='\r')
if axis == 'x-axis':
canvas1.xview(*args)
canvas2.xview(*args)
elif axis == 'y-axis':
canvas1.yview(*args)
canvas2.yview(*args)
else:
assert False, f"axis {axis} is incorrect, use 'x-axis' or 'y-axis'"
def onresize(enlarge, *args):
global size_x, size_y
print(f'enlarge: {enlarge} and args are {[*args]} ',
end='\r')
if enlarge:
size_x *= 1.1
size_y *= 1.1
else:
size_x /= 1.1
size_y /= 1.1
def main():
global canvas1, canvas2, block1, block2
root = tk.Tk()
frame1 = Frame(root, bg='grey')
frame1.grid(row=0, column=0)
frame2 = Frame(root, bg='grey')
frame2.grid(row=0, column=1)
frame3 = Frame(root, bg='grey')
frame3.grid(row=0, column=2)
yscrollbar = Scrollbar(frame3, orient='vertical',
command=lambda *args: onscroll('y-axis', *args))
yscrollbar.pack(side='right', fill='y', expand='yes')
xscrollbar = Scrollbar(frame3, orient='horizontal',
command=lambda *args: onscroll('x-axis', *args))
xscrollbar.pack(side='bottom', fill='x', expand='yes')
reduce_button = Button(frame3, text='reduce ',
command=lambda *args: onresize(False, *args))
reduce_button.pack(side='right', anchor='ne')
enlarge_button = Button(frame3, text='enlarge',
command=lambda *args: onresize(True, *args))
enlarge_button.pack(side='right', anchor='ne')
canvas1 = Canvas(frame1, width=200, height=200, bg="blue",
scrollregion=(0, 0, 500, 500),
yscrollcommand=yscrollbar.set,
xscrollcommand=xscrollbar.set)
canvas1.pack(side='right')
canvas2 = Canvas(frame2, width=200, height=200, bg="yellow",
scrollregion=(0, 0, 500, 500),
yscrollcommand=yscrollbar.set,
xscrollcommand=xscrollbar.set)
canvas2.pack()
canvas3 = Canvas(frame3, width=200, height=200, bg='pink')
canvas3.pack()
while True:
canvas1.delete(block1)
canvas2.delete(block2)
block1 = canvas1.create_rectangle(100, 100, size_x, size_y,
fill='orange')
block2 = canvas2.create_rectangle(100, 100, size_x, size_y,
fill='blue')
root.update()
root.mainloop()
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<h2>Remove unnecessary imports</h2>\n\n<p>You're importing parts of tkinter twice, Remove this line:</p>\n\n<pre><code>from tkinter import Frame, Canvas, Scrollbar, Button\n</code></pre>\n\n<p>Then, whenever you need to use <code>Frame</code>, <code>Canvas</code>, etc, use <code>tk.Frame</code>, <cod... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T12:38:47.053",
"Id": "202053",
"Score": "1",
"Tags": [
"python",
"tkinter",
"lambda"
],
"Title": "On tkinter: scrolling multiple widgets simultaneously in different frames"
} | 202053 |
<p>I wrote this code to count the dinucletide fractions that appear in a genome (this is a sequence of two nucleotides, 'A','G','C','T', together). My code also calculates the j2 index (this is a very simple index showing the fraction of groups of dinucleotides based on an equation at a glance*).</p>
<p>It has currently taken 3 days to generate a dataframe of 14gb, and there is still a lot to go, I'm wondering if I can improve the performance/speed with the code at all)</p>
<p><strong>This is my code:</strong></p>
<pre><code>from Bio import SeqIO
import sys
from collections import Counter
def chunks(l, n):
for i in range(0, len(l)-(n-1)):
yield l[i:i+n]
def species_name_function(infile):
for record in SeqIO.parse(infile, "fasta"):
fields = record.description.split()
speciesname = " ".join(fields[1:3])
return speciesname
if __name__ == '__main__':
frequency = []
infile = sys.argv[1]
for fasta in SeqIO.parse(open(infile), "fasta"):
dna = str(fasta.seq)
freq = Counter(dna)
freq.update(Counter(chunks(dna,2)))
frequency.append(freq)
species_name = species_name_function(infile)
genomesize = freq['A'] + freq['G'] + freq['C'] + freq['T']
FYY = (freq['TT'] + freq['CC'] + freq['TC'] + freq['CT']) / genomesize
FRR = (freq['AA'] + freq['GG'] + freq['AG'] + freq['GA']) / genomesize
FYR = (freq['TA'] + freq['TG'] + freq['CA'] + freq['CG']) / genomesize
FRY = (freq['AT'] + freq['AC'] + freq['GT'] + freq['GC']) / genomesize
J2 = FYY + FRR - FYR - FRY
listofbases = ["A", "C", "G", "T"]
for base in listofbases:
for base_2 in listofbases:
towrite = base + base_2 + '\t' + str(freq[base + base_2]/genomesize) + '\t' + species_name + '\t' + str(genomesize) + '\t' + str(J2) + '\t' + infile + '\n'
with open("resultsdinuc.csv", "a") as myfile:
myfile.write(towrite)
</code></pre>
<p><strong>Example input</strong> (the files are actually a lot bigger than this in reality):</p>
<pre><code>>NZ_NEDJ01000100.1 Halorubrum ezzemoulense DSM 17463 NODE_100_length_8476_cov_12.335, whole genome shotgun sequence
ACCGACACCATATGAGCGACGCGCCGACGACTGCGCCCTGCGACGCCTGCGGCGAGGCCACGACGGACGCGCTCGCGCGC
ACCGTCCGGCTGAGCGTCGACCGGGCGAACATCGACACCCAGCGGCTCTGCCCCGACTGCTTCGCCGACTGGATCCAGCG
CTACCAGGACCGCCTCGGCTCCGGCGACGACGGGGGCGACGAGAGCTCCGAGATCATCGTCGACTGAGGCCGAACGCGTT
CGCGTCGGCCGGCAACGTCCGTCTCGACCGCCCGTCTTAAGCCCCGGCGGGACGGACGCCGTGGTAATGGATC
>NZ_NEDJ01000108.1 Halorubrum ezzemoulense DSM 17463 NODE_108_length_6789_cov_9.46893, whole genome shotgun sequence
TGGCGTCGAGCGGCTCGGCCCGAAATTCTATTACCCCAAGTTCCGCAAGTTCTGATAGCCTCTGGCCGAAGGCAGGACGG
TCTTCATACATACCCGTTTTTGCCGGGCCAGAGGCACTAATGCTCCTGGTTCCGCCAGTCTACTGAAGAGCGTCGTCGCT
TAACGGTCGATTCGTTCCGCTCAGCGAGCCCCCGAACGAGGTAAGAGAACGCTGTAAAGGATTTATACTGCGAGGACGAG
GCCCGAGTGTGGTCGGACTCGCACGCGGGACCGTCGAAGTCGTGCCGTATCAGGAGTCGTGGAGCGACGCGTACGACGGG
GAGGTGGCTCGGTTACGGAGCGCAGTCGGTGATCGCGTCCGTCAGTTCGAACACATCGGCAGTACCGCGGTCGAGGGGAT
GGCGGCCAAGCCGATACTCGACGTGCTCGCCGTAGTCGACGAATCGACGACCGCGAGCGACCTCGTCCCAGCGCTCGAAA
CGCACGGCTACGAACGGCGCCCCGATGAGGTGGACGGGCGGGTGTTCCTCGCGAAGGGACCGCCAGAGAATCGTACGTGC
TATCTGTCGATCGCCGAAGTCGGAAGC
>NZ_NEDJ01000109.1 Halorubrum ezzemoulense DSM 17463 NODE_109_length_6759_cov_12.5481, whole genome shotgun sequence
GGCCCGATCCCGCCCGCGAGCTGCGCCGGGACCGCCACGAACCCGTCGCCGGGAGCGAGCGTCGGCTGCATGCTCCCGGT
CTCGACGTAGCTGAGGAGGACCGGTTGGCCGAGGAGCTGTCCGACGACCAGCGAGACGACGACCAGCACCGCGGCCGCTT
GGAGCGCGACGGACAGCGTTCGTTTGAGTGACATGGTGTCGAACTCGGCTCGGAGACGGACTCGGGGCGGCGACCGCCGC
GAGGCGGTACCTGTCGCGCGGCCGTCAGGTAGTCGTCGATCGCTGAACGGCGGCGTGTCCTTATAACTTCGTGGGTGGCG
GCGAACCGGATCGGGCGGCCGCCGTCGGCCCTACTCGTCGAAGGCGCCGGCGGCGAGCAGCGCGAACGGGCCGATGAACC
CGAGGCAGAACCCGAGCAGGTGGACGTACAGGTTCACGACGCTCCCGCCGCCCGAGGGGTCGGACGGGAAGCCGACGACG
GGGTAGCCGACGGCCACCAGCCCGCCGACGACCAGCAGTTCCCCGTAGCCGGGACGCGACGCGACGGCGGCCGCGTGCGT
CCGGACCGCGGGCGGGAACCGGACCTCGCTGCTGGCCGCGTACAGCACCGCGAGGAGCGCGCCCGCGACGCCGATCGCCA
GCCCCGCGACCCCGATGCCCGTCGTCGAGACCGGCAGCGCGAGGAGCGCGATCCACCCGACGAGCGCGAAGAAGACCGCC
GGCAGCGCACGCAGCGAGGCCGCGGGCGCGAAGTGTTCGCGGGCGTAGCAGTACCACAGGATCGGGAGCAGTCCGGCGAG
CGCCATGTTGATCCCGGAGAAGCCGAAGCCGATCGCGTCCCGCGGGACGGCGAGGTTCAGCGCGGACAGCGCGAACGGGA
AGGCGCCGAGGTACGTCGCGAGCGACGTGAAGAAGAGCCGCCGTCGCCCGCCAAGGACGGCGAGCGCGTAGC
</code></pre>
<p><strong>Example output</strong>:</p>
<pre><code>AA 0.0141576215 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
AC 0.0624115149 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
AG 0.0366918358 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
AT 0.0165172251 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
CA 0.0284332232 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
CC 0.0970976876 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
CG 0.1910099103 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
CT 0.0486078339 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
GA 0.0777489382 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
GC 0.1178621992 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
GG 0.092732421 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
GT 0.0658329401 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
TA 0.0093204342 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
TC 0.0878952336 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
TG 0.0337423313 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
TT 0.0198206701 Halorubrumezzemoulense 8476 -0.0503775366 ./GCF_002114285.1_ASM211428v1_genomic.fna
AA 0.0378834927 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
AC 0.0679418706 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
AG 0.0491864365 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
AT 0.0475717302 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
CA 0.0544031797 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
CC 0.0710470749 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
CG 0.1038380325 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
CT 0.06322196 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
GA 0.0739038629 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
GC 0.0694323686 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
GG 0.0614830456 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
GT 0.0715439076 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
TA 0.0363929947 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
TC 0.0840889331 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
TG 0.0617314619 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
TT 0.0462054403 Halorubrumezzemoulense 8051 -0.0258353 ./GCF_002114285.1_ASM211428v1_genomic.fna
AA 0.018964836 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
AC 0.0595285131 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
AG 0.0431976821 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
AT 0.0243645463 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
CA 0.0296325563 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
CC 0.0949558804 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
CG 0.1818780456 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
CT 0.0416172791 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
GA 0.0817858554 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
GC 0.1065455024 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
GG 0.0902146714 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
GT 0.0694060319 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
TA 0.0156723298 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
TC 0.0871855657 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
TG 0.0325299618 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
TT 0.0223890425 Halorubrumezzemoulense 7593 -0.0392466746 ./GCF_002114285.1_ASM211428v1_genomic.fna
</code></pre>
<p>How can I best improve this code? (I'm using it for hundreds of thousands of files, and when I use this, I'm using it in a bash loop:</p>
<pre><code>for FAA in $(find . -name "*.fna")
do
python3 dinucleotidescript.py $FAA
done
</code></pre>
<hr>
<p>*Nucleotides can be divided into purines (R) which are either A or G, and pyramidines (Y) which are either T or C, the equation for J2 index is:</p>
<blockquote>
<p>J2 index = FYY + FRR - FYR - FRY</p>
</blockquote>
<p>F is fraction, so FYY for example is a the fraction of the genome where a T or C is followed by another T or C.</p>
| [] | [
{
"body": "<p>Welcome back Biomage :)</p>\n\n<p>I can see you have improved your Python. However there is still room left for improvement!</p>\n\n<ul>\n<li><p>Don't put everything under the <code>if __name__ == '__main__'</code> part</p>\n\n<p>Doing so will make it less readable and other programs can't import ... | {
"AcceptedAnswerId": "202069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T13:27:27.660",
"Id": "202058",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"bioinformatics"
],
"Title": "Counting dinucletotide fractions & j2 index from a genome fasta file"
} | 202058 |
<p>I am looking for some suggestions on how to make my code cleaner and simpler. Or put another way: more elegant and idiomatic. Any other comments on quality or anything would be appreciated.</p>
<pre><code>class App extends Component {
constructor(props){
super(props);
this.state = {
colIds : ["winnie", "bob", "thomas", "george"],
cols : [
{name:"Winnnie", headerColor: "#8E6E95", id : "winnie" },
{name:"Bob", headerColor: "#39A59C", id :"bob"},
{name:"Thomas", headerColor: "#344759", id: "thomas"},
{name:"George", headerColor: "#E8741E", id: "george"}
],
cards : [
{colid: "winnie", task: "buy eggs"},
{colid: "bob", task: "clean basement"},
{colid: "thomas", task: "pack"},
{colid: "george", task: "pay bills"},
]
}
this.addCard = this.addCard.bind(this);
this.moveCardRight = this.moveCardRight.bind(this);
this.moveCardLeft = this.moveCardLeft.bind(this);
}
getColCards(colid){
let cards = this.state.cards.filter( c => c.colid == colid);
return cards;
}
addCard(colid){
let cardTask = window.prompt("Whats the task you want to add");
let currentCards = this.state.cards.slice();
let newCard = {colid: colid, task: cardTask};
currentCards.push(newCard);
this.setState({cards: currentCards});
}
moveCardRight(card){
let currentCardCol = card.colid;
let nextIndex = this.state.colIds.indexOf(currentCardCol) + 1;
if(nextIndex > this.state.colIds.length - 1 ){
return null;
}
let currentCards = this.state.cards.slice();
for(let i = 0; i < currentCards.length; i++){
if(currentCards[i].task === card.task){
currentCards[i] = {
...currentCards[i],
colid : this.state.colIds[nextIndex]
}
}
}
this.setState({cards: currentCards});
}
moveCardLeft(card){
let currentCardCol = card.colid;
let nextIndex = this.state.colIds.indexOf(currentCardCol) - 1;
if(nextIndex < 0 ){
return null;
}
let currentCards = this.state.cards.slice();
for(let i = 0; i < currentCards.length; i++){
if(currentCards[i].task === card.task){
currentCards[i] = {
...currentCards[i],
colid : this.state.colIds[nextIndex]
}
}
}
this.setState({cards: currentCards});
}
render() {
let cols =[
{name:"Winnnie", headerColor: "#8E6E95"},
{name:"Bob", headerColor: "#39A59C"},
{name:"Thomas", headerColor: "#344759"},
{name:"George", headerColor: "#E8741E"}
];
let colCards = this.state.cols.map(c => {
let cards = this.getColCards(c.id).map(c => {
return <div>
<span onClick = {() => this.moveCardLeft(c)}> {"< "} </span>
{c.task}
<span onClick = {() => this.moveCardRight(c)}> {" >"} </span>
</div>
})
return <CardCol name={c.name} headerColor={c.headerColor} addCard={this.addCard} id={c.id}>
{cards}
</CardCol>
})
return (
<div className="App">
{colCards}
</div>
);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T23:30:54.527",
"Id": "389696",
"Score": "0",
"body": "Could you please [edit] you post to include the code for the `CardCol` component? And are the `moveCardLeft()` and `moveCardRight()` functions supposed to move the cards left and... | [
{
"body": "<p>Your implementation is great and works well, but there are some things you could change.</p>\n\n<h3>Eliminate repetitive code</h3>\n\n<p>You have two large methods, <code>moveCardLeft</code> and <code>moveCardRight</code>, that do almost the same thing. These can either be combined entirely or the... | {
"AcceptedAnswerId": "202337",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T13:42:54.947",
"Id": "202059",
"Score": "3",
"Tags": [
"react.js",
"jsx"
],
"Title": "Simple Kanban component"
} | 202059 |
<p>The task is to find the median of two Arrays. I have an O(n) solution.
Can it be written in a better time complexity?</p>
<pre><code>def findMedianSortedArrays(self, A, B):
combined = []
while len(A) > 0 and len(B) > 0:
if (A[0] < B[0]):
combined.append(A.pop(0))
else:
combined.append(B.pop(0))
combined.extend(A)
combined.extend(B)
length = len(combined)
if length % 2 != 0:
return combined[length // 2]
else:
return (combined[length // 2-1] + combined[length//2]) / 2
</code></pre>
| [] | [
{
"body": "<p>According to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>, function and variable names\nshould be <em>“lowercase, with words separated by underscores as necessary to improve readability.”</em> In your case I'd suggest</p>\n\n... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T14:13:33.827",
"Id": "202065",
"Score": "0",
"Tags": [
"python",
"array",
"complexity",
"statistics"
],
"Title": "Median of two sorted arrays"
} | 202065 |
<p>This is the continuation of the questions raised in this <a href="https://codereview.stackexchange.com/questions/202043/si-type-safe-unit-calculations?noredirect=1#202043">thread</a></p>
<p>I did include the improvements that were mentioned but still feel like, I do more copies than I need to. Also I am unsure about the number of copies being made when invoking certain operations on lavlues and rvalues respectively. Is this in general a code you guys can approve of, or are there some major flaws, except for the still missing support of various operations that were mentioned in the other thread?</p>
<pre><code>#include <iostream>
template<typename Value>
struct OperatorFacade {
friend constexpr bool operator!=(Value const &lhs, Value const &rhs)
noexcept {
return !(lhs==rhs);
}
friend constexpr bool operator>(Value const &lhs, Value const &rhs) noexcept {
return rhs < lhs;
}
friend constexpr bool operator<=(Value const &lhs, Value const &rhs)
noexcept {
return !(rhs > lhs);
}
friend constexpr bool operator>=(Value const &lhs, Value const &rhs)
noexcept {
return !(rhs < lhs);
}
friend constexpr auto &operator<<(std::ostream &os, Value const &other)
noexcept {
return os << static_cast<long double>(other);
}
friend constexpr auto operator-(Value const &lhs,
Value const &rhs) noexcept {
return Value{lhs} -= rhs;
}
friend constexpr auto operator+(Value const &lhs,
Value const &rhs) noexcept {
return Value{lhs} += rhs;
}
};
// Type-safety at compile-time
template<int M = 0, int K = 0, int S = 0>
struct MksUnit {
enum { metre = M, kilogram = K, second = S };
};
template<typename U = MksUnit<>> // default to dimensionless value
class Value final : public OperatorFacade<Value<U>> {
public:
Value(Value const &other) : OperatorFacade<Value>(other) {
std::clog << "Copy ctor" << std::endl;
}
Value(Value &&other) noexcept : OperatorFacade<Value>(std::move(other)) {
std::clog << "Move ctor" << std::endl;
}
auto &operator=(Value const &other) {
std::clog << "copy assign" << std::endl;
magnitude_ = other.magnitude_;
return *this;
}
auto &operator=(Value &&other) noexcept {
std::clog << "Move assign " << std::endl;
magnitude_ = std::move(other.magnitude_);
return *this;
}
constexpr explicit Value() noexcept = default;
constexpr explicit Value(long double const &magnitude) noexcept
: magnitude_{magnitude} {}
//constexpr auto &magnitude() noexcept { return magnitude_; }
constexpr explicit operator long double() const noexcept {
return magnitude_;
}
friend constexpr bool operator==(Value const &lhs, Value const &rhs)noexcept {
return lhs.magnitude_==rhs.magnitude_;
}
friend constexpr bool operator<(Value const &lhs, Value const &rhs)noexcept {
return lhs < rhs;
}
constexpr auto &operator+=(Value const &other) noexcept {
magnitude_ += other.magnitude_;
return *this;
}
constexpr auto &operator-=(Value const &other) noexcept {
magnitude_ -= other.magnitude_;
return *this;
}
friend constexpr auto operator*(long double const &scalar, Value const &other)
noexcept {
return other*scalar;
}
constexpr auto operator*(long double const &scalar) const noexcept {
return Value{magnitude_*scalar};
}
constexpr auto &operator*=(long double const &scalar) noexcept {
magnitude_ *= scalar;
return *this;
}
private:
long double magnitude_{0.0};
};
// Some handy alias declarations
using Length = Value<MksUnit<1, 0, 0>>;
namespace si {
// A couple of convenient factory functions
constexpr auto operator "" _m(long double magnitude)noexcept {
return Length{magnitude};
}
}
// Arithmetic operators for consistent type-rich conversions of SI-Units
template<int M1, int K1, int S1, int M2, int K2, int S2>
constexpr auto operator*(Value<MksUnit<M1, K1, S1>> const &lhs,
Value<MksUnit<M2, K2, S2>> const &rhs) noexcept {
return Value<MksUnit<M1 + M2, K1 + K2, S1 + S2>>{
static_cast<long double>(lhs)*static_cast<long double>(rhs)};
}
template<int M1, int K1, int S1, int M2, int K2, int S2>
constexpr auto operator/(Value<MksUnit<M1, K1, S1>> const &lhs,
Value<MksUnit<M2, K2, S2>> const &rhs) noexcept {
return Value<MksUnit<M1 - M2, K1 - K2, S1 - S2>>{
static_cast<long double>(lhs)/static_cast<long double>(rhs)};
}
int main(){
Length l1 {10};
Length l2 {20};
l1 + l2;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T15:35:41.810",
"Id": "389223",
"Score": "0",
"body": "Are those outputs to `std::cerr` supposed to be in here, or did you forget to remove them before posting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "201... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T14:16:07.170",
"Id": "202066",
"Score": "2",
"Tags": [
"c++",
"template-meta-programming",
"type-safety",
"unit-conversion"
],
"Title": "SI type safe unit calculations (revised)"
} | 202066 |
<p>I´m a programing rookie with minor javascript skills. So I ask you for a code review since I'm not sure whether my code is ok. </p>
<p>Short explanation of my program:
I work for the heating industry. Radiators have a different heat output. The standard heat output is calculated with:</p>
<ul>
<li>heat flow = 75°C</li>
<li>heat return = 65°C</li>
<li>heat temperature = 20°C</li>
<li>a specific heat exponent</li>
</ul>
<p>My program can calculate the heat output with different values e.g.</p>
<ul>
<li>heat flow = 60°C</li>
<li>heat return = 55°C</li>
<li>heat temperature = 18°C</li>
<li>a specific heat exponent</li>
</ul>
<p>There are restrictions:</p>
<ul>
<li>Heat return must not be higher than heat flow</li>
<li>Heat temp must not be higher than heat flow and heat return</li>
<li>Input field must not be empty</li>
</ul>
<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>"use strict";
const heatFlowCalculator = {
init: function() {
this.setEventHandler();
},
getDom: {
heatFlow: document.getElementById('heatFlow'),
heatReturn: document.getElementById('heatReturn'),
heatTemp: document.getElementById('heatTemp'),
heatValue: document.getElementById('heatValue'),
heatExponent: document.getElementById('heatExponent'),
buttonResult: document.getElementById('buttonResult'),
renderResult: document.getElementById('renderResult')
},
getFixedValue: function() {
const normHeatFlow = 75,
normHeatReturn = 65,
normHeatTemp = 20,
// formula for fixed value
result = (normHeatFlow - normHeatReturn) /
(Math.log((normHeatFlow - normHeatTemp) /
(normHeatReturn - normHeatTemp)));
return result;
},
/*
Check if the user Input is valid.
Case 1: (isSmallerThan): heatFlow value has to be greater than heatReturn value
heatTemp has to be smaller than heatFlow value or heatReturn value
Case 2: (isNotEmpty): check if the input fields have values
If both cases return true, the input is valid!
*/
isInputValid: function() {
const heatFlow = this.getDom.heatFlow.value,
heatReturn = this.getDom.heatReturn.value,
heatTemp = this.getDom.heatTemp.value,
heatValue = this.getDom.heatValue.value,
heatExponent = this.getDom.heatExponent.value;
function isSmallerThan() {
return (heatReturn < heatFlow &&
heatTemp < heatFlow &&
heatTemp < heatReturn)
}
function isNotEmpty() {
return (
heatFlow !== "" ||
heatReturn !== "" ||
heatTemp !== "" ||
heatValue !== "" ||
heatExponent !== ""
) ? true : false;
}
return isSmallerThan() && isNotEmpty();
},
getTempDifference: function() {
const heatFlow = this.getDom.heatFlow.value,
heatReturn = this.getDom.heatReturn.value,
heatTemp = this.getDom.heatTemp.value,
// Formula for heat difference
result = (heatFlow - heatReturn) /
(Math.log((heatFlow - heatTemp) /
(heatReturn - heatTemp)));
return result;
},
setResult: function() {
const heatValue = this.getDom.heatValue.value,
heatExponent = this.getDom.heatExponent.value,
tempDifference = this.getTempDifference(),
fixedValue = this.getFixedValue(),
// formula to get the final result
result = Math.round(heatValue * Math.exp(
(Math.log(tempDifference / fixedValue))
* heatExponent));
if (this.isInputValid()) {
return `The calculated value is ${result}`;
} else {
return `The input is invalid! `;
}
},
// render the result of setResult() to the DOM
showResult: function() {
const showResult = this.getDom.renderResult;
showResult.textContent = this.setResult();
},
setEventHandler: function() {
const _this = this,
button = this.getDom.buttonResult;
button.addEventListener('click', function() {
_this.showResult();
}, false);
}
};
heatFlowCalculator.init();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
input {
display: block;
}
#renderResult {
margin-top: 25px;
}
</style>
</head>
<body>
Heat flow<input type="number" name="HeatFlow" id="heatFlow" placeholder="70">
Heat return<input type="number" name="HeatReturn" id="heatReturn" placeholder="60">
Heat temperature<input type="number" name="HeatTemp" id="heatTemp" placeholder="20">
Heat value<input type="number" name="HeatValue" id="heatValue" placeholder="2100">
Heat exponent<input type="number" name="HeatExponent" id="heatExponent" placeholder="1.3211">
<br>
<button id="buttonResult">Calculate</button>
<div id="renderResult"></div>
<script src="heatflow.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>The flow of this app is,</p>\n\n<ol>\n<li>Get the input values</li>\n<li>Check if the input values are valid</li>\n<li>Calculate,output the value or \"invalid\"</li>\n</ol>\n\n<p>Since you use const,I assume you understand/prefer es6,arrow function,etc...</p>\n\n<p>For 1. ,you can simplify your ge... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T15:14:15.497",
"Id": "202071",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"calculator",
"event-handling"
],
"Title": "Calculate the heat flow (for radiators)"
} | 202071 |
<p>Code performs well for small matrices, but gives memory error for large matrices of size 63000x93000, even when I am using server with memory of 64GB, space 100GB, swap 40GB.</p>
<pre><code># -*- coding: utf-8 -*-
from numpy import array, argmax, concatenate
import csv
def uread(Filename):
UFILE = open(Filename, 'r')
with UFILE:
READER = csv.reader(UFILE)
for i in READER:
yield i
ufinal = uread('U.csv')
U = []
for k in ufinal:
TEMP = []
for j in k:
TEMP.append(eval(j))
U.append(TEMP)
del TEMP
del k
sfinal = uread('s.csv')
S = []
for s in sfinal:
for t in s:
S.append(eval(t))
del t
EIGVALfinal = uread('EIGVAL.csv')
EIGVAL = []
for e in EIGVALfinal:
for l in e:
EIGVAL.append(eval(l))
del l
EIGVECfinal = uread('EIGVEC.csv')
EIGVEC = []
for e in EIGVECfinal:
for l in e:
EIGVEC.append(eval(l))
del l
NEW_U = []
NEW_EIGVAL = []
NEW_EIGVEC = []
for i in range(len(S)):
if S[i] > 0.001:
NEW_U.append(U[i])
NEW_EIGVAL.append(EIGVAL[i])
NEW_EIGVEC.append(EIGVEC[i])
del EIGVAL
del EIGVEC
# Select the first r columns of u corresponding to the r principle Eigenvector of
# MatrixForEigenvalues
TRANSPOSE_NEW_EIGVEC = array(NEW_EIGVEC).real.T # Done for easy accesiblity of matrix
TRANSPOSE_MATRIX_U = array(NEW_U).real.T # Done for easy accesiblity of matrix
FINAL_ARRAY_EIGVAL = []
FINAL_ARRAY_EIGVEC = []
FINAL_MATRIX_U = []
for i in range(len(array(NEW_EIGVAL).real)):
j = argmax(array(NEW_EIGVAL).real)
FINAL_ARRAY_EIGVAL.append((array(NEW_EIGVAL).real)[j])
FINAL_ARRAY_EIGVEC.append(TRANSPOSE_NEW_EIGVEC[j])
FINAL_MATRIX_U.append(TRANSPOSE_MATRIX_U[j])
TRANSPOSE_NEW_EIGVEC = concatenate((TRANSPOSE_NEW_EIGVEC[:j], TRANSPOSE_NEW_EIGVEC[j+1:]))
TRANSPOSE_MATRIX_U = concatenate((TRANSPOSE_MATRIX_U[:j], TRANSPOSE_MATRIX_U[j+1:]))
RESULT_MATRIX_U = array(FINAL_MATRIX_U).T # This is the actual R
r_file = open('r.csv', 'w')
with r_file:
WRITER = csv.writer(r_file)
WRITER.writerows(RESULT_MATRIX_U)
print(RESULT_MATRIX_U)
del FINAL_MATRIX_U
</code></pre>
| [] | [
{
"body": "<p>It looks like you are creating duplicate <code>numpy.array</code> objects.</p>\n\n<pre><code>for i in range(len(array(NEW_EIGVAL).real)):\n j = argmax(array(NEW_EIGVAL).real)\n FINAL_ARRAY_EIGVAL.append((array(NEW_EIGVAL).real)[j])\n #...\n</code></pre>\n\n<p>Each iteration creates <code>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T17:30:19.330",
"Id": "202076",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"matrix",
"numpy",
"memory-optimization"
],
"Title": "Eigenvector calculation involving three matrices"
} | 202076 |
<p>Is the following in poor taste?</p>
<p>This would be contained within a <code>groupme</code> module. Does it make sense to re-define a <code>RequestException</code> class within this module? If I didn't, wouldn't consumers of the module need to be aware of the underlying <code>requests.exceptions.RequestException</code> being thrown:</p>
<pre><code>...
class Bot(object):
API_BASE_URL = 'http://api.groupme.com/v3/bots/{route}'
API_POST_URL = API_BASE_URL.format(route='post')
def __init__(self, bot_id):
self.bot_id = bot_id
def post(self, message):
try:
data = {'bot_id': self.bot_id, 'message': message}
response = requests.post(Bot.API_POST_URL, data)
response.raise_for_status()
except requests.exceptions.RequestException as ex:
raise RequestException('Failed to post bot message') from ex
class RequestException(Exception):
...
</code></pre>
<p>And the <code>groupme</code> module / above code would then be used in the following manner:</p>
<pre><code>import groupme
bot = groupme.Bot('abcdef123')
try:
bot.post('Hello, world!')
except groupme.RequestException as ex: # this seems cleaner as opposed to requests.exceptions.RequestException
print(ex)
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Does it make sense to re-define a RequestException class within this module?</p>\n</blockquote>\n\n<p>Yes, that makes total sense. Library users should <em>never</em> be expected to catch dependency exceptions. If there's even the slightest chance a user needs to interact with a de... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T17:45:36.930",
"Id": "202078",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python - Simple wrapper class for a bot API"
} | 202078 |
<p>I implemented a Double linked list in c++ to practice. I reviewed the code myself and I would like others perspective about the improvements that could be made. I have also noticed that I don't take fully advantage of many c++ features nor use them in my code. Any comments about significant performance improvements are also appreciated!</p>
<p><strong>Header File</strong> (List.h)</p>
<pre><code>#pragma once
class List {
private:
struct Node {
int x;
Node* next;
Node* prev;
};
Node * head;
Node * tail;
public:
List();
List(const int x);
void printList();
void insert(const int x);
unsigned short length();
bool deleteList();
bool isEmpty();
bool isSorted();
void reversePrint();
void sortedInsert(const int x);
List operator+(List const &obj1);
void operator+(const int x);
};
</code></pre>
<p><strong>Source File</strong> (Source.cpp)</p>
<pre><code>#include <iostream>
#include "List.h"
using std::cout;
List::List() {
head = nullptr;
}
List::List(const int x) {
List();
insert(x);
}
List List::operator+(List const &obj1) {
List newList;
Node* tmp = head;
Node* tmp2 = obj1.head;
while (tmp != nullptr) {
newList.insert(tmp->x);
tmp = tmp->next;
}
while (tmp2 != nullptr) {
newList.insert(tmp2->x);
tmp2 = tmp2->next;
}
return newList;
}
void List::operator+(const int x) {
insert(x);
}
void List::printList() {
if (head == nullptr) {
return;
}
Node* tmp = head;
while (tmp != nullptr) {
cout << tmp->x << " ";
tmp = tmp->next;
}
cout << '\n';
}
void List::insert(const int x) {
// If list is empty
if (head == nullptr) {
head = new Node;
head->x = x;
head->next = nullptr;
head->prev = nullptr;
return;
}
// Inserting at the end
Node* copy = head;
while (copy->next != nullptr) {
copy = copy->next;
}
// Inserting at the end
Node* tmp2 = new Node;
tmp2->x = x;
tmp2->next = nullptr;
copy->next = tmp2;
tmp2->prev = copy;
// Save the last node (tail)
tail = tmp2;
}
unsigned short List::length() {
short c = 0;
Node* copy = head;
while (copy != nullptr) {
c++;
copy = copy->next;
}
return c;
}
void List::reversePrint() {
Node* tmp = tail;
while (tmp->prev != nullptr) {
cout << tmp->x << ' ';
tmp = tmp->prev;
}
cout << tmp->x << '\n';
}
bool List::deleteList() {
if (head == nullptr)
return false;
Node* tmp = head;
Node* tmp2 = head;
head = nullptr;
while (tmp != nullptr) {
tmp = tmp->next;
delete tmp2;
tmp2 = tmp;
}
return true;
}
bool List::isEmpty() {
if (length() == 0) {
return true;
}
else {
return false;
}
}
void List::sortedInsert(const int x) {
if (isEmpty()) {
insert(x);
return;
}
Node* copy = head;
while (copy != nullptr) {
if (copy->x > x) {
//Insertar antes
Node* tmp = new Node;
tmp->x = x;
head = tmp;
tmp->next = copy;
tmp->prev = nullptr;
copy->prev = tmp;
break;
}
if (copy->next == nullptr) {
insert(x);
break;
}
if ((x >= copy->x) && (x < copy->next->x)) {
// insertar Despues
Node* tmp = new Node;
tmp->x = x;
tmp->prev = copy;
tmp->next = copy->next;
copy->next->prev = tmp;
copy->next = tmp; // -> next next
break;
}
copy = copy->next;
}
}
bool List::isSorted() {
Node* tmp = head;
while (tmp->next != nullptr) {
if (tmp->x > tmp->next->x) {
return false;
}
tmp = tmp->next;
}
return true;
}
</code></pre>
<p><strong>Additional notes:</strong>
The sortedInsert(x) function would only work properly if it is used with a new list. It wouldn't work if first insert(x) is used and then sortedInsert(x)</p>
| [] | [
{
"body": "<p>Here are a few suggestions, in order of importance</p>\n<h2>Delete nodes in the destructor</h2>\n<p>Right now, you are relying on users to call <code>deleteList</code> in order to delete the nodes in the List. Modern C++ uses the concept of <a href=\"https://en.wikipedia.org/wiki/Resource_acquisit... | {
"AcceptedAnswerId": "202086",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T19:08:55.677",
"Id": "202082",
"Score": "6",
"Tags": [
"c++",
"performance",
"linked-list"
],
"Title": "Double Linked-List Implementation"
} | 202082 |
<p>I am trying to improve the quality of my code as well as trying to study the <code>Heap</code> data structure. I have implemented a minHeap (Heap in which minimum value nodes have higher priority). Ref: <a href="https://www.geeksforgeeks.org/binary-heap/" rel="nofollow noreferrer">link1</a>, <a href="https://www.tutorialspoint.com/data_structures_algorithms/heap_data_structure.htm" rel="nofollow noreferrer">link2</a>, <a href="https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/tutorial/" rel="nofollow noreferrer">link3</a>. This is the commented code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <limits>
// Class for throwing `out of range` exceptions
class OutofRange
{
std::string error = "The index is out of range.";
public:
OutofRange()
{
}
std::string what()
{
return error;
}
};
// Class for MinHeap. The `arr` holds the heap elements. The `capacity` indicates total
// allocated space for the heap. The `length` indicates size of the heap.
template<typename T>
class MinHeap
{
T* arr;
size_t capacity;
size_t length;
public:
MinHeap(size_t);
T get_min();
void heapify(int);
void insert(T);
T delete_min();
T delete_by_index(int);
void print_heap();
};
// Constructor for the heap
template<typename T>
MinHeap<T>::MinHeap(size_t n)
{
arr = new T[n];
capacity = n;
length = 0;
}
// Return the minimum node (root)
template<typename T>
T MinHeap<T>::get_min()
{
if(length > 0)
{
return arr[0];
}
else
{
std::cout << "Error: Invalid access" << std::endl;
throw OutofRange{};
}
}
// Function to put a node at the right position if it has the possibility to move up
// in the heap
template<typename T>
void MinHeap<T>::heapify(int start)
{
for(int i = start; i > 0; i = (i - 1) / 2)
{
if(arr[i] < arr[(i - 1) / 2])
{
std::swap(arr[i], arr[(i - 1) / 2]);
}
else
{
return;
}
}
}
// Inserts nodes to heap
template<typename T>
void MinHeap<T>::insert(T data)
{
// Check if capacity is reached
if(length == capacity)
{
std::cout << "Error: Heap capacity reached" << std::endl;
return;
}
// Insert the node
arr[length] = data;
this -> heapify(length);
length++;
}
// Deletes the minimum value node (root)
template<typename T>
T MinHeap<T>::delete_min()
{
// Check if heap has any elements/ nodes
if(length == 0)
{
std::cout << "Error: Invalid Access" << std::endl;
throw OutofRange{};
}
// Replace minimum node (root) with the last node
T del_min = arr[0];
std::swap(arr[0], arr[length - 1]);
arr[length - 1] = (T)NULL;
length--;
// Bring the new root to correct position based on value
for(size_t i = 0; i < length - 1 && length > 0;)
{
int min_child;
if(2 * i + 1 > length - 1)
{
break;
}
if(2 * i + 2 > length - 1)
{
min_child = 2 * i + 1;
}
else
{
min_child = arr[2 * i + 1] <= arr[2 * i + 2] ? 2 * i + 1 : 2 * i + 2;
}
if(arr[i] > arr[min_child])
{
std::swap(arr[i], arr[min_child]);
}
i = min_child;
}
return del_min;
}
// Deletes a node by index
template<typename T>
T MinHeap<T>::delete_by_index(int index)
{
int del_val = arr[index];
T min_val = std::numeric_limits<T>::min();
arr[index] = min_val;
this -> heapify(index);
this -> delete_min();
return del_val;
}
// Print the heap
template<typename T>
void MinHeap<T>::print_heap()
{
std::cout << "The Min Heap: " << std::endl;
if(length == 0)
{
std::cout << "Empty" << std::endl;
}
for(size_t i = 0; i < length; i++)
{
std::cout << arr[i] << "\t";
}
std::cout << std::endl;
}
int main()
{
try
{
MinHeap<int> h1{10};
int del_val;
std::vector<int> input = {35, 33, 42, 10, 14, 19, 27, 44, 26, 31};
// Insert input values to the heap
for(size_t i = 0; i < input.size(); i++)
{
h1.insert(input[i]);
h1.print_heap();
}
// Check if minimum value/ highest priority can be accessed
std::cout << "Current Root: " << h1.get_min() << std::endl;
// Delete by index test case
del_val = h1.delete_by_index(2);
std::cout << "Delete by index: " << del_val << std::endl;
h1.print_heap();
// Delete the minimum value
for(size_t i = 0; i < input.size(); i++)
{
del_val = h1.delete_min();
std::cout << "Deleted value: " << del_val << std::endl;
h1.print_heap();
}
// Uncomment to test exception in deletion if delete_by_index test case is not present.
//del_val = h1.delete_min();
//std::cout << "Deleted value: " << del_val << std::endl;
// Uncomment to test exception in accessing minimum value(root)
//h1.get_min();
}
// Catch the out of range exceptions
catch(OutofRange& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
</code></pre>
<ol>
<li><p>Are heaps used for data types other than numeric? Even though my implementation uses templates, it does depend on <code>numeric_limits</code>. I am assuming that if the data type is not numeric, it can converted to a custom data type like shown below:</p>
<pre><code>struct custom_type
{
T val;
int priority;
custom_type(T v, int p)
{
val = v;
priority = p;
}
// Overloads for comparison operators which utilize priority field.
/*
-------
-------
*/
};
</code></pre></li>
<li><p>Is there a better way to handle <code>out of range</code> errors without using exceptions and not returning a value such as <code>INT_MAX</code>, <code>INT_MIN</code> or zero?</p></li>
<li><p>What could be other possible improvements in the code?</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T08:47:13.963",
"Id": "389322",
"Score": "3",
"body": "I realize that implementing a heap is a good learning exercise, but if you ever want a better implementation: [`std::make_heap`](https://en.cppreference.com/w/cpp/algorithm/make_... | [
{
"body": "<h1>Memory management</h1>\n\n<p>You never <code>delete[] arr;</code>, which leaks memory. Not a good thing! There are multiple ways to fix this:</p>\n\n<ul>\n<li><p>Adding correct calls to <code>delete[] arr;</code> in the right places (remember exceptions, assignments and so on!), which is rather b... | {
"AcceptedAnswerId": "202102",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-20T23:29:48.990",
"Id": "202093",
"Score": "8",
"Tags": [
"c++",
"error-handling",
"generics",
"heap"
],
"Title": "Heap implementation for numeric types"
} | 202093 |
<p>In my ongoing quest to demonstrate how VBA code can absolutely be object-oriented, I've started implementing a game of <strong>Battleship</strong> in pure VBA.</p>
<p>This is a rather large project, so I'll split the reviewing across multiple posts. This first one covers the coordinate/grid system.</p>
<p>Each module in the project is annotated with a <code>@Folder</code> annotation, which <a href="http://www.github.com/rubberduck-vba/Rubberduck" rel="noreferrer">Rubberduck</a> uses to organize the modules into a folder hierarchy, making the rather large project easy to navigate despite the poorly tooled IDE; other annotations include:</p>
<ul>
<li><code>@IgnoreModule</code> prevents static code analysis from firing results in that module.</li>
<li><code>@Description</code> will eventually translate into <code>VB_Description</code> attributes; until then they serve as descriptive comments for public members, where appropriate.</li>
</ul>
<p>The <strong>GridCoord</strong> class module has a <code>VB_PredeclaredId = True</code> module attribute which gives it a <em>default instance</em>; I'm only ever using this default instance to invoke the <code>Create</code> factory method, which serves as a public parameterized constructor for the class.</p>
<p>The <code>ToString</code> method gives a representation in the form of <code>(x,y)</code> that can be used internally, and easily round-trips back to a <code>GridCoord</code> instance; the <code>ToA1String</code> method yields a string representation that can easily be used by the game to display e.g. the selected grid coordinate. That format is just for display, and does not round-trip.</p>
<pre><code>'@Folder("Battleship.Model")
'@IgnoreModule UseMeaningfulName; X and Y are perfectly fine names here.
Option Explicit
Private Type TGridCoord
X As Long
Y As Long
End Type
Private this As TGridCoord
Public Function Create(ByVal xPosition As Long, ByVal yPosition As Long) As GridCoord
With New GridCoord
.X = xPosition
.Y = yPosition
Set Create = .Self
End With
End Function
Public Function FromString(ByVal coord As String) As GridCoord
coord = Replace(Replace(coord, "(", vbNullString), ")", vbNullString)
Dim coords As Variant
coords = Split(coord, ",")
Dim xPosition As Long
xPosition = coords(LBound(coords))
Dim yPosition As Long
yPosition = coords(UBound(coords))
Set FromString = Create(xPosition, yPosition)
End Function
Public Property Get X() As Long
X = this.X
End Property
Public Property Let X(ByVal value As Long)
this.X = value
End Property
Public Property Get Y() As Long
Y = this.Y
End Property
Public Property Let Y(ByVal value As Long)
this.Y = value
End Property
Public Property Get Self() As GridCoord
Set Self = Me
End Property
Public Property Get Default() As GridCoord
Set Default = New GridCoord
End Property
Public Function ToString() As String
ToString = "(" & this.X & "," & this.Y & ")"
End Function
Public Function ToA1String() As String
ToA1String = Chr$(64 + this.X) & this.Y
End Function
Public Function Equals(ByVal other As GridCoord) As Boolean
Equals = other.X = this.X And other.Y = this.Y
End Function
Public Function Offset(Optional ByVal xOffset As Long, Optional ByVal yOffset As Long) As GridCoord
Set Offset = GridCoord.Create(this.X + xOffset, this.Y + yOffset)
End Function
Public Function IsAdjacent(ByVal other As GridCoord) As Boolean
If other.Y = this.Y Then
IsAdjacent = other.X = this.X - 1 Or other.X = this.X + 1
ElseIf other.X = this.X Then
IsAdjacent = other.Y = this.Y - 1 Or other.Y = this.Y + 1
End If
End Function
</code></pre>
<p>The <strong>GridCoordTests</strong> module is a Rubberduck test module that includes 16 passing tests that demonstrate usage and validate the type's behavior.</p>
<pre><code>'@TestModule
'@Folder("Tests")
Option Explicit
Option Private Module
Private Assert As Rubberduck.AssertClass
'Private Fakes As Rubberduck.FakesProvider
'@ModuleInitialize
Public Sub ModuleInitialize()
Set Assert = CreateObject("Rubberduck.AssertClass")
'Set Fakes = CreateObject("Rubberduck.FakesProvider")
End Sub
'@ModuleCleanup
Public Sub ModuleCleanup()
Set Assert = Nothing
'Set Fakes = Nothing
End Sub
'@TestMethod
Public Sub CreatesAtSpecifiedXCoordinate()
Const expectedX As Long = 42
Const expectedY As Long = 74
Dim sut As GridCoord
Set sut = GridCoord.Create(expectedX, expectedY)
Assert.AreEqual expectedX, sut.X, "X coordinate mismatched."
Assert.AreEqual expectedY, sut.Y, "Y coordinate mismatched."
End Sub
'@TestMethod
Public Sub DefaultIsZeroAndZero()
Const expectedX As Long = 0
Const expectedY As Long = 0
Dim sut As GridCoord
Set sut = GridCoord.Default
Assert.AreEqual expectedX, sut.X, "X coordinate mismatched."
Assert.AreEqual expectedY, sut.Y, "Y coordinate mismatched."
End Sub
'@TestMethod
Public Sub OffsetAddsX()
Const xOffset As Long = 1
Const yOffset As Long = 0
Dim initial As GridCoord
Set initial = GridCoord.Default
Dim sut As GridCoord
Set sut = GridCoord.Default
Dim actual As GridCoord
Set actual = sut.Offset(xOffset, yOffset)
Assert.AreEqual initial.X + xOffset, actual.X
End Sub
'@TestMethod
Public Sub OffsetAddsY()
Const xOffset As Long = 0
Const yOffset As Long = 1
Dim initial As GridCoord
Set initial = GridCoord.Default
Dim sut As GridCoord
Set sut = GridCoord.Default
Dim actual As GridCoord
Set actual = sut.Offset(xOffset, yOffset)
Assert.AreEqual initial.Y + yOffset, actual.Y
End Sub
'@TestMethod
Public Sub FromToString_RoundTrips()
Dim initial As GridCoord
Set initial = GridCoord.Default
Dim asString As String
asString = initial.ToString
Dim sut As GridCoord
Set sut = GridCoord.FromString(asString)
Assert.AreEqual initial.X, sut.X, "X coordinate mismatched."
Assert.AreEqual initial.Y, sut.Y, "Y coordinate mismatched."
End Sub
'@TestMethod
Public Sub ToStringFormat_NoSpaceCommaSeparatedInParentheses()
Dim sut As GridCoord
Set sut = GridCoord.Default
Dim expected As String
expected = "(" & sut.X & "," & sut.Y & ")"
Dim actual As String
actual = sut.ToString
Assert.AreEqual expected, actual
End Sub
'@TestMethod
Public Sub EqualsReturnsTrueForMatchingCoords()
Dim other As GridCoord
Set other = GridCoord.Default
Dim sut As GridCoord
Set sut = GridCoord.Default
Assert.IsTrue sut.Equals(other)
End Sub
'@TestMethod
Public Sub EqualsReturnsFalseForMismatchingCoords()
Dim other As GridCoord
Set other = GridCoord.Default.Offset(1)
Dim sut As GridCoord
Set sut = GridCoord.Default
Assert.IsFalse sut.Equals(other)
End Sub
'@TestMethod
Public Sub GivenOneLeftAndSameY_IsAdjacentReturnsTrue()
Dim other As GridCoord
Set other = GridCoord.Create(1, 1)
Dim sut As GridCoord
Set sut = GridCoord.Create(2, 1)
Assert.IsTrue sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenTwoLeftAndSameY_IsAdjacentReturnsFalse()
Dim other As GridCoord
Set other = GridCoord.Create(1, 1)
Dim sut As GridCoord
Set sut = GridCoord.Create(3, 1)
Assert.IsFalse sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenOneRightAndSameY_IsAdjacentReturnsTrue()
Dim other As GridCoord
Set other = GridCoord.Create(3, 1)
Dim sut As GridCoord
Set sut = GridCoord.Create(2, 1)
Assert.IsTrue sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenTwoRightAndSameY_IsAdjacentReturnsFalse()
Dim other As GridCoord
Set other = GridCoord.Create(5, 1)
Dim sut As GridCoord
Set sut = GridCoord.Create(3, 1)
Assert.IsFalse sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenOneDownAndSameX_IsAdjacentReturnsTrue()
Dim other As GridCoord
Set other = GridCoord.Create(1, 2)
Dim sut As GridCoord
Set sut = GridCoord.Create(1, 1)
Assert.IsTrue sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenTwoDownAndSameX_IsAdjacentReturnsFalse()
Dim other As GridCoord
Set other = GridCoord.Create(1, 3)
Dim sut As GridCoord
Set sut = GridCoord.Create(1, 1)
Assert.IsFalse sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenOneUpAndSameX_IsAdjacentReturnsTrue()
Dim other As GridCoord
Set other = GridCoord.Create(1, 1)
Dim sut As GridCoord
Set sut = GridCoord.Create(1, 2)
Assert.IsTrue sut.IsAdjacent(other)
End Sub
'@TestMethod
Public Sub GivenTwoUpAndSameX_IsAdjacentReturnsFalse()
Dim other As GridCoord
Set other = GridCoord.Create(1, 1)
Dim sut As GridCoord
Set sut = GridCoord.Create(1, 3)
Assert.IsFalse sut.IsAdjacent(other)
End Sub
</code></pre>
<hr>
<p>The <strong>PlayerGrid</strong> class also has a <code>VB_PredeclaredId = True</code> module attribute; again, the class' <em>default instance</em> is never used to store any state. The <code>Create</code> method serves as a public parameterized constructor for the class. The type represents a player's game grid, and encapsulates its state.</p>
<pre><code>'@Folder("Battleship.Model.Player")
Option Explicit
Private Const KnownGridStateErrorMsg As String _
= "Specified coordinate is not in an unknown state."
Private Const CannotAddShipAtPositionMsg As String _
= "Cannot add a ship of this size at this position."
Private Const CannotAddMoreShipsMsg As String _
= "Cannot add more ships to this grid."
Public Enum PlayerGridErrors
KnownGridStateError = vbObjectError Or 127
CannotAddShipAtPosition
CannotAddMoreShips
End Enum
Public Enum AttackResult
Miss
Hit
Sunk
End Enum
Public Enum GridState
'@Description("Content at this coordinate is unknown.")
Unknown = -1
'@Description("Unconfirmed friendly ship position.")
PreviewShipPosition = 0
'@Description("Confirmed friendly ship position.")
ShipPosition = 1
'@Description("Unconfirmed invalid/overlapping ship position.")
InvalidPosition = 2
'@Description("No ship at this coordinate.")
PreviousMiss = 3
'@Description("An enemy ship occupies this coordinate.")
PreviousHit = 4
End Enum
Private Type TPlayGrid
Id As Byte
ships As Collection
State(1 To Globals.GridSize, 1 To Globals.GridSize) As GridState
End Type
Private this As TPlayGrid
Public Function Create(ByVal grid As Byte) As PlayerGrid
With New PlayerGrid
.GridId = grid
Set Create = .Self
End With
End Function
'@Description("Gets the ID of this grid. 1 for Player1, 2 for Player2.")
Public Property Get GridId() As Byte
GridId = this.Id
End Property
Public Property Let GridId(ByVal value As Byte)
this.Id = value
End Property
Public Property Get Self() As PlayerGrid
Set Self = Me
End Property
'@Description("Gets the number of ships placed on the grid.")
Public Property Get ShipCount() As Long
ShipCount = this.ships.Count
End Property
Private Sub Class_Initialize()
Set this.ships = New Collection
Dim currentX As Long
For currentX = LBound(this.State, 1) To UBound(this.State, 1)
Dim currentY As Long
For currentY = LBound(this.State, 2) To UBound(this.State, 2)
this.State(currentX, currentY) = GridState.Unknown
Next
Next
End Sub
'@Description("Adds the specified ship to the grid. Throws if position is illegal.")
Public Sub AddShip(ByVal item As IShip)
If Not CanAddShip(item.GridPosition, item.orientation, item.size) Then
Err.Raise PlayerGridErrors.CannotAddShipAtPosition, TypeName(Me), CannotAddShipAtPositionMsg
End If
If this.ships.Count >= Globals.ShipsPerGrid Then
Err.Raise PlayerGridErrors.CannotAddMoreShips, TypeName(Me), CannotAddMoreShipsMsg
End If
' will throw a duplicate key error if item.Name is already in collection
this.ships.Add item, item.Name
Dim currentX As Long
For currentX = item.GridPosition.X To item.GridPosition.X + IIf(item.orientation = Horizontal, item.size - 1, 0)
Dim currentY As Long
For currentY = item.GridPosition.Y To item.GridPosition.Y + IIf(item.orientation = Vertical, item.size - 1, 0)
this.State(currentX, currentY) = GridState.ShipPosition
Next
Next
End Sub
'@Description("Gets a value indicating whether a ship can be added at the specified position/direction/size.")
Public Function CanAddShip(ByVal position As GridCoord, ByVal direction As ShipOrientation, ByVal shipSize As Byte) As Boolean
CanAddShip = (position.X + IIf(direction = Horizontal, shipSize - 1, 0) <= UBound(this.State, 1)) _
And (position.Y + IIf(direction = Vertical, shipSize - 1, 0) <= UBound(this.State, 2)) _
And (position.X > 0 And position.Y > 0) _
And IntersectsAny(position, direction, shipSize) Is Nothing
End Function
'@Description("Gets a value indicating whether the specified position/direction/size intersects with any existing ship.")
Public Function IntersectsAny(ByVal position As GridCoord, ByVal direction As ShipOrientation, ByVal shipSize As Byte) As GridCoord
Dim currentShip As IShip
For Each currentShip In this.ships
Dim intersecting As GridCoord
Set intersecting = currentShip.Intersects(Ship.Create("InsersectCheck", shipSize, direction, position))
If Not intersecting Is Nothing Then
Set IntersectsAny = intersecting
Exit Function
End If
Next
End Function
'@Description("Gets a value indicating whether the specified position/direction/size has any adjacent existing ship.")
Public Function HasAdjacentShip(ByVal position As GridCoord, ByVal direction As ShipOrientation, ByVal shipSize As Byte) As Boolean
Dim positionX As Long
Dim positionY As Long
If direction = Horizontal Then
positionY = position.Y
For positionX = position.X To position.X + shipSize - 1
If HasAnyAdjacentShips(GridCoord.Create(positionX, positionY)) Then
HasAdjacentShip = True
Exit Function
End If
Next
Else
positionX = position.X
For positionY = position.Y To position.Y + shipSize - 1
If HasAnyAdjacentShips(GridCoord.Create(positionX, positionY)) Then
HasAdjacentShip = True
Exit Function
End If
Next
End If
End Function
Private Function HasAnyAdjacentShips(ByVal coord As GridCoord) As Boolean
Dim currentX As Long
Dim currentY As Long
Dim currentShip As IShip
For Each currentShip In this.ships
If currentShip.orientation = Horizontal Then
currentY = currentShip.GridPosition.Y
For currentX = currentShip.GridPosition.X To currentShip.GridPosition.X + currentShip.size - 1
If GridCoord.Create(currentX, currentY).IsAdjacent(coord) Then
HasAnyAdjacentShips = True
Exit Function
End If
Next
Else
currentX = currentShip.GridPosition.X
For currentY = currentShip.GridPosition.Y To currentShip.GridPosition.Y + currentShip.size - 1
If GridCoord.Create(currentX, currentY).IsAdjacent(coord) Then
HasAnyAdjacentShips = True
Exit Function
End If
Next
End If
Next
End Function
'@Description("(side-effecting) Attempts a hit at the specified position; returns the result of the attack, and a reference to the hit ship if successful.")
Public Function TryHit(ByVal position As GridCoord, Optional ByRef hitShip As IShip) As AttackResult
If this.State(position.X, position.Y) = GridState.PreviousHit Or _
this.State(position.X, position.Y) = GridState.PreviousMiss Then
Err.Raise PlayerGridErrors.KnownGridStateError, TypeName(Me), KnownGridStateErrorMsg
End If
Dim currentShip As IShip
For Each currentShip In this.ships
If currentShip.Hit(position) Then
this.State(position.X, position.Y) = GridState.PreviousHit
If currentShip.IsSunken Then
TryHit = Sunk
Else
TryHit = Hit
End If
Set hitShip = currentShip
Exit Function
End If
Next
this.State(position.X, position.Y) = GridState.PreviousMiss
TryHit = Miss
End Function
'@Description("Gets the GridState value at the specified position.")
Public Property Get State(ByVal position As GridCoord) As GridState
On Error Resume Next
State = this.State(position.X, position.Y)
On Error GoTo 0
End Property
'@Description("Gets a 2D array containing the GridState of each coordinate in the grid.")
Public Property Get StateArray() As Variant
Dim result(1 To Globals.GridSize, 1 To Globals.GridSize) As Variant
Dim currentX As Long
For currentX = 1 To Globals.GridSize
Dim currentY As Long
For currentY = 1 To Globals.GridSize
Dim value As GridState
value = this.State(currentX, currentY)
result(currentX, currentY) = IIf(value = Unknown, Empty, value)
Next
Next
StateArray = result
End Property
'@Description("Gets a value indicating whether the ship at the specified position is sunken.")
Public Property Get IsSunken(ByVal position As GridCoord) As Boolean
Dim currentShip As IShip
For Each currentShip In this.ships
If currentShip.IsSunken Then
If currentShip.orientation = Horizontal Then
If currentShip.GridPosition.Y = position.Y Then
If position.X >= currentShip.GridPosition.X And _
position.X <= currentShip.GridPosition.X + currentShip.size - 1 _
Then
IsSunken = True
Exit Property
End If
End If
End If
End If
Next
End Property
'@Descrition("Gets a value indicating whether all ships have been sunken.")
Public Property Get IsAllSunken() As Boolean
Dim currentShip As IShip
For Each currentShip In this.ships
If Not currentShip.IsSunken Then
IsAllSunken = False
Exit Property
End If
Next
IsAllSunken = True
End Property
'@Description("Returns the GridCoord of known hits around the specified hit position.")
Public Function GetHitArea(ByVal position As GridCoord) As Collection
Debug.Assert this.State(position.X, position.Y) = GridState.PreviousHit
Dim result As Collection
Set result = New Collection
Dim currentX As Long
Dim currentY As Long
currentX = position.X
currentY = position.Y
Dim currentPosition As GridCoord
If position.X > 1 Then
Do While currentX >= 1 And this.State(currentX, currentY) = GridState.PreviousHit
On Error Resume Next
With GridCoord.Create(currentX, currentY)
result.Add .Self, .ToString
End With
On Error GoTo 0
currentX = currentX - 1
Loop
End If
currentX = position.X
currentY = position.Y
If position.X < Globals.GridSize Then
Do While currentX <= Globals.GridSize And this.State(currentX, currentY) = GridState.PreviousHit
On Error Resume Next
With GridCoord.Create(currentX, currentY)
result.Add .Self, .ToString
End With
On Error GoTo 0
currentX = currentX + 1
Loop
End If
currentX = position.X
currentY = position.Y
If position.Y > 1 Then
Do While currentY >= 1 And this.State(currentX, currentY) = GridState.PreviousHit
On Error Resume Next
With GridCoord.Create(currentX, currentY)
result.Add .Self, .ToString
End With
On Error GoTo 0
currentY = currentY - 1
Loop
End If
currentX = position.X
currentY = position.Y
If position.Y < Globals.GridSize Then
Do While currentY <= Globals.GridSize And this.State(currentX, currentY) = GridState.PreviousHit
On Error Resume Next
With GridCoord.Create(currentX, currentY)
result.Add .Self, .ToString
End With
On Error GoTo 0
currentY = currentY + 1
Loop
End If
Set GetHitArea = result
End Function
'@Description("Removes confirmed ship positions from grid state.")
Public Sub Scramble()
Dim currentX As Long
For currentX = 1 To Globals.GridSize
Dim currentY As Long
For currentY = 1 To Globals.GridSize
If this.State(currentX, currentY) = GridState.ShipPosition Then
this.State(currentX, currentY) = GridState.Unknown
End If
Next
Next
End Sub
</code></pre>
<p>The <strong>PlayerGridTests</strong> module is a Rubberduck test module including 19 passing tests that demonstrate usage and validate the type's behavior.</p>
<pre><code>'@TestModule
'@Folder("Tests")
Option Explicit
Option Private Module
Private Assert As Rubberduck.AssertClass
'Private Fakes As Rubberduck.FakesProvider
'@ModuleInitialize
Public Sub ModuleInitialize()
Set Assert = CreateObject("Rubberduck.AssertClass")
'Set Fakes = CreateObject("Rubberduck.FakesProvider")
End Sub
'@ModuleCleanup
Public Sub ModuleCleanup()
Set Assert = Nothing
'Set Fakes = Nothing
End Sub
'@TestMethod
Public Sub CanAddShipInsideGridBoundaries_ReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(1, 1)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
Assert.IsTrue sut.CanAddShip(position, Horizontal, Ship.MinimumSize)
End Sub
'@TestMethod
Public Sub CanAddShipAtPositionZeroZero_ReturnsFalse()
'i.e. PlayerGrid coordinates are 1-based
Dim position As GridCoord
Set position = GridCoord.Create(0, 0)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
Assert.IsFalse sut.CanAddShip(position, Horizontal, Ship.MinimumSize)
End Sub
'@TestMethod
Public Sub CanAddShipGivenInterectingShips_ReturnsFalse()
Dim ship1 As IShip
Set ship1 = Ship.Create("Ship1", 3, Horizontal, GridCoord.Create(1, 1))
Dim ship2 As IShip
Set ship2 = Ship.Create("Ship2", 3, Vertical, GridCoord.Create(2, 1))
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip ship1
Assert.IsFalse sut.CanAddShip(ship2.GridPosition, ship2.orientation, ship2.size)
End Sub
'@TestMethod
Public Sub AddingSameShipNameTwice_Throws()
Const ExpectedError As Long = 457 ' "This key is already associated with an element of this collection"
On Error GoTo TestFail
Const shipName As String = "TEST"
Dim ship1 As IShip
Set ship1 = Ship.Create(shipName, 2, Horizontal, GridCoord.Create(1, 1))
Dim ship2 As IShip
Set ship2 = Ship.Create(shipName, 3, Horizontal, GridCoord.Create(5, 5))
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip ship1
sut.AddShip ship2
Assert:
Assert.Fail "Expected error was not raised."
TestExit:
Exit Sub
TestFail:
If Err.Number = ExpectedError Then
Resume TestExit
Else
Resume Assert
End If
End Sub
'@TestMethod
Public Sub AddingShipOutsideGridBoundaries_Throws()
Const ExpectedError As Long = PlayerGridErrors.CannotAddShipAtPosition
On Error GoTo TestFail
Dim ship1 As IShip
Set ship1 = Ship.Create("TEST", 2, Horizontal, GridCoord.Create(0, 0))
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip ship1
Assert:
Assert.Fail "Expected error was not raised."
TestExit:
Exit Sub
TestFail:
If Err.Number = ExpectedError Then
Resume TestExit
Else
Resume Assert
End If
End Sub
'@TestMethod
Public Sub AddingMoreShipsThanGameAllows_Throws()
Const ExpectedError As Long = PlayerGridErrors.CannotAddMoreShips
Const MaxValue As Long = Globals.ShipsPerGrid
On Error GoTo TestFail
Dim sut As PlayerGrid
Set sut = New PlayerGrid
Dim i As Long
For i = 1 To Globals.ShipsPerGrid
sut.AddShip Ship.Create("TEST" & i, 2, Horizontal, GridCoord.Create(1, i))
Next
sut.AddShip Ship.Create("TEST" & MaxValue + i, 2, Horizontal, GridCoord.Create(1, MaxValue + 1))
Assert:
Assert.Fail "Expected error was not raised."
TestExit:
Exit Sub
TestFail:
If Err.Number = ExpectedError Then
Resume TestExit
Else
Resume Assert
End If
End Sub
'@TestMethod
Public Sub TryHitKnownState_Throws()
Const ExpectedError As Long = PlayerGridErrors.KnownGridStateError
On Error GoTo TestFail
Dim position As GridCoord
Set position = GridCoord.Create(1, 1)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
sut.TryHit position
sut.TryHit position
Assert:
Assert.Fail "Expected error was not raised."
TestExit:
Exit Sub
TestFail:
If Err.Number = ExpectedError Then
Resume TestExit
Else
Resume Assert
End If
End Sub
'@TestMethod
Public Sub TryHitMiss_SetsPreviousMissState()
Const expected = GridState.PreviousMiss
Dim position As GridCoord
Set position = GridCoord.Create(1, 1)
Dim badPosition As GridCoord
Set badPosition = position.Offset(5, 5)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
sut.TryHit badPosition
Dim actual As GridState
actual = sut.State(badPosition)
Assert.AreEqual expected, actual
End Sub
'@TestMethod
Public Sub TryHitSuccess_SetsPreviousHitState()
Const expected = GridState.PreviousHit
Dim position As GridCoord
Set position = GridCoord.Create(1, 1)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
sut.TryHit position
Dim actual As GridState
actual = sut.State(position)
Assert.AreEqual expected, actual
End Sub
'@TestMethod
Public Sub TryHitSuccess_ReturnsTrue()
Const expected = GridState.PreviousHit
Dim position As GridCoord
Set position = GridCoord.Create(1, 1)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
Assert.IsTrue sut.TryHit(position)
End Sub
'@TestMethod
Public Sub TryHitMisses_ReturnsFalse()
Const expected = GridState.PreviousMiss
Dim position As GridCoord
Set position = GridCoord.Create(1, 1)
Dim badPosition As GridCoord
Set badPosition = position.Offset(5, 5)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
Assert.IsFalse sut.TryHit(badPosition)
End Sub
'@TestMethod
Public Sub GridInitialState_UnknownState()
Const expected = GridState.Unknown
Dim sut As PlayerGrid
Set sut = New PlayerGrid
Dim actual As GridState
actual = sut.State(GridCoord.Create(1, 1))
Assert.AreEqual expected, actual
End Sub
'@TestMethod
Public Sub GivenAdjacentShip_HasRightAdjacentShipReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(2, 2)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
Assert.IsTrue sut.HasAdjacentShip(GridCoord.Create(1, 2), Vertical, 3)
End Sub
'@TestMethod
Public Sub GivenAdjacentShip_HasLeftAdjacentShipReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(2, 1)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
Assert.IsTrue sut.HasAdjacentShip(GridCoord.Create(1, 1), Vertical, 3)
End Sub
'@TestMethod
Public Sub GivenAdjacentShip_HasDownAdjacentShipReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(2, 2)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
Assert.IsTrue sut.HasAdjacentShip(GridCoord.Create(1, 3), Horizontal, 3)
End Sub
'@TestMethod
Public Sub GivenAdjacentShip_HasUpAdjacentShipReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(2, 2)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 2, Horizontal, position)
Assert.IsTrue sut.HasAdjacentShip(GridCoord.Create(1, 1), Horizontal, 3)
End Sub
'@TestMethod
Public Sub GivenAdjacentShipAtHorizontalTipEnd_ReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(10, 4)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 5, Vertical, position)
Assert.IsTrue sut.HasAdjacentShip(GridCoord.Create(6, 7), Horizontal, 4)
End Sub
'@TestMethod
Public Sub GivenAdjacentShipAtVerticalTipEnd_ReturnsTrue()
Dim position As GridCoord
Set position = GridCoord.Create(6, 7)
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 4, Horizontal, position)
Assert.IsTrue sut.HasAdjacentShip(GridCoord.Create(10, 4), Vertical, 5)
End Sub
'@TestMethod
Public Sub GivenTwoSideBySideHits_GetHitAreaReturnsTwoItems()
Const expected As Long = 2
Dim sut As PlayerGrid
Set sut = New PlayerGrid
sut.AddShip Ship.Create("TEST", 5, Horizontal, GridCoord.Create(1, 1))
sut.TryHit GridCoord.Create(1, 1)
Dim actual As Long
actual = sut.GetHitArea(GridCoord.Create(1, 1)).Count
Assert.AreEqual expected, actual
End Sub
</code></pre>
<hr>
<p>These two classes are the foundation of the game (I'll upload the whole thing to GitHub once I have everything ready - <a href="https://www.dropbox.com/s/cv4yquqzi7ue93y/Battleship-Play.mp4?dl=0" rel="noreferrer">here's a teaser video</a>), and since I'm planning to make this project a model of a VBA project to demonstrate Rubberduck's features and debunk any "VBA can't do real OOP" once and for all, I want this to be as good as it gets.</p>
<p>Does <em>anything</em> stick out? <em>Please be picky</em>!</p>
<hr>
<p>The <strong>Globals</strong> module is just a standard procedural module that exposes, well, the game's globals:</p>
<pre><code>'@Folder("Battleship")
Option Explicit
Public Const GridSize As Byte = 10
Public Const ShipsPerGrid As Byte = 5
Public Const Delay As Long = 1200
Public Const ShipNameCarrier As String = "Aircraft Carrier"
Public Const ShipNameBattleship As String = "Battleship"
Public Const ShipNameSubmarine As String = "Submarine"
Public Const ShipNameCruiser As String = "Cruiser"
Public Const ShipNameDestroyer As String = "Destroyer"
Public Function GetDefaultShips() As Variant
GetDefaultShips = Array( _
GetDefaultCarrier, _
GetDefaultBattleship, _
GetDefaultSubmarine, _
GetDefaultCruiser, _
GetDefaultDestroyer)
End Function
Private Function GetDefaultCarrier() As IShip
Set GetDefaultCarrier = Ship.Create(ShipNameCarrier, 5, Horizontal, GridCoord.Create(1, 1))
End Function
Private Function GetDefaultBattleship() As IShip
Set GetDefaultBattleship = Ship.Create(ShipNameBattleship, 4, Horizontal, GridCoord.Create(1, 1))
End Function
Private Function GetDefaultSubmarine() As IShip
Set GetDefaultSubmarine = Ship.Create(ShipNameSubmarine, 3, Horizontal, GridCoord.Create(1, 1))
End Function
Private Function GetDefaultCruiser() As IShip
Set GetDefaultCruiser = Ship.Create(ShipNameCruiser, 3, Horizontal, GridCoord.Create(1, 1))
End Function
Private Function GetDefaultDestroyer() As IShip
Set GetDefaultDestroyer = Ship.Create(ShipNameDestroyer, 2, Horizontal, GridCoord.Create(1, 1))
End Function
</code></pre>
<p>I'm not 100% convinced this is the best place to put the ship names and default ships.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T04:47:12.937",
"Id": "389291",
"Score": "2",
"body": "PlayerGrid also refers to the `IShip` interface"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T05:32:50.977",
"Id": "389293",
"Score": "2... | [
{
"body": "<p>Based on my first not too thorough read, this looks rather nice. I currently only have two points of critique.</p>\n\n<p>The first point is the lack of explicit interfaces. I think both the <code>PlayerGrid</code> and the <code>Grid Coordinates</code>could use an explicit interface, <code>IGrid</c... | {
"AcceptedAnswerId": "202109",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T03:57:05.063",
"Id": "202101",
"Score": "12",
"Tags": [
"object-oriented",
"vba",
"unit-testing",
"rubberduck",
"battleship"
],
"Title": "BattleShip Grid: Classes and Tests"
} | 202101 |
<p>I am working on a photo editor, which displays a preview to the user on a canvas. At various points in the app, the user may use sliders to adjust properties of the photo, such as scaling, rotation, etc. The preview needs to be updated in real time, as the user drags the slider.</p>
<p>As I understand, pointer events are fired much more rapidly than the browser window is repainted. Because of this, it would be wasteful to update the preview directly from the pointer event handlers, since most of those updates would have no visible effect. Instead, I wanted to separate the actions of updating the preview state based on the most recent pointer event, and redrawing the preview based on the latest update since the last redraw.</p>
<p>To this end, I wrote a small helper function called <code>throttleRedraw()</code>, which I'd appreciate if you could review. Is it properly optimized? Is it even necessary? There's probably a library for it, but I wanted to make sure I understand the principle at the core.</p>
<p>Here's a snippet containing the function itself, and a simple example that draws a rectangle on a canvas when you click and drag with the pointer:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function throttleRedraw(target, props) {
const {
onstart,
onmove,
onend,
ondraw,
absolute,
} = props;
let frameReq = 0;
let lastX = 0;
let lastY = 0;
let isTouch = false;
let enabled = true;
// This is the callback we will be passing to requestAnimationFrame().
// It's just a proxy for the ondraw() function passed in the props object.
const frameHandler = (now) => {
if (ondraw) ondraw(now);
frameReq = 0;
};
// The callback for the mousemove/touchmove events,
// which in turn calls props.onmove() if it was specified.
// If props.absolute is true, props.onmove() receives the x and y coordinates of the pointer;
// otherwise, it receives the delta since the last update.
const moveHandler = (event) => {
if (onmove) {
const newX = isTouch ? event.touches[0].clientX : event.clientX;
const newY = isTouch ? event.touches[0].clientY : event.clientY;
onmove(
absolute ? newX : newX - lastX,
absolute ? newY : newY - lastY,
event
);
lastX = newX;
lastY = newY;
}
// If we have not yet requested an animation frame since the last, do it now.
if (!frameReq) {
frameReq = window.requestAnimationFrame(frameHandler);
}
};
// The callback for the mouseup/touchend events,
// which in turn calls props.onend() if it was specified.
const upHandler = (event) => {
if (onend) onend(event);
// Remove the event handlers we set at the start.
if (!isTouch) {
window.removeEventListener('mousemove', moveHandler);
window.removeEventListener('mouseup', upHandler);
}
else {
window.removeEventListener('touchmove', moveHandler);
window.removeEventListener('touchend', upHandler);
window.removeEventListener('touchcancel', upHandler);
}
};
// Set the mousedown/touchstart event listeners on the target.
// They're mostly the same, except for how the coordinates are obtained
// from the event, and what additional event handlers need to be set.
target.addEventListener('mousedown', (event) => {
if (!enabled) return true;
isTouch = false;
event.preventDefault();
lastX = event.clientX;
lastY = event.clientY;
if (onstart) onstart(lastX, lastY, event);
window.addEventListener('mousemove', moveHandler);
window.addEventListener('mouseup', upHandler);
});
target.addEventListener('touchstart', (event) => {
if (!enabled) return true;
isTouch = true;
event.preventDefault();
lastX = event.touches[0].clientX;
lastY = event.touches[0].clientY;
if (onstart) onstart(lastX, lastY, event);
window.addEventListener('touchmove', moveHandler);
window.addEventListener('touchend', upHandler);
window.addEventListener('touchcancel', upHandler);
});
// Return an object that allows us to enable or disable listening for events,
// and query the current enabled state.
return {
isEnabled: () => enabled,
enable: (value) => { enabled = value; },
};
}
const canvas = document.querySelector('canvas');
const rect = canvas.getBoundingClientRect();
const ctx = canvas.getContext('2d');
let x0, y0, x1, y1;
throttleRedraw(canvas, {
absolute: true,
onstart: (x, y) => {
x0 = x - rect.left;
y0 = y - rect.top;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
},
onmove: (x, y) => {
x1 = x - rect.left;
y1 = y - rect.top;
},
ondraw: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(
Math.min(x0, x1),
Math.min(y0, y1),
Math.abs(x1 - x0),
Math.abs(y1 - y0)
);
},
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas width="400" height="400" style="border: 2px solid #888"></canvas></code></pre>
</div>
</div>
</p>
<p>Thanks in advance.</p>
| [] | [
{
"body": "<h1>Limiting updates</h1>\n<p>You are correct about mouse event rates, I have seen mouse event 2ms apart. However touch events seem to be in sync with the display 60FPS, I have never seen a touch event fire at rates higher than this (but that is a hardware attribute as far as I know).</p>\n<p>But tha... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T09:04:49.567",
"Id": "202110",
"Score": "2",
"Tags": [
"javascript",
"reinventing-the-wheel",
"event-handling"
],
"Title": "Throttle redraw requests fired from pointer events"
} | 202110 |
<p>I want to determine a path (x and y coordinates) by using curvature data (radius, with constant distance (<code>length_of_arc</code>) travelled between data points. I want to repeat this calculation every 0.010 seconds and visualize the points in pyhon kivy (at the moment a raw calculation takes 0.006 - 0.014 seconds). </p>
<p>Assume sample data </p>
<pre><code>radius = [68.96551724, 69.73500697, 71.78750897, 75.98784195, 81.96721311, 90.74410163, 102.6694045, 120.0480192,
146.1988304, 187.9699248, 265.9574468, 458.7155963, 1694.915254, -1020.408163, -393.7007874, -244.4987775]
</code></pre>
<p>This is the code (inside a class) that I use to calculate the coordinates. Is there a way to increase performance / readability of the code. It is important to note that performance has higher priority.</p>
<p><strong>EDIT:</strong> I already tried small angle approximation (sin x \approx x, cos x \approx 1 - 0.5 x^2) but that did only lead to insignificant changes.</p>
<pre><code># positive curvature is a right bend, negative curvature is a left bend
# scale_factor: used to scale the values for plotting them
# initial_displacement_x and initial_displacement_y: values are displaced such that the plot is in the Center of the screen.
@staticmethod
def calculate_coordinates_from_length_of_arc_and_radius(_radius, length_of_arc, scale_factor,
initial_displacement_x, initial_displacement_y):
phi = 0 # accumulation of angle
number_of_data_points = len(_radius)
x_accumulated = number_of_data_points * [0]
y_accumulated = number_of_data_points * [0]
track_coordinates = 2 * number_of_data_points * [0] # x,y alternating needed for ploting values as line in python kivy
for data_point in range(number_of_data_points - 1):
delta_phi = - length_of_arc / _radius[data_point]
phi = phi + delta_phi
dx = - _radius[data_point] * (cos(delta_phi) - 1)
dy = - _radius[data_point] * sin(delta_phi)
if data_point != 0:
dx_rotated = cos(phi) * dx - sin(phi) * dy # apply rotation matrix
dy_rotated = sin(phi) * dx + cos(phi) * dy # apply rotation matrix
else:
dx_rotated = dx # the displacements are not rotated
dy_rotated = dy # for the first data point
x_accumulated[data_point + 1] = x_accumulated[data_point] + dx_rotated
y_accumulated[data_point + 1] = y_accumulated[data_point] + dy_rotated
track_coordinates[2 * data_point + 2] = scale_factor * (x_accumulated[data_point] + dx_rotated)
track_coordinates[2 * data_point + 3] = scale_factor * (y_accumulated[data_point] + dy_rotated)
for data_point in range(len(track_coordinates)):
if data_point % 2:
track_coordinates[data_point] = track_coordinates[data_point] + initial_displacement_x
elif not data_point % 2:
track_coordinates[data_point] = track_coordinates[data_point] + initial_displacement_y
return track_coordinates
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T09:18:40.217",
"Id": "389328",
"Score": "1",
"body": "Which version of Python are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T09:26:09.263",
"Id": "389330",
"Score": "1",
"b... | [
{
"body": "<p>If you are doing a lot of numerical calculations in Python and want them to be fast, you should use <code>numpy</code>, a package specifically for this purpose.</p>\n\n<p>It allows you to write your code in a vectorized way, making it easer to understand at the same time:</p>\n\n<pre><code>import ... | {
"AcceptedAnswerId": "202118",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T09:06:07.350",
"Id": "202111",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"computational-geometry"
],
"Title": "Curvature data to coordinates"
} | 202111 |
<p>A BASH script that ask users simple questions and greps the syslog archive files (plain-text and gzipped).</p>
<p>The script is fully working; I am looking for advices on:</p>
<ul>
<li>Coding style</li>
<li>Possible optimisations</li>
<li>Any potential pitfalls / hidden bugs</li>
<li>User interaction</li>
<li>Best practices and idiomatic ways to do things in BASH</li>
</ul>
<hr>
<pre><code>#!/bin/bash
#
# Syslog archive search script
# Alexander Ivashkin, August 2018
#
ScriptVersion='v. 1.8.1'
# Those constants are called "sensitive_" because they could contain sensitive data that should be removed by the anonymisation process.
#
# After anonymisation only this section would remain...
sensitive_Author="Alexander Ivashkin"
sensitive_DirectoryWithLogs="/var/data/syslog/"
sensitive_HostnamesExamples='
router1
NYC-switch.*4507
London-WAN
Texas.*ATM'
sensitive_PatternExamples='
LINEPROTO-5-UPDOWN
lineproto-5-updown
%BGP
bgp.*neighbor.*down
Tunnel69
OSPF.*10.10.10.10
DAI-4-(?!DHCP) - for PCRE engine'
# There should be a sensitive section below this line... but you probably won't see it!
#
cat<<EOF
======================================================================
Welcome to the syslog search script $ScriptVersion
$sensitive_Author, August 2018
----------------------------------------------------------------------
EOF
# FUNCTIONS
#
# Make output more grammatical.
# Usage: choose_singular_or_plural NUMBER WORD_SINGULAR WORD_PLURAL
# Example: choose_singular_or_plural 99 balloon balloons
# outputs: 99 balloons
choose_singular_or_plural()
{
echo -n "$1 "
[ ${1: -1} = "1" ] && echo $2 || echo $3
}
# Clean-up function to be used in the end and when catching SIGINT/SIGTERM
summarize_and_cleanup()
{
if [ "$2" = "summarize" ]; then
time_ElapsedSeconds=$(($(date +%s)-$time_Start))
time_ElapsedHumanFriendly="$((time_ElapsedSeconds/60)) min $((time_ElapsedSeconds%60)) sec"
totalLinesFound=$(($(cat $file_output | wc -l)-$file_outputHeaderSize))
time_PerFile=$((time_ElapsedSeconds/$count_filesProcessed))
cat<<EOF
$1
Processed $( choose_singular_or_plural $count_filesProcessed file files ).
Script has helped you to find $( choose_singular_or_plural $totalLinesFound line lines ) of logs!
Time elapsed: $time_ElapsedHumanFriendly (ca. $time_PerFile seconds per file)
Exported output to $file_output.
Log file: $file_log
------------------------------
EOF
cat<<EOF>>$file_log
$1
Processed $( choose_singular_or_plural $count_filesProcessed file files ).
Found $( choose_singular_or_plural $totalLinesFound line lines ) of logs.
Time elapsed: $time_ElapsedHumanFriendly (ca. $time_PerFile seconds per file)
Exported output to $file_output.
EOF
# No summary required (early abort)
else
echo $1 | tee -a $file_log
fi
[ -n "$old_IFS" ] && IFS=${old_IFS} || IFS=" "
exec 2>&1
exit
}
trap "summarize_and_cleanup 'Aborted by SIGINT.'" SIGINT
trap "summarize_and_cleanup 'Aborted by SIGTERM.'" SIGTERM
file_log="$(cd $(dirname $0) > /dev/null && pwd)/syslog_search.log"
exec 2>>$file_log
file_output="$(cd $(dirname $0) > /dev/null && pwd)/syslog_search.out"
cat<<EOF>>$file_log
======================================================================
Script started at $(date -u)
User: $(whoami)
System: $(uname -a)
BASH: $(bash --version | head -n 1)
EOF
cat<<EOF>$file_output
======================================================================
Script started at $(date -u)
EOF
# Checking for grep version.
# Order of preference: ext. grep -> basic grep -> PCRE
out_pcregrep=$(echo 696969 | pcregrep "\d{6}" 2>/dev/null)
out_egrep=$(echo 696969 | grep -E "[0-9]{6}" 2>/dev/null)
out_grep=$(echo 696969 | grep "[0-9]\{6\}" 2>/dev/null)
if [ "$out_egrep" = "696969" ]; then
# We use newline instead of space due to different IFS in the end (to allow for spaces in filenames)
cmd_grep=$'grep\n-Ei'
echo 'Regular expressions flavour: extended grep (see https://www.unix.com/man-page/linux/1/grep/ for reference)'
echo "Regexps: egrep" >> $file_log
elif [ "$out_grep" = "696969" ]; then
cmd_grep=$'grep\n-i'
echo 'Regular expressions flavour: grep (see https://www.unix.com/man-page/linux/1/grep/ for reference)'
echo "Regexps: grep" >> $file_log
elif [ "$out_pcregrep" = "696969" ]; then
cmd_grep=$'pcregrep\n-i'
echo 'Regular expressions flavour: PCRE (see https://www.unix.com/man-page/Linux/3/pcresyntax/ for reference)'
echo "Regexps: PCRE" >> $file_log
else
summarize_and_cleanup 'FATAL ERROR. No grep found. ABORTING.'
fi
[ "$out_egrep" = "696969" ] && regexp_engines="egrep"; grep -V | head -n 1 >&2
if [ "$out_grep" = "696969" ]; then
if [ -n "$regexp_engines" ]; then
regexp_engines="$regexp_engines grep"
else
regexp_engines="grep"
grep -V | head -n 1 >&2
fi
fi
if [ "$out_pcregrep" = "696969" ]; then pcregrep -V | head -n 1 >&2; [ -n "$regexp_engines" ] && regexp_engines="$regexp_engines pcregrep" || regexp_engines="pcregrep"; fi
echo "Available regexps engines: $regexp_engines" | tee -a $file_log
echo ======================================================================
cd $sensitive_DirectoryWithLogs 2>/dev/null || summarize_and_cleanup 'FATAL ERROR: could not cd to $sensitive_DirectoryWithLogs. ABORTING.'
set -o pipefail
oldest_CiscoInfo=$(ls -tg --time-style=long-iso cisco_info* | tail -1 | sed -E 's/^.* [0-9]+ (2[0-9]{3}-[0-9]{2}-[0-9]{2}) .*$/\1/g' || echo NO LOGS)
oldest_CiscoCrit=$(ls -tg --time-style=long-iso cisco_crit* | tail -1 | sed -E 's/^.* [0-9]+ (2[0-9]{3}-[0-9]{2}-[0-9]{2}) .*$/\1/g' || echo NO LOGS)
oldest_Rmessages=$(ls -tg --time-style=long-iso rmessages* | tail -1 | sed -E 's/^.* [0-9]+ (2[0-9]{3}-[0-9]{2}-[0-9]{2}) .*$/\1/g' || echo NO LOGS)
oldest_Netscaler=$(ls -tg --time-style=long-iso netscaler* | tail -1 | sed -E 's/^.* [0-9]+ (2[0-9]{3}-[0-9]{2}-[0-9]{2}) .*$/\1/g' || echo NO LOGS)
set +o pipefail
count_CiscoInfo=$(ls cisco_info* | wc -l || echo 0)
count_CiscoCrit=$(ls cisco_crit* | wc -l || echo 0)
count_Rmessages=$(ls rmessages* | wc -l || echo 0)
count_NetScaler=$(ls netscaler* | wc -l || echo 0)
cat<<EOF>>$file_log
----------------------------------------------------------------------
OLDEST AVAILABLE LOGS
$(printf "%-16s %s\n" "Cisco info: " "$oldest_CiscoInfo ($count_CiscoInfo days ago)")
$(printf "%-16s %s\n" "Cisco critical: " "$oldest_CiscoCrit ($count_CiscoCrit days ago)")
$(printf "%-16s %s\n" "Rmessages: " "$oldest_Rmessages ($count_Rmessages days ago)")
$(printf "%-16s %s\n" "NetScaler: " "$oldest_Netscaler ($count_NetScaler days ago)")
----------------------------------------------------------------------
EOF
cat<<EOF
Note that this script can produce enormous amount of output. Use filtering carefully.
Moreover, it can take quite some time due to sheer amount of syslog data (especially with the NetScaler logs).
Caveat emptor.
Be patient. You can always interrupt execution with a SIGINT (by pressing Ctrl-C) and the script would handle this correctly.
----------------------------------------------------------------------
OLDEST AVAILABLE LOGS
$(printf "%-45s %s\n" "Cisco info (severity 3-7): " "$oldest_CiscoInfo ($count_CiscoInfo days ago)")
$(printf "%-45s %s\n" "Cisco critical (severity 1-2): " "$oldest_CiscoCrit ($count_CiscoCrit days ago)")
$(printf "%-45s %s\n" "Rmessages (Arista and other weird devices): " "$oldest_Rmessages ($count_Rmessages days ago)")
$(printf "%-45s %s\n" "NetScaler (load balancers): " "$oldest_Netscaler ($count_NetScaler days ago)")
----------------------------------------------------------------------
EOF
[ "$count_CiscoInfo" -gt "0" -o "$count_CiscoCrit" -gt "0" ] && log_types="Cisco"
if [ "$count_Rmessages" -gt "0" ]; then [ -n "$log_types" ] && log_types="$log_types#rmessages" || log_types="rmessages"; fi
if [ "$count_NetScaler" -gt "0" ]; then [ -n "$log_types" ] && log_types="$log_types#NetScaler" || log_types="NetScaler"; fi
[ -z "$log_types" ] && summarize_and_cleanup "NO LOGFILES FOUND! ABORTING."
cat<<EOF
Please select the kind of logs you are interested in:
EOF
old_IFS=${IFS}
IFS="#"
exec 2>&1
log_types="$log_types#Change regexp engine (if you know what you are doing!)"
selection_done=0
while (( !selection_done )); do
PS3="Select logs:"
select log_type in $log_types;
do
case $log_type in
"Cisco")
log_fileNamePattern='cisco*'
echo "Searching in Cisco logs" | tee -a $file_log >> $file_output
selection_done=1
break
;;
"rmessages")
log_fileNamePattern='rmessages*'
echo "Searching in rmessages logs" | tee -a $file_log >> $file_output
selection_done=1
break
;;
"NetScaler")
log_fileNamePattern='netscaler*'
echo "Searching in NetScaler logs" | tee -a $file_log >> $file_output
selection_done=1
break
;;
"Change regexp engine (if you know what you are doing!)")
# $regexp_engines are also being printed as is, so we use space instead of hash
IFS=" "
PS3="Choose regexp engine:"
select regexp_engine in $regexp_engines
do
case $regexp_engine in
"egrep")
cmd_grep=$'grep\n-Ei'
echo $'\nRegular expressions flavour: extended grep (see https://www.unix.com/man-page/linux/1/grep/ for reference)\n'
echo "Regexps changed by user to: $regexp_engine" >> $file_log
break
;;
"grep")
cmd_grep=$'grep\n-i'
echo $'\nRegular expressions flavour: grep (see https://www.unix.com/man-page/linux/1/grep/ for reference)\n'
echo "Regexps changed by user to: $regexp_engine" >> $file_log
break
;;
"pcregrep")
cmd_grep=$'pcregrep\n-i'
echo $'\nRegular expressions flavour: PCRE (see https://www.unix.com/man-page/Linux/3/pcresyntax/ for reference)\n'
echo "Regexps changed by user to: $regexp_engine" >> $file_log
break
;;
esac
done
PS3="Select logs:"
IFS="#"
break
esac
done
done
cat<<EOF
Please select the range of logs:
EOF
PS3="Select log range:"
IFS="#"
log_ranges="Today#Last week#Last month#Hit me with your laser beams! (all of them)"
select log_range in $log_ranges;
do
case $log_range in
"Today")
log_rangeDays=-1440
break
;;
"Last week")
log_rangeDays=-11520
break
;;
"Last month")
log_rangeDays=-46080
break
;;
"Hit me with your laser beams! (all of them)")
log_rangeDays=0
break
;;
esac
done
cat<<EOF
Please input device hostname to search logs for.
Can be full, partial or with regexps.
Note: the hostname is case-insensitive
Examples:
$sensitive_HostnamesExamples
EOF
read -p 'Hostname: ' -r -e log_hostname
cat<<EOF
Please input search pattern. Again, it can be partial or with regexps.
Note: the pattern is case-insensitive
Examples:
$sensitive_PatternExamples
EOF
read -p 'Search pattern: ' -r -e log_pattern
echo "Hostname: $log_hostname" | tee -a $file_log >> $file_output
echo "Pattern: $log_pattern" | tee -a $file_log >> $file_output
echo "Log range: $(($log_rangeDays/-60/24)) days" | tee -a $file_log >> $file_output
exec 2>>$file_log
file_outputHeaderSize=$(cat $file_output | wc -l)
time_Start=$(date +%s)
trap "summarize_and_cleanup 'Aborted by SIGINT.' summarize" SIGINT
trap "summarize_and_cleanup 'Aborted by SIGTERM.' summarize" SIGTERM
# To catch spaces in filenames...
IFS="
"
if [ "$log_rangeDays" = "0" ]; then
log_AllFiles=$( ls -t $log_fileNamePattern )
else
log_AllFiles=$( find -daystart -mmin $log_rangeDays -name "$log_fileNamePattern" -print0 | xargs -0 ls -t )
fi
count_filesProcessed=0
for log_file in $log_AllFiles; do
cat<<EOF
------------------------------
SEARCHING IN $log_file
------------------------------
EOF
(gunzip -c $log_file 2>/dev/null || cat $log_file) | $cmd_grep "$log_hostname.*$log_pattern" | tee -a $file_output
count_filesProcessed=$(($count_filesProcessed+1))
done
summarize_and_cleanup "DONE." summarize
</code></pre>
| [] | [
{
"body": "<p>If you don't have <code>shellcheck</code>, install and use it (or submit your code to the <a href=\"https://shellcheck.net\" rel=\"nofollow noreferrer\">online version</a>). Here's what it says about this script:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>202114.sh:48:7: note: Dou... | {
"AcceptedAnswerId": "202121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T09:44:53.867",
"Id": "202114",
"Score": "2",
"Tags": [
"bash",
"shell",
"user-interface"
],
"Title": "User-friendly script for searching through log files"
} | 202114 |
<p>I am new at programming and I'm really confused about how should I do this, because at first I thought I should ask user which path to export. However I have been told that I should check if it exists the directory and if doesn't I should create it. How can I even create a directory path or ask user if it can be created? Sorry if my question is too odd but I'm very confused about this, I was convinced that simply asking was enough to export data. </p>
<pre><code>static void exportData(string[,] matrix)
{
var dir = "";
do
{
Console.Clear();
Console.Write("Insert path to export txt: ");
dir = Console.ReadLine();
} while (String.IsNullOrEmpty(dir));
var path = Path.Combine(dir, "export.txt");
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1) - 1; j++)
{
{
sw.Write($"\t{matrix[i, j]}\t");
}
}
Console.WriteLine("\n");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T11:16:12.983",
"Id": "389353",
"Score": "5",
"body": "This application seems to be very simple. Could you post all of its code? You should also explain what the format of the text file is and what is the purpose of it."
},
{
... | [
{
"body": "<p>As I correctly understood, you want to export matrix in text file.\nIf its true, your code contains some mistakes:</p>\n\n<pre><code>for (int j = 0; j < matrix.GetLength(1) - 1; j++)\n</code></pre>\n\n<p>should be without decreasing length by 1 and <code>Console.WriteLine(\"\\n\");</code>\nshou... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T11:01:18.617",
"Id": "202119",
"Score": "2",
"Tags": [
"c#",
"beginner",
"console",
"file-system"
],
"Title": "Export data from matrix to txt file"
} | 202119 |
<p>I have server side log files written to various directories throughout the course of a week. I have the need to optionally compress, and archive these files to AWS.</p>
<p>The script I have come up with takes a config file defining the include glob to look for matches, and offers optional removal of the source files once the process has completed.</p>
<pre><code>python aws_bkup.py path/to/config.cfg
</code></pre>
<p>A sample config file can be found in the project directory: <a href="https://github.com/twanas/aws-bkup" rel="nofollow noreferrer">https://github.com/twanas/aws-bkup</a></p>
<p>I would be most appreciative of feedback on the code style and areas it can be improved.</p>
<pre><code>from __future__ import print_function
import re
import errno
import os
from glob import glob
from os.path import join, basename, splitext
from os import environ, remove
from shutil import copy, rmtree
from uuid import uuid4
import gzip
from configparser import ConfigParser
from datetime import date, timedelta
import subprocess
def gz(src, dest):
""" Compresses a file to *.gz
Parameters
----------
src: filepath of file to be compressesd
dest: destination filepath
"""
filename = splitext(basename(src))[0]
destpath = join(dest, '{}.gz'.format(filename))
blocksize = 1 << 16 #64kB
with open(src) as f_in:
f_out = gzip.open(destpath, 'wb')
while True:
block = f_in.read(blocksize)
if block == '':
break
f_out.write(block)
f_out.close()
def aws_sync(src, dest):
""" Synchronise a local directory to aws
Parameters
----------
src: local path
dest: aws bucket
"""
cmd = 'aws s3 sync {} {}'.format(src, dest)
push = subprocess.call(cmd, shell=True)
def today():
""" Returns a string format of today's date """
return date.today().strftime('%Y%m%d')
def fwe():
""" Returns a string format of the next friday's date """
d = date.today()
while d.weekday() != 4:
d += timedelta(1)
return d
def regex_match(string, pattern):
""" Returns if there is a match between parameter and regex pattern """
pattern = re.compile(pattern)
return pattern.match(string)
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def aws_bkup(section, include, exclude, s3root, categorize_weekly=True, compress=True, remove_source=True):
""" Transfers a backup of any local files matching the user's criteria to AWS.
Parameters
----------
include: regex pattern to use for the file inclusion(s)
exclude: regex pattern to use for the file exclusion(s)
s3root: AWS root in which to send the backup
categorize_weekly: switch between daily and weekly folder groupings
compress: switch to compress outbound files to AWS
"""
folder = '{}'.format(fwe() if categorize_weekly else today())
tmp_root = join('/tmp', str(uuid4()))
tmp_dir = join(tmp_root, folder)
mkdir_p(tmp_dir)
for file in glob(include):
if regex_match(file, exclude):
continue
print('Processing: {}'.format(file))
if compress:
gz(file, tmp_dir)
else:
copy(file, tmp_dir)
if remove_source:
remove(file)
aws_dest = join(s3root, section)
print('Syncronizing {} to s3'.format(tmp_dir))
aws_sync(tmp_root, aws_dest)
if os.path.exists(tmp_root):
rmtree(tmp_root)
print('Done')
if __name__ == "__main__":
import sys
args = sys.argv
if len(args) < 2:
print("Usage: python -m aws-bkup /path/to/config.cfg")
sys.exit()
config = ConfigParser()
config.read(args[1])
environ['AWS_ACCESS_KEY_ID'] = config.get('aws', 'access_id')
environ['AWS_SECRET_ACCESS_KEY'] = config.get('aws', 'secret_key')
environ['AWS_DEFAULT_REGION'] = config.get('aws', 'region')
for section in config.sections():
if section != 'aws':
print('Starting {}'.format(section))
aws_bkup(
section,
config.get(section, 'include'),
config.get(section, 'exclude'),
config.get('aws', 's3root'),
config.getboolean(section, 'categorize_weekly'),
config.getboolean(section, 'compress'),
config.getboolean(section, 'remove_source')
)
</code></pre>
| [] | [
{
"body": "<p>After a quick read-through, I’ve spotted two items:</p>\n\n<hr>\n\n<h2><code>with</code> not used for <code>f_out</code></h2>\n\n<p>The code:</p>\n\n<pre><code>with open(src) as f_in:\n f_out = gzip.open(destpath, 'wb')\n #...\n f_out.close()\n</code></pre>\n\n<p>should be replaced with:<... | {
"AcceptedAnswerId": "202128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T11:07:59.753",
"Id": "202120",
"Score": "4",
"Tags": [
"python",
"file-system",
"logging",
"amazon-web-services"
],
"Title": "Simple server log backup script utilising AWS"
} | 202120 |
<p>Let us assume that we need to develop an application which can select best 11 players to score maximum points. The application will select the best players after completion of a match. The rules are mentioned below. </p>
<p>a. Each cricket team will have 5 players (2 batsmen, 2 bowlers and 1 wicket keeper) only. (For two teams total 10 players)</p>
<p>b. 1 Run means 1 point. 1 wicket means 50 points. Wicketkeepers points will be depend on bowlers. If two bowlers score 100 total points then the points of wicketkeeper will be 50. (50%).</p>
<p>c. One batsman can score in between 0 to 100 and one bowler can take maximum 3 wickets.</p>
<p>d. All out is not necessary. Bowlers cannot score runs.</p>
<p>e. Points of captain of the fantasy team will be double. That means 1 run = 2 points and 1 wicket = 100 points. The application will automatically select the captain.</p>
<p>f. One fantasy cricket team can have only one captain. </p>
<p>g. One can select maximum three players from a team.</p>
<p>h. Fantasy team can score maximum 200 runs and can take maximum 4 wickets. </p>
<ol>
<li><p>First create two link lists of two cricket teams (Say team A and team B). Total 5 nodes. The structure of the list is as mentioned below. Put the runs scored by the batsman and wicket taken by the bowler in data field. The points of wicket keepers will be counted automatically as mentioned earlier.</p>
<blockquote>
<p>Batsman(1) Batsman(2) Wicketkeeper Bowler(1) Bowler(2) </p>
</blockquote></li>
<li><p>Create a new linklist from above two lists. The data field will represent the team name from where the player belongs. This list will select the best possible 5 players to get the maximum points. </p></li>
<li>Display the fantasy points earn by your selected team. </li>
<li><p>Select the highest run scoring batsman (Select the team) and maximum wicket taking player (Select the team). Select the best valuable wicketkeeper (Select the team). These players may not be present in the selected fantasy cricket team. </p>
<p>Test Cases:
Input: Enter runs score by team ‘A’ batsmen followed by
team ‘B’: 29, 81, 79, 35 Enter
wicket taken by team ‘A’ bowlers followed by
team ‘B’: 1, 3, 2, 2<br>
Output:<br>
Question 1: Display the two link lists.<br>
Question 2: A->B->B->A->A (Result: 81+79+100+150+50) (Captain is a bowler from team A)<br>
Question 3: Points: 81+79+100+300+50=610<br>
Question 4: Highest run scoring batsman is from team A.
Highest wicket taking bowler is from team A.
Valuable wicketkeeper is from team B. </p></li>
</ol>
<p>My solution for this is following</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
/*Structure representing nodes of linked list forming the team. */
struct Node
{
float run;
struct Node *next;
};
/*Function to create a node of a linked list*/
void create_node(int x,struct Node **temp)
{
struct Node *r, *z;
z = *temp;
if(z == NULL)
{
r =(struct Node*)malloc(sizeof(struct Node));
r->run = x;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else
{
r->run = x;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
/*Function to display the linked lists*/
void show(struct Node *node)
{
while(node->next != NULL)
{
printf("%f , ", node->run);
node = node->next;
}
}
void main()
{
struct Node *team1 = NULL , *team2 = NULL , *fteam = NULL ;
float run1,run2,bow1,bow2,wc1 ;
printf("Enter the runs and wickets taken by Team-1: \n ");
printf("Enter the run scored by 1st player of Team-1:");
scanf("%f" , &run1);
printf("Enter the run scored by 2nd player of Team-1:");
scanf("%f" , &run2);
printf("Enter the wickets taken by 1st bowler player of Team-1:");
scanf("%f" , &bow1);
printf("Enter the wickets taken by 2nd bowler player of Team-1:");
scanf("%f" , &bow2);
wc1 = ((bow1 + bow2)*50)*0.5 ;
create_node(run1, &team1);
create_node(run2, &team1);
create_node(wc1, &team1);
create_node(bow1, &team1);
create_node(bow2, &team1);
printf("DISPLAY TEAM-1 :");
show(team1);
float run21,run22,bow21,bow22,wc2 ;
printf("\nEnter the runs and wickets taken by Team-2: \n ");
printf("Enter the run scored by 1st player of Team-2:");
scanf("%f" , &run21);
printf("Enter the run scored by 2nd player of Team-2:");
scanf("%f" , &run22);
printf("Enter the wickets taken by 1st bowler player of Team-2:");
scanf("%f" , &bow21);
printf("Enter the wickets taken by 2nd bowler player of Team-2:");
scanf("%f" , &bow22);
wc2 = ((bow21 + bow22)*50)*0.5 ;
create_node(run21, &team2);
create_node(run22, &team2);
create_node(wc2, &team2);
create_node(bow21, &team2);
create_node(bow22, &team2);
printf("\nDISPLAY TEAM-2");
show(team2);
float run[4];
run[0] = run1;
run[1] = run2;
run[2] = run21;
run[3] = run22;
float bow[4];
bow[0] = bow1;
bow[1] = bow2;
bow[2] = bow21;
bow[3] = bow22;
int trun[4];
int tbow[4];
int a,b;
/*Sorting the run array in descending order*/
for (int i = 0; i < 4; ++i)
{
for (int j = i + 1; j <4;++j)
{
if (run[i] < run[j])
{a = run[i];
run[i] = run[j];
run[j] = a;
}
}
}
/*Checking which Batsman is from which team*/
if(run[0]==run1 || run[0]==run2)
{trun[0]=1;}
else
{trun[0]=2;}
if(run[1]==run1 || run[1]==run2)
{trun[1]=1;}
else
{trun[1]=2;}
if(run[2]==run1 || run[2]==run2)
{trun[2]=1;}
else
{trun[2]=2;}
if(run[3]==run1 || run[3]==run2)
{trun[3]=1;}
else
{trun[3]=2;}
/*Sorting the bow array in descending order*/
for (int i = 0; i < 4; ++i)
{
for (int j = i + 1; j < 4;++j)
{
if (bow[i] < bow[j])
{b = bow[i];
bow[i] = bow[j];
bow[j] = b;
}
}
}
/*Checking which Bowler is from which team*/
if(bow[0]==bow1 || bow[0]==bow2)
{tbow[0]=1;}
else
{tbow[0]=2;}
if(bow[1]==bow1 || bow[1]==bow2)
{tbow[1]=1;}
else
{tbow[1]=2;}
if(bow[2]==bow1 || bow[2]==bow2)
{tbow[2]=1;}
else
{tbow[2]=2;}
if(bow[3]==bow1 || run[3]==bow2)
{tbow[3]=1;}
else
{tbow[3]=2;}
float frun1 , frun2 , fbow1 , fbow2 , fwc;
/*Checking whether the contribution of the team exceeds 3 or not and froming the team*/
if(trun[0]==trun[1] && tbow[0]==tbow[1] && trun[0]==tbow[0])
{
frun1 = run[0];
frun2 = run[1];
fbow1 = bow[0];
fbow2 = bow[2];
fwc = ((fbow1+fbow2)*50)*0.5;
}
else
{
frun1 = run[0];
frun2 = run[1];
fbow1 = bow[0];
fbow2 = bow[1];
fwc = ((fbow1+fbow2)*50)*0.5;
}
float ba1 = frun1;
float ba2 = frun2;
float bw1 = 50*fbow1 ;
float bw2 = 50*fbow2 ;
/*Create the fanntasy league team*/
create_node(frun1, &fteam);
create_node(frun2, &fteam);
create_node(fwc, &fteam);
create_node(bw1, &fteam);
create_node(bw2, &fteam);
/*Dispaly the Fantasy league team*/
printf("\nFANTASY LEAGUE :");
show(fteam);
/*Checking which member is from which team*/
printf("\n||TEAM SELECTION||");
if(frun1 == run1 || frun1 == run2)
{printf("\n1st batsman -> Team-1");}
else if(frun1 == run21 || frun1 == run22)
{printf("\n1st batsman -> Team-2");}
if(frun2 == run1 || frun2 == run2)
{printf("\n2nd batsman -> Team-1");}
else if(frun2 == run21 || frun2 == run22)
{printf("\n2nd batsman -> Team-2");}
if(wc1>wc2)
{printf("\nWicket Keeper -> Team-1");}
else
{printf("\nWicket Keeper-> Team-2");}
if(fbow1 == bow1 || fbow1 == bow2)
{printf("\n1st Bowler -> Team-1");}
else if(fbow1 == bow21 || fbow1 == bow22)
{printf("\n1st Bowler -> Team-2");}
if(fbow2 == bow1 || fbow2 == bow2)
{printf("\n2nd Bowler -> Team-1");}
else if(fbow2 == bow21 || fbow2 == bow22)
{printf("\n2nd Bowler -> Team-2");}
float arr[5] ;
arr[0] = ba1;
arr[1] = ba2;
arr[2] = fwc;
arr[3] = bw1;
arr[4] = bw2;
float captain;
captain = arr[0];
for (int i = 0; i < 5; i++)
{
if (arr[i] > captain)
{
captain = arr[i];
}
}
float sbow1 = bow1*50;
float sbow2 = bow2*50;
float sbow21 = bow21*50;
float sbow22 = bow22*50;
printf("\n ||CAPTAIN SELECTION||");
if(captain == run1)
{printf("\nCAPTAIN -> 1ST Batsman of TEAM-1");}
else if(captain == run2)
{printf("\nCAPTAIN -> 2nd Batsman of TEAM-1");}
else if(captain == sbow1)
{printf("\nCAPTAIN -> 1ST Bowler of TEAM-1");}
else if(captain == sbow2)
{printf("\nCAPTAIN -> 2nd Bowler of TEAM-1");}
else if(captain == run21)
{printf("\nCAPTAIN -> 1ST Batsman of TEAM-2");}
else if(captain == run22)
{printf("\nCAPTAIN -> 2nd Batsman of TEAM-2");}
else if(captain == sbow21)
{printf("\nCAPTAIN -> 1ST Bowler of TEAM-2");}
else if(captain == sbow22)
{printf("\nCAPTAIN -> 2nd Bowler of TEAM-2");}
else if(captain == fwc)
{
if(wc1 > wc2)
{printf("\nCAPTAIN -> Wicket Keeper of TEAM-1");}
else
{printf("\nCAPTAIN -> Wicket Keeper of TEAM-2");}
}
float totalscore;
printf("\n ||TOTAL SCORE||");
if(captain==frun1)
{totalscore = (frun1*2)+frun2+(fbow1*50)+(fbow2*50)+fwc;
printf("\nTotal Score of the FANTASY LEAGUE : %f" , totalscore);
}
else if(captain==frun2)
{totalscore = frun1+(frun2*2)+(fbow1*50)+(fbow2*50)+fwc;
printf("\nTotal Score of the FANTASY LEAGUE : %f" , totalscore);
}
else if(captain==fwc)
{totalscore = frun1+frun2+(fbow1*50)+(fbow2*50)+fwc;
printf("\nTotal Score of the FANTASY LEAGUE : %f" , totalscore);
}
else if(captain==fwc)
{totalscore = frun1+frun2+(fbow1*50)+(fbow2*50)+fwc;
printf("\nTotal Score of the FANTASY LEAGUE : %f" , totalscore);
}
else if(captain==bw1)
{totalscore = frun1+frun2+(fbow1*100)+(fbow2*50)+ (((fbow1*100)+(fbow2*50))*0.5);
printf("\nTotal Score of the FANTASY LEAGUE : %f" , totalscore);
}
else if(captain==bw2)
{totalscore = frun1+frun2+(fbow1*50)+(fbow2*100)+ (((fbow1*50)+(fbow2*100))*0.5);
printf("\nTotal Score of the FANTASY LEAGUE : %f" , totalscore);
}
}
</code></pre>
<p>Is there a better way to do as mentioned in question for the problem given above.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T14:13:11.657",
"Id": "389589",
"Score": "1",
"body": "Please choose exactly one indentation style and fix your indentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T14:50:22.020",
"Id": "38... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T13:10:33.827",
"Id": "202125",
"Score": "1",
"Tags": [
"algorithm",
"c",
"game",
"linked-list",
"dynamic-programming"
],
"Title": "selecting 5 best players out of 2 team"
} | 202125 |
<pre><code>Sub SearchSlicer()
Dim oSc As SlicerCache
Dim oSi As SlicerItem
Dim searchword As Variant
searchword = InputBox("Enter a searchword")
Set oSc = ThisWorkbook.SlicerCaches("Slicer_SEARCH_WORDS")
For Each oSi In oSc.SlicerItems
If oSi.Name Like "*" & UCase(searchword) & "*" Then
oSi.Selected = True
Else: oSi.Selected = False
End If
Next
End Sub
</code></pre>
<p>So I have a pivot table with two columns - a column for a verb and a column for search words containing synonyms/similar phrases. For example, if a word in the first column is 'broke', the second column will contain the list 'fell apart, broken, split'.</p>
<p>Running the above code asks the user for a search word which will be used to loop through the search word column and filter the search word pivot table and slicers.</p>
<p>This search word slicer is linked to first column slicer as the search word slicer is not visible on the input sheet.</p>
<p>The reason for using slicers is because I have another code for when the user clicks on a slicer choice, it automatically pastes it into the active cell.</p>
<p>I have a table with 350 rows and this code is already taking very long to run. How can I make this more optimal?</p>
| [] | [
{
"body": "<p>Invariants, variables which don't change in a loop, should be set before entering the loop. Additionally, if you want to store the value of a Boolean expression, just store the expression's return value: </p>\n\n<pre><code>Sub SearchSlicer()\n Dim oSc As SlicerCache\n Dim oSi As SlicerItem\... | {
"AcceptedAnswerId": "202149",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T13:11:44.133",
"Id": "202126",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Speed up looping through slicers and .selected true if slicer item name matches input words"
} | 202126 |
<blockquote>
<p>Given three positive numbers A, B, and C. Find the number of positive
integers less than D that are divisible by either of A, B or C.</p>
<p><strong>Input format</strong></p>
<p>The 1st argument given is an Integer A. The 2nd argument given is an
Integer B. The 3rd argument given is an Integer C. The 4th argument
given is an Integer D.</p>
<p><strong>Output Format</strong></p>
<p>Return an Integer X, the number of positive integers that are
divisible by either of A, B, or C.</p>
<p>Constraints</p>
<p>1 <= A, B, C, D <= 1e9</p>
<p>For Example</p>
<p>Input:</p>
<p>A = 2</p>
<p>B = 3</p>
<p>C = 4</p>
<p>D = 10 </p>
<p>Output:</p>
<p>6</p>
<p>Explanation:</p>
<p>positive numbers less than D that are divisible by either of A, B or C are 2, 3, 4, 6, 8, 9</p>
</blockquote>
<p>My approach:</p>
<pre><code>import java.math.BigInteger;
public class Solution {
public int solve(int A, int B, int C, int D) {
BigInteger numDivA = BigInteger.valueOf((D - 1)/A);
BigInteger numDivB = BigInteger.valueOf((D - 1)/B);
BigInteger numDivC = BigInteger.valueOf((D - 1)/C);
BigInteger newA = BigInteger.valueOf(A);
BigInteger newB = BigInteger.valueOf(B);
BigInteger newC = BigInteger.valueOf(C);
BigInteger newD = BigInteger.valueOf(D);
BigInteger limit = new BigInteger("1000000000");
BigInteger lcmAB = (newA.divide(hcf(newA, newB))).multiply(newB);
BigInteger lcmAC = (newC.divide(hcf(newA, newC))).multiply(newA);
BigInteger lcmBC = (newB.divide(hcf(newB, newC))).multiply(newC);
BigInteger lcmABC = lcmAB.divide(hcf(lcmAB,newC)).multiply(newC);
BigInteger numDivAB = newD.subtract(BigInteger.ONE).divide(lcmAB);
BigInteger numDivBC = newD.subtract(BigInteger.ONE).divide(lcmBC);
BigInteger numDivAC = newD.subtract(BigInteger.ONE).divide(lcmAC);
BigInteger numDivABC = newD.subtract(BigInteger.ONE).divide(lcmABC);
BigInteger numTotal = (((((numDivA.add(numDivB)).add(numDivC)).subtract(numDivAB)).subtract(numDivBC)).subtract(numDivAC)).add(numDivABC);
return (numTotal.mod(limit)).intValue();
}
private BigInteger hcf (BigInteger a, BigInteger b) {
BigInteger hcf = a.gcd(b);
return hcf;
}
}
</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>
<li><p>Have I gone too overboard by using <strong>BigInteger</strong>?</p></li>
</ol>
<p><a href="https://www.interviewbit.com/problems/three-numbers/" rel="nofollow noreferrer">Reference</a></p>
| [] | [
{
"body": "<p>Using BigInteger would increase the complexity of the program you can do it simpily.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T15:14:35.980",
"Id": "389410",
"Score": "5",
"body": "Welcome to Code Review!... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T14:00:50.677",
"Id": "202130",
"Score": "2",
"Tags": [
"java",
"beginner",
"interview-questions",
"complexity"
],
"Title": "Three Numbers in Java"
} | 202130 |
<p>This is basically my first real venture into JS coding ... I think what I have put together here is quite long-winded and could be streamlined but I'm not quite sure how.</p>
<p>I have a table with Columns "Region", "Country", and "Display".</p>
<pre><code>CREATE TABLE [dbo].[DATABASE](
[Region] [varchar](20) NOT NULL,
[Country] [varchar](40) NOT NULL,
[Display] [varchar](1) NULL
) ON [PRIMARY]
</code></pre>
<p>Here is some info from the database</p>
<pre><code>EMEA Azerbaijan Y
CALA Bahamas Y
EMEA Bahrain Y
APAC Bangladesh Y
CALA Barbados Y
EMEA Belarus Y
</code></pre>
<p>Region is either EMEA, CALA or APAC.</p>
<p>Country is the name of the countries in that Region</p>
<p>Display is Y if its to be displayed in the list</p>
<p>e.g.</p>
<p>EMEA / France / Y</p>
<p>EMEA / Italy / Y</p>
<p>APAC / India / Y</p>
<p>the HTML page I would like to display is a selection of regions (countries hidden) and if a region is checked then the countries in that region are displayed with checkboxes so that they can be also selected. The overall idea is to have a list of countries you want to see information on.</p>
<p>You can check an "ALL regions" option and then check an "ALL countries" option to check all that region</p>
<p>Here's the JS:</p>
<pre><code><script>
function ChooseEMEA() {
var checkEMEA = document.getElementById("checkEMEA");
var textEMEA = document.getElementById("textEMEA");
if (checkEMEA.checked == true){
textEMEA.style.display = "block";
} else {
textEMEA.style.display = "none";
var allCB = document.querySelectorAll("input[class='CouCheckEMEA']");
var AllEMEAChecked = document.getElementById("checkAllEMEA");
for(var i=0; i< allCB.length; i++){
allCB[i].checked=false;
}
AllEMEAChecked.checked=false;
}
}
function ChooseAPAC() {
var checkAPAC = document.getElementById("checkAPAC");
var textAPAC = document.getElementById("textAPAC");
if (checkAPAC.checked == true){
textAPAC.style.display = "block";
} else {
textAPAC.style.display = "none";
var allCB = document.querySelectorAll("input[class='CouCheckAPAC']");
var AllAPACChecked = document.getElementById("checkAllAPAC");
for(var i=0; i< allCB.length; i++){
allCB[i].checked=false;
}
AllAPACChecked.checked=false;
}
}
function ChooseCALA() {
var checkCALA = document.getElementById("checkCALA");
var textCALA = document.getElementById("textCALA");
if (checkCALA.checked == true){
textCALA.style.display = "block";
} else {
textCALA.style.display = "none";
var allCB = document.querySelectorAll("input[class='CouCheckCALA']");
var AllCALAChecked = document.getElementById("checkAllCALA");
for(var i=0; i< allCB.length; i++){
allCB[i].checked=false;
}
AllCALAChecked.checked=false;
}
}
function ChooseALL() {
var checkAll = document.getElementById("checkAll");
var checkEMEA = document.getElementById("checkEMEA");
var checkAPAC = document.getElementById("checkAPAC");
var checkCALA = document.getElementById("checkCALA");
var textEMEA = document.getElementById("textEMEA");
var textAPAC = document.getElementById("textAPAC");
var textCALA = document.getElementById("textCALA");
if (checkAll.checked == true){
textEMEA.style.display = "block";
textAPAC.style.display = "block";
textCALA.style.display = "block";
checkAPAC.checked = true;
checkEMEA.checked = true;
checkCALA.checked = true;
} else {
textEMEA.style.display = "none";
textAPAC.style.display = "none";
textCALA.style.display = "none";
checkAPAC.checked = false;
checkEMEA.checked = false;
checkCALA.checked = false;
}
}
function ChooseALLEMEA() {
var allCB = document.querySelectorAll("input[class='CouCheckEMEA']");
var AllEMEAChecked = document.getElementById("checkAllEMEA");
if (AllEMEAChecked.checked == true){
for(var i=0; i< allCB.length; i++){
allCB[i].checked=true;
}
}
else{
for(var i=0; i< allCB.length; i++){
allCB[i].checked=false;
}
}
}
function ChooseALLAPAC() {
var allCB = document.querySelectorAll("input[class='CouCheckAPAC']");
var AllAPACChecked = document.getElementById("checkAllAPAC");
if (AllAPACChecked.checked == true){
for(var i=0; i< allCB.length; i++){
allCB[i].checked=true;
}
}
else{
for(var i=0; i< allCB.length; i++){
allCB[i].checked=false;
}
}
}
function ChooseALLCALA() {
var allCB = document.querySelectorAll("input[class='CouCheckCALA']");
var AllCALAChecked = document.getElementById("checkAllCALA");
if (AllCALAChecked.checked == true){
for(var i=0; i< allCB.length; i++){
allCB[i].checked=true;
}
}
else{
for(var i=0; i< allCB.length; i++){
allCB[i].checked=false;
}
}
}
</script>
</code></pre>
<p>Here's the HTML:</p>
<pre><code><?php
include ('./lib/db_config.php'); //DATABASE logon info and connections
$EMEAsql = "SELECT DISTINCT Country
FROM DATABASE
WHERE Region='EMEA' AND Display='Y'
ORDER BY Country ASC";
$APACsql = "SELECT DISTINCT Country
FROM DATABASE
WHERE Region='APAC' AND Display='Y'
ORDER BY Country ASC";
$CALAsql = "SELECT DISTINCT Country
FROM DATABASE
WHERE Region='CALA' AND Display='Y'
ORDER BY Country ASC";
?>
<table width="80%">
<tr><th>Select your Region</th><th colspan="3">Select your Country</th> <th></th>
</tr>
<tr>
<td width="20%" valign="Top" align="Left">
<form action="./action_page.php" method="POST">
<p>
<input type="checkbox" id="checkAll" onclick="ChooseALL()"> Region All / None<br><br>
<input type="checkbox" id="checkEMEA" class="checkEMEA" onclick="ChooseEMEA()"> EMEA<br>
<input type="checkbox" id="checkAPAC" onclick="ChooseAPAC()"> Asia Pacific<br>
<input type="checkbox" id="checkCALA" onclick="ChooseCALA()"> Canada & Latin America<br>
</p>
</td>
<td width="20%" valign="Top" align="Left">
<p id="textEMEA" style="display:none">
<input type="checkbox" id="checkAllEMEA" class="checkAllEMEA" onclick="ChooseALLEMEA()"> EMEA All / None<br><br>
<?php if (($result = sqlsrv_query($conn, $EMEAsql)) !== false)
{
while ($obj = sqlsrv_fetch_object($result))
{
$Country = ($obj->Country);
echo '<input type="checkbox" class="CouCheckEMEA" name="country[]" value="'.$Country.'" onclick="countrySelect(this.value)">'.$Country.'<br>';
}
}
?>
</p>
</td>
<td width="20%" valign="Top" align="Left">
<p id="textAPAC" style="display:none">
<input type="checkbox" id="checkAllAPAC" name="checkAllAPAC" onclick="ChooseALLAPAC()"> Asia Pacific All / None<br><br>
<?php if (($result = sqlsrv_query($conn, $APACsql)) !== false)
{
while ($obj = sqlsrv_fetch_object($result))
{
$Country = ($obj->Country);
echo '<input type="checkbox" class="CouCheckAPAC" name="country[]" value="'.$Country.'" onclick="countrySelect(this.value)">'.$Country.'<br>';
}
}
?>
</td>
<td width="20%" valign="Top" align="Left">
</p>
<p id="textCALA" style="display:none">
<input type="checkbox" id="checkAllCALA" name="checkAllCALA" onclick="ChooseALLCALA()"> Canada & Latin America All / None<br><br>
<?php if (($result = sqlsrv_query($conn, $CALAsql)) !== false)
{
while ($obj = sqlsrv_fetch_object($result))
{
$Country = ($obj->Country);
echo '<input type="checkbox" class="CouCheckCALA" name="country[]" value="'.$Country.'" onclick="countrySelect(this.value)">'.$Country.'<br>';
}
}
?>
</p>
</td>
<td width="20%" valign="Top" align="Left">
<button type="submit">Submit form</button>
</td>
</tr>
</form>
</code></pre>
<p>Am I over complicating my JavaScript functions?</p>
<p>I'm wondering if using DIV elements would be a smarter way of working this and if the JS can be consolidated in some way</p>
| [] | [
{
"body": "<p>You're repeating a lot of code that you could greatly condense with a little extra work.</p>\n\n<p>An excellent rule to follow is DRY: don't repeat yourself. If you see large blocks of code that repeat two or more times, consider condensing and implementing variables to keep the functionality.</p>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T14:58:47.017",
"Id": "202137",
"Score": "2",
"Tags": [
"javascript",
"php",
"html",
"sql",
"form"
],
"Title": "Dynamically displaying or hiding checkboxes based on region selection country. Also select All / None included"
} | 202137 |
<p>I am trying to calculate a customized concordance index for survival analysis. Below is my code. It runs well for small input dataframe but extremely slow on a dataframe with one million rows (>30min).</p>
<pre><code>import pandas as pd
def c_index1(y_pred, events, times):
df = pd.DataFrame(data={'proba':y_pred, 'event':events, 'time':times})
n_total_correct = 0
n_total_comparable = 0
df = df.sort_values(by=['time'])
for i, row in df.iterrows():
if row['event'] == 1:
comparable_rows = df[(df['event'] == 0) & (df['time'] > row['time'])]
n_correct_rows = len(comparable_rows[comparable_rows['proba'] < row['proba']])
n_total_correct += n_correct_rows
n_total_comparable += len(comparable_rows)
return n_total_correct / n_total_comparable if n_total_comparable else None
c = c_index([0.1, 0.3, 0.67, 0.45, 0.56], [1.0,0.0,1.0,0.0,1.0], [3.1,4.5,6.7,5.2,3.4])
print(c) # print 0.5
</code></pre>
<p>For each row (in case it matters...):</p>
<ul>
<li><p>If the event of the row is 1: retrieve all comparable rows whose </p>
<ol>
<li>index is larger (avoid duplicate calculation), </li>
<li>event is 0, and </li>
<li>time is larger than the time of the current row. Out of the comparable rows, the rows whose probability is less than the current row are correct predictions.</li>
</ol></li>
</ul>
<p>I guess it is slow because of the <code>for</code> loop. How should I speed up it?</p>
| [] | [
{
"body": "<p>You will not get dramatic speedups untill you can vectorize the operations, but here are some tips already</p>\n\n<h1>indexing before iterating</h1>\n\n<p>instead of </p>\n\n<pre><code>for i, row in df.iterrows():\n if row['event'] == 1:\n</code></pre>\n\n<p>If you do </p>\n\n<pre><code>for i, ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T15:13:42.333",
"Id": "202140",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Concordance index calculation"
} | 202140 |
<p>I'm trying to train my neural network and for the most part it's going well. However, I'd like it if it could train faster and was wondering if anyone could give some advice. </p>
<p>I'm trying mostly to understand the concept and didn't want to use any libraries like Tensorflow or Keras to make my network with, so I expected things to be slow. I'd just like to know if there's a more efficient method I could use to train my network.</p>
<p>Currently the code is trying to solve for the amount of x-intercepts in a quadratic function. I used a hyperbolic tangent activation to restrict the output between 1 and -1 and then just shifted it up one unit so it ends up where all possible answers are between 2 and 0.</p>
<p>If there is a more efficient method of doing this (without using numpy, tensorflow or other machine learning libraries) I would like to know.
Thanks in advance!</p>
<p>Here is my code:</p>
<pre><code>def tanh(x, derivative=False):
if (derivative):
return 1-(np.tanh(x)**2)
else:
return np.tanh(x)
bias = 1
learningrate = 0.5
w43 = -0.00761961638643
w42 = -0.00277057293921
w41 = -0.00761961638643
w4bias = 0.0125605873166
w3a = 0.999999973314
w3b = 0.999999946628
w3c = 0.999999973314
w3bias = 0.999430439099
w2a = -1.76817386861
w2b = -1.87500335887
w2c = -3.53116339806
w2bias = 0.972644723607
w1a = 1.00
w1b = 0.999999946628
w1c = 0.999999946628
w1bias = 0.999430439099
def add(x,y):
f = open(y)
lines = f.read()
f.close()
f = open(y, 'w')
f.write(lines)
f.write("\n<br>"+x)
f.close()
def u1(a, b, c):
global w1a
global w1b
global w1c
global w1bias
global bias
return tanh((bias*w1bias)+(w1a*a)+(w1b*b)+(w1c*c))
def u2(a, b, c):
global w2a
global w2b
global w2c
global w2bias
global bias
return tanh((bias*w2bias)+(w2a*a)+(w2b*b)+(w2c*c))
def u3(a, b, c):
global w3a
global w3b
global w3c
global w3bias
global bias
return tanh((bias*w3bias)+(w3a*a)+(w3b*b)+(w3c*c))
def u4(a, b, c):
global w43
global w42
global w41
global w4bias
global bias
return tanh((bias*w4bias)+(w43*u3(a,b,c))+(w42*u2(a,b,c))+(w41*u1(a,b,c)))
def feedforward(a, b, c):
return u4(a,b,c)+1
def error(a,b,c,d):
return ((d-feedforward(a,b,c))**2)/100
def backpropagation(a,b,c,d):
global learningrate
global w43
global w42
global w41
global w4bias
global w3a
global w3b
global w3c
global w3bias
global w2a
global w2b
global w2c
global w2bias
global w1a
global w1b
global w1c
global w1bias
result = feedforward(a,b,c)
delta0 = (d-result)*result*((1-result)**2)
delta3 = (delta0*w43)*u3(a,b,c)*(1-u3(a,b,c))
delta2 = (delta0*w42)*u2(a,b,c)*(1-u4(a,b,c))
delta1 = (delta0*w41)*u1(a,b,c)*(1-u1(a,b,c))
#adjustments
outputAdjustment = (learningrate*delta0)
w43 += outputAdjustment*u3(a,b,c)
w42 += outputAdjustment*u2(a,b,c)
w41 += outputAdjustment*u1(a,b,c)
w4bias += outputAdjustment
u3Adjustment = learningrate*delta3
w3c += u3Adjustment*c
w3b += u3Adjustment*b
w3a += u3Adjustment*a
w3bias += u3Adjustment
u2Adjustment = learningrate*delta2
w2c += u2Adjustment*c
w2b += u2Adjustment*b
w2a += u2Adjustment*a
w2bias += u2Adjustment
u1Adjustment = learningrate*delta1
w1c += u1Adjustment*c
w1b += u1Adjustment*b
w1c += u1Adjustment*a
w1bias += u1Adjustment
def train(data):
testing = [[2,3,4,0], [1,3,5,0], [1,5,3,2], [2,12,4,2], [4,8,4,0], [6,12,6,0]]
passed = False
count = 0
while (not passed):
for _ in range(500):
avgerr = 0
for i in data:
backpropagation(i[0], i[1], i[2], i[3])
avgerr += error(i[0], i[1], i[2], i[3])
avgerr = avgerr/len(data)
if (_%100 == 0):
print avgerr
add(str(avgerr), "index.html")
c = 0
for i in testing:
if int(round(feedforward(i[0], i[1], i[2]))) == i[3]:
c+=1
if c == 6:
break
f = open('weights-temp.txt', 'w')
f.write("w43 " + str(w43))
f.write("\nw42 " + str(w42))
f.write("\nw41 " + str(w41))
f.write("\nw4bias " + str(w4bias))
f.write("\nw3a " + str(w3a))
f.write("\nw3b " + str(w3b))
f.write("\nw3c " + str(w3c))
f.write("\nw3bias " + str(w3bias))
f.write("\nw2a " + str(w2a))
f.write("\nw2b " + str(w2b))
f.write("\nw2c " + str(w2c))
f.write("\nw2bias " + str(w2bias))
f.write("\nw1a " + str(w1a))
f.write("\nw1b " + str(w1b))
f.write("\nw1c " + str(w1c))
f.write("\nw1bias " + str(w1bias))
f.close()
train(dataset)
a = ""
while a != "quit":
a = raw_input(">> ")
if a == "test":
alpha = int(raw_input("alpha: "))
beta = int(raw_input("beta: "))
gamma = int(raw_input("gamma: "))
print feedforward(alpha, beta, gamma)
if a == "train":
train(dataset)
if a == "weights":
print w43
print w42
print w41
print w4bias
print
print w3c
print w3b
print w3a
print w3bias
print
print w2c
print w2b
print w2a
print w2bias
print
print w1c
print w1b
print w1a
print w1bias
f = open('weights.txt', 'w')
f.write("w43 " + str(w43))
f.write("w42 " + str(w42))
f.write("w41 " + str(w41))
f.write("w4bias " + str(w4bias))
f.write("w3c " + str(w3c))
f.write("w3b " + str(w3b))
f.write("w3a " + str(w3a))
f.write("w3bias " + str(w3bias))
f.write("w2c " + str(w2c))
f.write("w2b " + str(w2b))
f.write("w2a " + str(w2a))
f.write("w2bias " + str(w2bias))
f.write("w1c " + str(w1c))
f.write("w1b " + str(w1b))
f.write("w1a " + str(w1a))
f.write("w1bias " + str(w1bias))
f.close()
</code></pre>
| [] | [
{
"body": "<p>This will be a short review because the neural network seems okay.</p>\n\n<ol>\n<li><p>Use <code>numpy</code>. It isn't \"cheating\" if you want to learn about neural networks, but it will make every computation much faster and help you understand how to use matrices in Python. Numpy is much faste... | {
"AcceptedAnswerId": "228983",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T16:01:13.113",
"Id": "202145",
"Score": "3",
"Tags": [
"python",
"machine-learning",
"neural-network",
"python-2.x"
],
"Title": "How to make my neural network train faster"
} | 202145 |
<p>I am trying to model information around football teams and fixtures. I am using the Premier League fantasy football API for my data. The fixtures API is <a href="https://fantasy.premierleague.com/drf/fixtures/" rel="nofollow noreferrer">here</a>, and the team data (along with a lot of extra data) is <a href="https://fantasy.premierleague.com/drf/bootstrap-static" rel="nofollow noreferrer">here</a> - see the "teams" element.</p>
<p>I want to be able to do things like report on all of Arsenal's fixtures/results, for example...</p>
<pre><code>ARSENAL
event kickoff opponent venue result scoreline
1 12 aug 16:00 Manchester City H L 1-2
2 18 Aug 17:30 Chelsea A L 2-3
3 25 Aug 15:00 West Ham H -
</code></pre>
<p>However I may want to access more data items than shown here - it's just an example.</p>
<p>I'm experienced with database, so if I were writing this to a normalized database I would have two tables, teams and fixtures, and I could write a query like this.</p>
<pre><code>SELECT t.team_name, f.[event], f.kickoff, opp.name,
CASE WHEN t.team_id = f.home_team_id THEN 'H' ELSE 'A' END AS venue,
CASE WHEN f.team_h_score IS NULL THEN '-'
WHEN f.team_h_score = f.team_a_score THEN 'D'
WHEN f.team_h_score > f.team_a_score AND t.team_id = f.home_team_id THEN 'W'
WHEN f.team_h_score < f.team_a_score AND t.team_id = f.away_team_id THEN 'W'
ELSE 'L' END AS result,
CASE WHEN t.team_id = f.home_team_id THEN f.team_h_score ELSE team_a_score END as own_score,
CASE WHEN t.team_id = f.home_team_id THEN f.team_a_score ELSE team_h_score END as opp_score
FROM team t
INNER JOIN fixture f ON t.team_id IN (f.away_team_id, f.home_team_id)
INNER JOIN team opp ON opp.team_id IN (f.away_team_id, f.home_team_id)
WHERE t.team_id = @input_team_id
</code></pre>
<p>I would be happy with this - it "feels" pretty good and I trust my feelings - I know there are rules and principles that I am following but they have been internalised such that I can usually "feel" what is right in database design.</p>
<p>However, when I'm trying to write this in an object-oriented way, I have much less experience so I'm trying to follow guidelines and principles of object-oriented design - SRP, managing dependencies and so on. </p>
<p>I decided that starting from the SQL above is a decent way to start. So, here's my thinking so far. There obviously needs to be a team class and a fixture class. I also thought a TeamFixture class would be good too - and can encapsulate some of the logic in the long case statements above.</p>
<pre><code>class Databank
def initialize
#some stuff outside the scope of this review
#just assume the fixtures and teams methods work
end
def fixtures
#returns array of all Fixtures
end
def teams
#returns array of all Teams
end
end
class Fixture
attr_reader :data
def initialize(data)
@data = data
end
end
class Team
attr_reader :data, :fixtures
def initialize(data, fixtures)
@data = data
@fixtures = fixtures.map { |f| TeamFixture.new(f, @data['id']) }
end
end
class TeamFixture
attr_reader :fixture, :venue
def initialize(fixture,team_id)
@fixture=fixture
@venue = fixture.data['team_h']==team_id ? 'H' : 'A'
@h_score = fixture.data['team_h_score']
@a_score = fixture.data['team_a_score']
end
def result
return '-' if @h_score=='null'
return 'D' if @h_score==@a_score
winner = @h_score==@a_score ? 'H' : 'A'
return @venue==winner ? 'W' : 'L'
end
def own_score
@venue=='H' ? @h_score : @a_score
end
def opp_score
@venue=='H' ? @a_score : @h_score
end
def opponent
id = @venue=='H' ? @fixture['team_a'] : @fixture['team_h']
# How to get from this id to the Team object it represents?
end
end
</code></pre>
<p>I'm left asking myself three questions that I'm not sure how to answer. Though feel free to make any other comments.</p>
<ol>
<li><p>If I want to access information about an opponent, I feel like I'm "reaching through" many objects, for example to print every fixture for every team it would be something like this...</p>
<pre><code>d = Databank.new
d.teams.each |t| do
puts "#{t.data['name']} are playing these teams..."
t.fixtures.each |tf| do
puts "#{tf.fixture.data['kickoff_time_formatted']} - #{tf.opponent.data['name']}"
end
end
</code></pre>
<p>So effectively I'm doing Databank → teams → teamFixture → opponent.data albeit across a few lines. The Law of Demeter states that this is not <em>usually</em> a good thing, but I'm not experienced enough to know if this is a <em>good</em> violation or not? My database voice in my head says this is fine but the OOP voice isn't so sure.</p></li>
<li><p>I don't like the Team and Fixture classes, having to write <code>t.data['name']</code> feels clunky and that it would be easier to just call <code>t['name']</code>, <code>t[:name]</code> or <code>t.name</code>. However looking around I can't seem to find a "good" way to achieve this. I understand that subclassing a <code>Hash</code> is a bad idea. Then there's <a href="https://stackoverflow.com/questions/26809848/convert-hash-to-object">this Stackoverflow question</a>, which suggests either an OpenStruct (which wouldn't work for the nested nature of some of my data) or some ugly-looking code to achieve this. Am I right in wanting something like <code>t['name']</code> to work, and if so how should I go about it?</p></li>
<li><p>The opponent method is not finished. What is the best way to get it to return the appropriate Team object? If I had an Enumerable of the teams I could do <code>teams.find { |t| t["id"]==id}</code> but such an Enumerable is only in the Databank object, so it would be a lot of reaching through objects again and it does not feel right at all to do this.</p></li>
</ol>
| [] | [
{
"body": "<p>I should say that your work might get easier here if you are using an ORM such as ActiveRecord or Squeel or Sequel.</p>\n\n<p>I think that the <code>TeamFixture</code> may be incorrect there.</p>\n\n<p><code>Fixture</code> feels like an object, with attributes of <code>home_team_id</code> and <cod... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T18:27:59.630",
"Id": "202153",
"Score": "2",
"Tags": [
"object-oriented",
"ruby",
"ruby-on-rails"
],
"Title": "Modelling football teams and fixtures in Ruby (as compared to SQL)"
} | 202153 |
<p>I use the code below to calculate the required information from other tables. I used joins to display names instead of IDs and to get required sums from other tables. I used <code>COALESCE</code> to convert null to zero.</p>
<p>I had to used it again if I need to sum already COALESCED values. The code below is hard to understand and it's getting harder because I need to add more information. This is just a small part of the main project so it will be really hard to work with it and will have many error and bugs.</p>
<p>Does it have to be so complicated or did I do it wrong? If it has to be complicated like this, is there any replacement to get same results with easier way and code, maybe with an RDBMS other than Firebird?</p>
<pre><code>SELECT P.PROJ_ID, P.PROJ_STATUS, P.TYPE_ID, PT.TYPE_NAME, P.CLASS_ID, CLA.CLASS_NAME, P.PROJ_NO, P.PROJ_YEAR, P.PROJ_NAME, P.OLD_PROJ_NAME,
P.AGENCY_ID, A.AGENCY_NAME, P.CONTRACT_NO, P.CONTRACT_DATE, P.MINISTRY_ID, M.MINISTRY_NAME,
P.DIRECTORATE_ID, DIR.DIRECTORATE_NAME,
P.COST, P.ESTIMATED_COST, COALESCE(CO.ADDED_COSTS, 0) AS ADDED_COSTS, (COALESCE(P.COST, 0) + COALESCE(CO.ADDED_COSTS, 0)) AS TOTAL_COST,
P.ALLOCATION,
COALESCE(EPY.PAST_YEARS, 0) AS PAST_YEARS,
COALESCE(EF.PAST_MONTHS, 0) AS PAST_MONTHS,
COALESCE(ECM.CURRENT_MONTH, 0) AS CURRENT_MONTH,
COALESCE(ECY.CURRENT_YEAR, 0) AS CURRENT_YEAR,
COALESCE(E.TOTAL_EXPENSES, 0) AS TOTAL_EXPENSES,
COALESCE(CASH_EPY.CASH_PAST_YEARS, 0) AS CASH_PAST_YEARS,
COALESCE(CASH_EF.CASH_PAST_MONTHS, 0) AS CASH_PAST_MONTHS,
COALESCE(CASH_ECM.CASH_CURRENT_MONTH, 0) AS CASH_CURRENT_MONTH,
COALESCE(CASH_ECY.CASH_CURRENT_YEAR, 0) AS CASH_CURRENT_YEAR,
COALESCE(CASH_E.CASH_TOTAL_EXPENSES, 0) AS CASH_TOTAL_EXPENSES,
COALESCE(TOTAL_E.TOTAL_EXPENSES_CASH, 0) AS TOTAL_EXPENSES_CASH,
((COALESCE(P.COST, 0) + COALESCE(CO.ADDED_COSTS, 0)) - COALESCE(E.TOTAL_EXPENSES, 0)) AS REMAINING,
P.DURATION, COALESCE(DU.ADDED_DURATIONS, 0) AS ADDED_DURATIONS,
(COALESCE(P.DURATION, 0) + COALESCE(DU.ADDED_DURATIONS, 0)) AS TOTAL_DURATION, P.START_DATE, P.FINISH_DATE,
P.GOVERNORATE_ID, G.GOVERNORATE_NAME, P.PROVINCE_ID, PR.PROVINCE_NAME, P.DISTRICT_ID, D.DISTRICT_NAME,
P.TOWN_ID, T.TOWN_NAME,
COALESCE( (E.TOTAL_EXPENSES / (COALESCE(P.COST, 0) + COALESCE(CO.ADDED_COSTS, 0)))/100, 0) AS FINANCIAL_ACHIEVEMENT,
P.MATERIAL_ACHIEVEMENT, P.NOTES
FROM PROJECTS P
INNER JOIN PROJECTS_TYPES PT
ON P.TYPE_ID = PT.TYPE_ID
INNER JOIN CLASSES CLA
ON P.CLASS_ID = CLA.CLASS_ID
INNER JOIN AGENCIES A
ON P.AGENCY_ID = A.AGENCY_ID
LEFT JOIN MINISTRIES M
ON P.MINISTRY_ID = M.MINISTRY_ID
LEFT JOIN DIRECTORATES DIR
ON P.DIRECTORATE_ID = DIR.DIRECTORATE_ID
INNER JOIN GOVERNORATES G
ON P.GOVERNORATE_ID = G.GOVERNORATE_ID
LEFT JOIN PROVINCES PR
ON P.PROVINCE_ID = PR.PROVINCE_ID
LEFT JOIN DISTRICTS D
ON P.DISTRICT_ID = D.DISTRICT_ID
LEFT JOIN TOWNS T
ON P.TOWN_ID = T.TOWN_ID
-- ADDED COSTS
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(ADDED_VALUE, 0) - COALESCE(REMOVED_VALUE, 0)) as ADDED_COSTS
FROM COSTS
GROUP BY PROJ_ID ) AS CO
ON P.PROJ_ID = CO.PROJ_ID
-- EXPENSES FROM PAST YEARS
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as PAST_YEARS
FROM EXPENSES WHERE EXTRACT(YEAR FROM DOC_DATE) < EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = FALSE
GROUP BY PROJ_ID ) AS EPY
ON P.PROJ_ID= EPY.PROJ_ID
-- EXPENSES FROM PAST MONTHS IN CUREENT YEAR
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as PAST_MONTHS
FROM EXPENSES WHERE EXTRACT(MONTH FROM DOC_DATE) < EXTRACT(MONTH FROM CURRENT_DATE)
AND EXTRACT(YEAR FROM DOC_DATE) = EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = FALSE
GROUP BY PROJ_ID ) AS EF
ON P.PROJ_ID= EF.PROJ_ID
-- EXPENSES FROM CURRENT MONTH AND YEAR
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CURRENT_MONTH
FROM EXPENSES WHERE EXTRACT(MONTH FROM DOC_DATE) = EXTRACT(MONTH FROM CURRENT_DATE) AND EXTRACT(YEAR FROM DOC_DATE) = EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = FALSE
GROUP BY PROJ_ID ) AS ECM
ON P.PROJ_ID= ECM.PROJ_ID
-- SUM OF EXPENSES IN CURRENT YEAR
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CURRENT_YEAR
FROM EXPENSES WHERE EXTRACT(YEAR FROM DOC_DATE) = EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = FALSE
GROUP BY PROJ_ID ) AS ECY
ON P.PROJ_ID= ECY.PROJ_ID
-- TOTAL EXPENSES FROM ALL TIME
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as TOTAL_EXPENSES
FROM EXPENSES WHERE CASH_DEDUCTIONS = FALSE
GROUP BY PROJ_ID ) AS E
ON P.PROJ_ID= E.PROJ_ID
-- CASH DEDUCTIONS SUMS
-- CASH DEDUCTIONS FROM PAST YEARS
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CASH_PAST_YEARS
FROM EXPENSES WHERE EXTRACT(YEAR FROM DOC_DATE) < EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = TRUE
GROUP BY PROJ_ID ) AS CASH_EPY
ON P.PROJ_ID= CASH_EPY.PROJ_ID
-- CASH DEDUCTIONS FROM PAST MONTHS IN CUREENT YEAR
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CASH_PAST_MONTHS
FROM EXPENSES WHERE EXTRACT(MONTH FROM DOC_DATE) < EXTRACT(MONTH FROM CURRENT_DATE)
AND EXTRACT(YEAR FROM DOC_DATE) = EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = TRUE
GROUP BY PROJ_ID ) AS CASH_EF
ON P.PROJ_ID= CASH_EF.PROJ_ID
-- CASH DEDUCTIONS FROM CURRENT MONTH AND YEAR
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CASH_CURRENT_MONTH
FROM EXPENSES WHERE EXTRACT(MONTH FROM DOC_DATE) = EXTRACT(MONTH FROM CURRENT_DATE) AND EXTRACT(YEAR FROM DOC_DATE) = EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = TRUE
GROUP BY PROJ_ID ) AS CASH_ECM
ON P.PROJ_ID= CASH_ECM.PROJ_ID
-- SUM OF CASH DEDUCTIONS IN CURRENT YEAR
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CASH_CURRENT_YEAR
FROM EXPENSES WHERE EXTRACT(YEAR FROM DOC_DATE) = EXTRACT(YEAR FROM CURRENT_DATE) AND CASH_DEDUCTIONS = TRUE
GROUP BY PROJ_ID ) AS CASH_ECY
ON P.PROJ_ID= CASH_ECY.PROJ_ID
-- TOTAL CASH DEDUCTIONS FROM ALL TIME
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as CASH_TOTAL_EXPENSES
FROM EXPENSES WHERE CASH_DEDUCTIONS = TRUE
GROUP BY PROJ_ID ) AS CASH_E
ON P.PROJ_ID= CASH_E.PROJ_ID
-- TOTAL EXPENSES AND CASH DEDUCTIONS FROM ALL TIME
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(TOTAL_VALUE, 0)) as TOTAL_EXPENSES_CASH
FROM EXPENSES
GROUP BY PROJ_ID ) AS TOTAL_E
ON P.PROJ_ID= TOTAL_E.PROJ_ID
-- ADDED DURATIONS
LEFT JOIN (SELECT PROJ_ID, SUM(COALESCE(ADDED_VALUE, 0) - COALESCE(REMOVED_VALUE, 0)) as ADDED_DURATIONS
FROM DURATIONS
GROUP BY PROJ_ID ) AS DU
ON P.PROJ_ID= DU.PROJ_ID
ORDER BY P.PROJ_YEAR, P.TYPE_ID, P.PROJ_NO
</code></pre>
| [] | [
{
"body": "<p>I'd use <a href=\"https://firebirdsql.org/refdocs/langrefupd21-select.html\" rel=\"nofollow noreferrer\">common table expressions (CTE)</a> for <code>COSTS</code>, <code>EXPENSES</code> and <code>DURATIONS</code> tables. In the CTE, you can do all the calculations that require a <code>WHERE</code>... | {
"AcceptedAnswerId": "202179",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T18:38:04.263",
"Id": "202155",
"Score": "3",
"Tags": [
"sql",
"database",
"join"
],
"Title": "Project management query for various organizational units"
} | 202155 |
<p>I created this class to handle some dropdowns that I'd been creating using a squirrelly combination of HTML, jQuery, and AJAX. This works much better in the one script that I've deployed it in: </p>
<pre><code>namespace appwpclass;
class PopulateDropdown
{
public $skillArray;
public $grpArray;
public $facArray;
/**
* PopulateDropdown constructor.
*/
public function __construct() {
$skillArray[] = $this->skillArray;
$grpArray[] = $this->grpArray;
$facArray[] = $this->facArray;
}
public function skillSelect($category){
//query to db to get skills
return $skillArray;
} //end function
public function groupSelect($category, $mem_type, $selected_group=NULL){
// query to get list of clients -- it is allowed to be NULL in which case ALL active clients will be returned
return $grpArray;
} //end function
public function facilitySelect($selected_group){
//query to get list of facilities associated with a $selected_group, which is a required field.
return $facArray;
} //end function
} //end class
</code></pre>
<p>Now, in my admittedly "procedural" PHP script (which I'm trying to refactor), I have "required" this Class: </p>
<pre><code>require '../appwpclass/PopulateDropdown.php';
</code></pre>
<p>And in that script, I have these statements in order to populate the various dropdowns:</p>
<pre><code>$dropdown = new appwpclass\PopulateDropdown();
$skillsArr = $dropdown->skillSelect($category);
$groupArr = $dropdown->groupSelect($category, $memType, $selGroup);
$facilityArr = $dropdown->facilitySelect($selGroup);
</code></pre>
<p>And then I use those arrays in filter dropdown HTML, as in this example:</p>
<pre><code><select name="selGroup" id="selGroup" size="1" class="textfield" onchange="submit()">
<option value="0">--Any--</option>
<?php
foreach( $groupArr as $group_id=>$group_name ) {
$selected = ( $group_id == $selGroup ) ? ' selected' : '';
?>
<option value="<?php echo $group_id;?>"<?php echo $selected;?>><?php echo $group_name;?></option>
<?php } ?>
</code></pre>
<p></p>
<p>This all works fine in this one script, but I have a lot of scripts that also use one, two, or all of these dropdowns.
So I thought about just using them in a "require" somewhere in each script, but I'm thinking there has to be a better OOP way.
Maybe I should create another class and instantiate PopulateDropdown in that class's constructor? Or in another method in that other class? And then have a separate method for each of those statements, e.g. a method for</p>
<pre><code> $skillsArr = $dropdown->skillSelect($category)
</code></pre>
<p>, etc.. I guess if I did that, I'd need to "pass" the 3 properties that are required by one or more of these existing methods.</p>
<p>Would anyone please provide me some direction on this? I'm pretty new to OOP and I'm starting to use Laravel but I'm nowhere near ready to refactor this enterprise system yet.</p>
<p>If I used a new class, as I suggested, then obviously I'd <code>require</code> that class or <code>use</code> that namespace in my other scripts. Just seems like that would be more concise and less prone to errors.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T18:55:47.870",
"Id": "389439",
"Score": "0",
"body": "When adding additional information you should [edit] your question instead of adding a comment. I have added that information to your post. Learn more about comments including w... | [
{
"body": "<p>For such a use case a class would be rather useless. A class is used to encapsulate the stuff that belongs to just a single matter. Here, there is nothing in common between these functions.</p>\n\n<p>If you want to use a class, consider creating a class related to Skills, with one of its methods r... | {
"AcceptedAnswerId": "202193",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T18:40:44.253",
"Id": "202156",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "Class creating dropdown options from MySQL data for multiple scripts"
} | 202156 |
<p>On the fly, I just implemented this iterator supporting vector class to understand how range-based for loop works.
It's really basic but let me know what can be improved.</p>
<p><em>Vector.h</em></p>
<pre><code>#ifndef VECTOR_H
#define VECTOR_H
#include <stdexcept>
template <typename T>
class Vector
{
public:
/* The iterator */
class Iterator
{
public:
Iterator(const Vector<T> *vector, int nIndex);
const T &operator*() const;
Iterator &operator++();
bool operator!=(const Iterator &other) const;
private:
const Vector<T> *m_pVector;
int m_nIndex = -1;
};
public:
// constructors
Vector() = default;
explicit Vector(int nSize);
~Vector();
void insert(const T &value);
int size() const;
const T &operator[](int nIndex) const;
Iterator begin() const;
Iterator end() const;
private:
T *m_pData = nullptr;
int m_nSize = 0;
int m_nCapacity = 0;
};
/*
* Vector methods
**/
template <typename T>
Vector<T>::Vector(int nCapacity)
{
m_nCapacity = nCapacity;
m_pData = new T[m_nCapacity];
}
template <typename T>
Vector<T>::~Vector()
{
delete m_pData;
m_nSize = 0;
m_nCapacity = 0;
}
template <typename T>
void Vector<T>::insert(const T &value)
{
if (m_nSize == m_nCapacity)
{
if (m_nCapacity == 0)
m_nCapacity = 1;
m_nCapacity *= 2;
// allocate 2x larger memory
auto pNewMemory = new T[m_nCapacity];
// copy data to there
for (auto idx = 0; idx < m_nSize; ++idx)
pNewMemory[idx] = m_pData[idx];
delete m_pData;
m_pData = pNewMemory;
}
// insert the new element
m_pData[m_nSize] = value;
++m_nSize;
}
template <typename T>
int Vector<T>::size() const
{
return m_nSize;
}
template <typename T>
const T &Vector<T>::operator[](int nIndex) const
{
if (nIndex >= m_nSize)
throw std::exception("Index out of range");
return m_pData[nIndex];
}
template <typename T>
typename Vector<T>::Iterator Vector<T>::begin() const
{
return Vector<T>::Iterator{ this, 0 };
}
template <typename T>
typename Vector<T>::Iterator Vector<T>::end() const
{
return Vector<T>::Iterator{ this, m_nSize };
}
/*
* Iterator methods
**/
template <typename T>
Vector<T>::Iterator::Iterator(const Vector<T> *pVector, int nIndex)
: m_pVector(pVector)
, m_nIndex(nIndex)
{
}
template <typename T>
const T &Vector<T>::Iterator::operator*() const
{
return m_pVector->operator[](m_nIndex);
}
template <typename T>
typename Vector<T>::Iterator &Vector<T>::Iterator::operator++()
{
++m_nIndex;
return *this;
}
template <typename T>
bool Vector<T>::Iterator::operator!=(const Vector<T>::Iterator &other) const
{
return m_nIndex != other.m_nIndex;
}
#endif // !VECTOR_H
</code></pre>
<p><em>main.cpp</em></p>
<pre><code>#include <iostream>
#include "Vector.h"
int main()
{
try
{
Vector<int> vector;
vector.insert(8);
vector.insert(3);
vector.insert(1);
vector.insert(7);
vector.insert(2);
for (auto i : vector)
std::cout << i << std::endl;
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
}
std::cin.get();
return 0;
}
</code></pre>
| [] | [
{
"body": "<h2>Use <code>delete[]</code></h2>\n\n<p>You are allocating an array of objects with <code>new[]</code>, but attempting to delete them with <code>delete</code>, which results in undefined behavior. You should delete the array with <code>delete[]</code> to ensure that your code functions properly. Do ... | {
"AcceptedAnswerId": "202165",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T19:28:25.387",
"Id": "202157",
"Score": "14",
"Tags": [
"c++",
"iterator",
"vectors"
],
"Title": "Basic iterator supporting vector implementation"
} | 202157 |
<p>I have written the beginning of a map engine which runs off PIL and some JavaScript client side. Ignoring the rest of the code that is in the same file as this function, can you suggest any improvements to this code here?</p>
<pre><code>def convert_colour(region_number, incolour, outcolour):
#print(region_list.regions_d[region_number][0].split('\\')[7], incolour, outcolour)
img = Image.open(region_list.regions_d[region_number][0])
img = img.convert("RGBA")
newData = []
newData = [outcolour if item==incolour else item for item in img.getdata()]
img.putdata(newData)
img.save(region_list.regions_d[region_number][0], "PNG")
colour_change_single(region_number, outcolour)
</code></pre>
<p>Further to a suggestion I have tried to include <code>numpy</code> but recieve the following error:</p>
<pre><code>Traceback (most recent call last):
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 227, in <module>
run_function_tests()
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 219, in run_function_tests
run_engine_test(change_list)
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 161, in run_engine_test
convert_colour(x[0], region_list.regions_d[x[0]][1], x[1])
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 115, in convert_colour
new_img = _convert_colour(img, incolour, outcolour)
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 108, in _convert_colour
img[_colour_mask(img, incolour)] = outcolour
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (216,4)
</code></pre>
<p>I realised there needs maybe some clarity about this traceback.
<code>run_function_tests()</code> this has code to run a short test with my old code.</p>
<pre><code>def run_engine_test(change_list):
for x in change_list:
convert_colour(x[0], region_list.regions_d[x[0]][1], x[1])
</code></pre>
<p><code>change_list = [(n,random.choice(colour_list.colour_list)) for n in region_list.regions_d]</code></p>
<p>We also have a function called colour detect which will check for patterns in the colour</p>
<pre><code>def colour_detect():
#Detect if colours in the image match the colours on the palette and re-maps the dictionary if a region colour is changed
detected_colours = []
for x in region_list.regions_d:
region_colour = print_img_data(region_list.regions_d[x][0])
region_list.regions_d[x] = [region_list.regions_d[x][0], region_colour]
if region_colour not in detected_colours:
detected_colours.append(region_colour)
</code></pre>
<p>This is intended to be run at the beginnig of a "game or round" and then in between the engine ticks when actions like wars are comitted. Hence why it checks all of the images to ensure that the dictionary has been updated correctly.</p>
<p>After that the traceback comes from your functions.</p>
<p>[Edit]
The error was related to a typo in my code. The suggestion provided reduced the time to do the functions by 2/3rds!!!!</p>
<p>This is the image i am editing (c)
<a href="https://i.stack.imgur.com/EYDS3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EYDS3.png" alt="Image that I am editing, note, all sections have their own file."></a></p>
| [] | [
{
"body": "<p>Add a \"\"\"docstring\"\"\" describing what the function does, and what the arguments do. </p>\n\n<p>Remove <code>newData = []</code></p>\n\n<p>Perhaps rename <code>incolour</code> and <code>outcolour</code> to more descriptive names. </p>\n",
"comments": [
{
"ContentLicense": "C... | {
"AcceptedAnswerId": "202204",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T19:51:18.420",
"Id": "202158",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"image"
],
"Title": "Converting colours in an image using Python Imaging Library"
} | 202158 |
<p>Let's say I have this pattern and a large array:</p>
<pre><code>String [] pattern = new String[]{"i","am","a", "pattern"};
String [] large_array = new String[]{"not","i","am","a", "pattern","pattern","i","am","a", "pattern", "whatever", "x", "y", i","am","a", "pattern",................, i","am","a", "pattern" ....};
</code></pre>
<p>As you can see the pattern appears multiple times in the array. The first time at index 1, the second time at index 6, etc... I want to find out at which positions the pattern begins and return it in a collection (eg list).</p>
<p>In this case the position array is
1,6,13, etc...</p>
<p>Here is my current method:</p>
<pre><code>private ArrayList<Integer> getStartPositionOfPattern(String[] headerArray, String[] pattern) {
ArrayList<Integer> allPositions = new ArrayList<>();
int idxP = 0, idxH = 0;
int startPos = 0;
while (idxH < headerArray.length) {
if (pattern.length == 1) {
if (pattern[0].equals(headerArray[idxH])) {
allPositions.add(idxH);
}
} else {
if (headerArray[idxH].equals(pattern[idxP])) {
idxP++;
if (idxP == pattern.length) { //you reached end of pattern
idxP = 0; //start Pattern from begining
allPositions.add(startPos); //you can save startPosition because pattern is finished
}
} else {
idxP = 0;
startPos = idxH + 1;
if (pattern[idxP].equals(headerArray[idxH])) { //if current arrray.idxH is not pattern.idxP but array.idxH is begining of pattern
startPos = idxH;
idxP++;
}
}
}
idxH++;
}
return allPositions;
}
</code></pre>
<p>Is there a way to make my function more readable and faster? I believe it works correctly, but because the function is complex, I worry I might have an undetected bug.</p>
<p>NOTE: <code>headerArray</code> is the large array.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T20:46:40.913",
"Id": "389450",
"Score": "3",
"body": "**Code not implemented or not working as intended**: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainabilit... | [
{
"body": "<h2>Naming</h2>\n<ol>\n<li>\n<blockquote>\n<p>NOTE: headerArray is the large array.</p>\n</blockquote>\n</li>\n</ol>\n<p>If you need to specify this to us, then your variable name isn't good. We should be able to understand your code with only your code because you wouldn't be beside us when we read ... | {
"AcceptedAnswerId": "202223",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T20:43:52.343",
"Id": "202160",
"Score": "2",
"Tags": [
"java",
"array",
"search"
],
"Title": "Check if specific pattern exists in another array and save the index"
} | 202160 |
<p>I needed an environment values loader for a random node project, and instead of just using dotenv, decided to just make one myself and see how it'll turn out.</p>
<p>To make this meaningful, here's a rough description of the task requirements:</p>
<pre><code>// make an .env file loader
// each line has the format key=value
// # starts a comment
// updates process.env and returns an object
// may only use native JS (ES5/6), no external dependencies
</code></pre>
<p>I've made two implementations:</p>
<p>Version 1:</p>
<pre><code>module.exports = function() {
var lines = require('fs').readFileSync('.env', 'utf8').split('\n');
var map = {};
for(var i = 0; i < lines.length; i++) {
var line = lines[i].split('#')[0];
var equalsIndex = line.indexOf('=');
if(equalsIndex != -1) {
var key = line.split(0, equalsIndex).trim();
var value = line.split(equalsIndex + 1).trim();
process.env[key] = value;
map[key] = value;
}
}
return map;
};
</code></pre>
<p>Version 2:</p>
<pre><code>'use strict';
// dependencies
const FileSystem = require('fs');
// static
const DEFAULT_FILE_PATH = '.env';
const DEFAUTL_TEXT_ENCODING = 'utf8';
const DEFAULT_RECORD_SEPARATOR = '\n';
const DEFAULT_VALUE_SEPARATOR = '=';
const DEFAULT_COMMENT_SYMBOL = '#';
const DEFAULT_EMPTY_VALUE_FLAG = null;
// interface
module.exports = envLoaderSync;
// implementation
/**
* synchronously loads values from a file into a returned object and into process.env
*
* @param {Object?} attr - options
* @param {string?} attr.filePath - default `.env`
* @param {string?} attr.textEncoding - default `utf8`
* @param {string?} attr.recordSeparator - default `\n`
* @param {string?} attr.valueSeparator - default `=`
* @param {string?} attr.commentSymbol - default `#`
* @param {any?} attr.emptyValueFlag - default `null`, returned value for empty value strings
* @param {boolean?} attr.toTryGuessingTypes - default false,
* if true, tries to JSON.parse, and returns the parsed value on success, else the raw string
* @param {boolean?} attr.toOverwriteProcessEnv = default true,
* whether to overwrite process.env keys
*
* @effects - adds/overwrite keys in process.env
* (only if toOverwriteProcessEnv === true)
*
* @return {Object.<{string, string|any}>} - map of values loaded
* (type is any if toTryGuessingTypes === true, else string)
*/
/* public */ function envLoaderSync(attr) {
// parameters
if(attr === undefined) {
attr = Object.create(null);
}
else if(!attr || typeof attr !== 'object' || Array.isArray(attr)) {
console.error('envLoaderSync: if you provide an attr argument, it must be an object');
throw Error('E_ATTR_NOT_OBJECT');
}
const filePath = getOptionalValue(attr, 'filePath', 'string', DEFAULT_FILE_PATH);
const textEncoding = getOptionalValue(attr, 'textEncoding', 'string', DEFAUTL_TEXT_ENCODING);
const recordSeparator = getOptionalValue(attr, 'recordSeparator', 'string', DEFAULT_RECORD_SEPARATOR);
const valueSeparator = getOptionalValue(attr, 'valueSeparator', 'string', DEFAULT_VALUE_SEPARATOR);
const commentSymbol = getOptionalValue(attr, 'commentSymbol', 'string', DEFAULT_COMMENT_SYMBOL);
const emptyValueFlag = getOptionalValue(attr, 'emptyValueFlag', null, DEFAULT_EMPTY_VALUE_FLAG);
const toTryGuessingTypes = getOptionalValue(attr, 'toTryGuessingTypes', 'boolean', false);
const toOverwriteProcessEnv = getOptionalValue(attr, 'toOverwriteProcessEnv', 'boolean', true);
// load file
let fileContent;
try {
fileContent = FileSystem.readFileSync(filePath, textEncoding);
}
catch(err) {
console.error('envLoaderSync:', err);
throw Error('E_UNABLE_TO_OPEN_FILE');
}
// create output data structure
const map = Object.create(null);
// parse file content
const records = fileContent.split(recordSeparator);
const recordsLength = records.length;
for(let i = 0; i < recordsLength; ++i) {
let record = records[i];
// ignore comment parts of records
const commentIndex = record.indexOf(commentSymbol);
if(commentIndex !== -1) {
record = record.slice(0, commentIndex);
}
// ignore records that have no value separator
const separatorIndex = record.indexOf(valueSeparator);
if(separatorIndex === -1) {
continue;
}
// store & update record as key-value pair
const key = record.slice(0, separatorIndex).trim();
let value = record.slice(separatorIndex + 1).trim();
if(key === '') {
continue; // empty key not allowed
}
if(value === '') {
value = emptyValueFlag; // empty values replaced with flag
}
else if(toTryGuessingTypes) {
try {
value = JSON.parse(value);
}
catch(err) {} // not an error; default to stay as original string
}
map[key] = value;
if(toOverwriteProcessEnv) {
process.env[key] = value;
}
}
return map;
}
/**
* returns a value from an object by key
* if missing in object, returns default value
* if asType provided and value doesn't match the type, throws error
*
* @param {Object} fromObject - the object to extract values from
* @param {string} asKey - the key to extract from the object
* @param {string?} asType - if provided, throws error on value type mismatch
* @param {any} defaultValue - returned if key not found
*
* @return {any} - value extracted from the object or default value
*/
/* private */ function getOptionalValue(fromObject, asKey, asType, defaultValue) {
if(asKey in fromObject) {
let value = fromObject[asKey];
if(asType === null || typeof value === asType) {
return value;
}
console.error('envLoaderSync: attr.' + asKey + ' must be of type ' + asType);
throw Error('E_INVALID_TYPE');
}
return defaultValue;
}
</code></pre>
<p>Which version would you consider to be better, what would you change about each, what can be improved upon in general?</p>
<p>If you needed an env loader for your project, what would you prefer?</p>
| [] | [
{
"body": "<p>Nice question! This is a great demonstration of opposing design aesthetics.</p>\n\n<p>I definitely prefer the first one. It is straightforward to read and does what it says. The story is clear. I'd prefer that the function didn't modify process.env directly as part of the loop (see <code>toOverwri... | {
"AcceptedAnswerId": "202183",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T22:31:10.887",
"Id": "202166",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"comparative-review",
"configuration"
],
"Title": "JS/Node.js .env loader"
} | 202166 |
<p>In order to learn Python and Curses programming I am in the process of creating a Battleship game for the console. At the moment I struggle more on object oriented programming and structuring the classes and methods rather that the implementations. </p>
<p>At the moment it contains:</p>
<ul>
<li>main.py The main file, the game should always be started: <code>$ python3 main.py</code></li>
<li>Board, ship, player classes (board.py ...)</li>
<li>Setships class which is the first stage of the game</li>
</ul>
<p>Now my problem is that I don't know how I can have multiple classes doing curses stuff if it requires the stdscr (<code>strstc = uc.initscr()</code>). Setships does too many things! In the future I want to have the init sutff seperated and, for instance, the close methode seperated, but I don't know how to structure it. It's easy to imagine oop at classes like Board, Player, Ship obviously but than it's more abstract. </p>
<p>The project is on github as well: <a href="https://github.com/horenso/SeaBattle/tree/9215e89d2c56a2362bbb6e9968ac84db3671ece2" rel="nofollow noreferrer">https://github.com/horenso/SeaBattle</a></p>
<p>The SetShip Class</p>
<pre><code>from player import Player
import unicurses as uc
from math import ceil
stdscr = uc.initscr()
class SetShips:
def __init__(self, player):
self.player = player
self.on_menu = True # Shifts the focus between menu and board, = show new ship
self.menu_hi = 0 # Which ele is hightlighted in the menu
self.menu_sel = -1 # Current item selected, relevant when board is active
self.num_ships_set = 0
self.menu = self.player.left_to_set()
self.new_ship_x = 0
self.new_ship_y = 0
self.new_ship_hor = True
self.str_title = f'Set ships for player: {self.player.name}'
self.max_y, self.max_x = uc.getmaxyx(stdscr)
uc.noecho() # Disable typing on the screen
uc.cbreak() # catching characters directly without waiting for [ENTER]
uc.curs_set(0) # Disable blinking curser
uc.keypad(stdscr, True) # for catching the arrow keys
uc.start_color()
self.init_colors()
self.init_wins()
def __del__(self):
uc.del_panel(self.pan_board)
uc.delwin(self.win_board)
uc.delwin(self.win_boardarea)
uc.delwin(self.win_shipmenu)
uc.delwin(self.win_statusbar)
uc.delwin(self.win_title)
def init_wins(self):
'''Creates win and panel objects. '''
uc.werase(stdscr)
self.max_y, self.max_x = uc.getmaxyx(stdscr)
border_x = ceil(self.max_x*2/3)
c = int(self.max_x % 2 == 1)
self.win_title = uc.newwin(3, self.max_x, 0, 0) #(h, w, starty, startx)
self.win_boardarea = uc.newwin(self.max_y-4, border_x, 3, 0)
self.win_shipmenu = uc.newwin(self.max_y-4, self.max_x-border_x, 3, border_x)
self.win_statusbar = uc.newwin(1, self.max_x, self.max_y-1, 0)
x, y = self.player.board.str_size()
self.win_board = uc.newwin(y, x+2, 0, 0)
self.pan_board = uc.new_panel(self.win_board)
uc.move_panel(self.pan_board, 3+(self.max_y-3)//2-y//2, (border_x-3)//2-x//2)
uc.wrefresh(stdscr)
self.draw()
def init_colors(self):
# Draw board
uc.init_pair(11, uc.COLOR_BLUE, uc.COLOR_BLACK)
uc.init_pair(12, uc.COLOR_WHITE, uc.COLOR_BLACK)
uc.init_pair(13, uc.COLOR_RED, uc.COLOR_BLACK)
# Status menu
uc.init_pair(4, uc.COLOR_WHITE, uc.COLOR_BLUE)
# close
uc.init_pair(1, uc.COLOR_WHITE, uc.COLOR_RED)
def draw_title(self):
uc.box(self.win_title, 0, 0)
uc.wmove(self.win_title, 1, 2)
uc.waddstr(self.win_title, self.str_title)
uc.wrefresh(self.win_title)
def draw_boardareaarea(self):
uc.werase(self.win_board)
uc.box(self.win_boardarea, 0, 0)
uc.wmove(self.win_boardarea, 1, 2)
if self.on_menu:
s = self.player.board.__str__()
else:
s = self.player.board.show_new_ship(self.new_ship_x, self.new_ship_y,
self.menu[self.menu_hi].id,
self.menu[self.menu_hi].length,
self.new_ship_hor)
for chr in s:
if chr == '~':
uc.wattron(self.win_board, uc.COLOR_PAIR(11))
uc.waddstr(self.win_board, chr)
uc.wattroff(self.win_board, uc.COLOR_PAIR(11))
elif chr == 'O':
uc.wattron(self.win_board, uc.COLOR_PAIR(12))
uc.waddstr(self.win_board, chr)
uc.wattroff(self.win_board, uc.COLOR_PAIR(12))
elif chr == '#':
uc.wattron(self.win_board, uc.COLOR_PAIR(13))
uc.waddstr(self.win_board, chr)
uc.wattroff(self.win_board, uc.COLOR_PAIR(13))
else:
uc.wattron(self.win_board, uc.COLOR_PAIR(12))
uc.waddstr(self.win_board, chr)
uc.wattroff(self.win_board, uc.COLOR_PAIR(12))
uc.wrefresh(self.win_boardarea)
uc.update_panels()
def draw_shipmenu(self):
uc.werase(self.win_shipmenu)
offset_x = 2
offset_y = 1
uc.box(self.win_shipmenu, 0, 0)
uc.wmove(self.win_shipmenu, offset_y, offset_x)
uc.waddstr(self.win_shipmenu, 'ship menu:')
offset_y += 2
for ele in self.menu:
if (self.on_menu and self.menu_hi == self.menu.index(ele)):
uc.wattron(self.win_shipmenu, uc.A_REVERSE)
uc.mvwaddstr(self.win_shipmenu, offset_y, offset_x, ele)
uc.wattroff(self.win_shipmenu, uc.A_REVERSE)
offset_y += 2
else:
uc.mvwaddstr(self.win_shipmenu, offset_y, offset_x, ele)
offset_y += 2
uc.wrefresh(self.win_shipmenu)
def draw_statusbar(self):
uc.werase(self.win_statusbar)
s = '[q] quit '
if self.on_menu:
s += '[\u2191\u2193] move '
s += '[\u21B5] select '
else:
s += '[\u2190\u2191\u2192\u2193] move '
s += '[r] rotate '
s += '[s] suggest '
s += '[\u21B5] commit '
s += f'{self.num_ships_set}/{len(self.player.ship_list)} set'
uc.waddstr(self.win_statusbar, s)
uc.wbkgd(self.win_statusbar, uc.COLOR_PAIR(4))
uc.wrefresh(self.win_statusbar)
def draw(self):
self.draw_boardareaarea()
self.draw_title()
self.draw_shipmenu()
self.draw_statusbar()
def input(self):
self.key = uc.wgetch(stdscr)
if self.key == uc.KEY_RESIZE:
self.max_y, self.max_x = uc.getmaxyx(stdscr)
if self.max_x > 10 and self.max_y > 10:
self.init_wins()
if(self.on_menu):
if(self.key == uc.KEY_UP):
self.menu_hi -= 1
if self.menu_hi == -1:
self.menu_hi = len(self.menu)-1
elif(self.key == uc.KEY_DOWN):
self.menu_hi += 1
if self.menu_hi >= len(self.menu):
self.menu_hi = 0
elif(self.key == ord('\n')):
for ship in self.player.ship_list:
if ship.id == self.menu[self.menu_hi].id:
ship.placed = True
self.new_ship_id = self.menu[self.menu_hi].id
self.new_ship_len = self.menu[self.menu_hi].length
self.new_ship_x = 0
self.new_ship_y = 0
self.new_ship_hor = True
self.on_menu = False
else:
if(self.key == uc.KEY_LEFT):
if self.new_ship_x - 1 >= 0:
self.new_ship_x -= 1
elif(self.key == uc.KEY_RIGHT):
if self.new_ship_hor:
if self.new_ship_x + self.menu[self.menu_hi].length < self.player.board.size:
self.new_ship_x += 1
else:
if self.new_ship_x + 1 < self.player.board.size:
self.new_ship_x += 1
elif(self.key == uc.KEY_UP):
if self.new_ship_y - 1 >= 0:
self.new_ship_y -= 1
elif(self.key == uc.KEY_DOWN):
if self.new_ship_hor:
if self.new_ship_y + 1 < self.player.board.size:
self.new_ship_y += 1
else:
if self.new_ship_y + self.menu[self.menu_hi].length < self.player.board.size:
self.new_ship_y += 1
elif(self.key == ord('r') or self.key == ord('R')):
if self.new_ship_hor:
if self.new_ship_y + self.menu[self.menu_hi].length > self.player.board.size:
self.new_ship_y = self.player.board.size - self.menu[self.menu_hi].length
else:
if self.new_ship_x + self.menu[self.menu_hi].length > self.player.board.size:
self.new_ship_x = self.player.board.size - self.menu[self.menu_hi].length
self.new_ship_hor = not self.new_ship_hor
elif(self.key == ord('s') or self.key == ord('S')):
s = self.player.board.suggest(self.menu[self.menu_hi].length)
if type(s) != bool:
x, y, h = s
self.new_ship_x = x
self.new_ship_y = y
self.new_ship_hor = h
elif(self.key == ord('\n')):
if self.player.board.check_new_ship(self.new_ship_x, self.new_ship_y,
self.menu[self.menu_hi].length,
self.new_ship_hor):
self.player.board.set_new_ship(self.new_ship_x, self.new_ship_y,
self.menu[self.menu_hi].id,
self.menu[self.menu_hi].length,
self.new_ship_hor)
self.num_ships_set += 1
if not self.all_set():
self.on_menu = True
self.menu = self.player.left_to_set()
self.menu_hi = 0
if self.key == ord('q') or self.key == ord('Q'):
self.close()
if self.key == ord('w') or self.key == ord('W'):
uc.endwin()
exit()
def all_set(self):
'''Returns ture if all ships are placed.'''
return self.num_ships_set == len(self.player.ship_list)
def close(self):
prompt_start_x = self.max_x//2-19
prompt_start_y = self.max_y//3
if prompt_start_x < 1:
prompt_start_x = 1
if prompt_start_y < 1:
prompt_start_y = 1
win_prompt = uc.newwin(3, 38, prompt_start_y, prompt_start_x)
uc.box(win_prompt, 0, 0)
uc.mvwaddstr(win_prompt, 1, 1, 'Do you want to close the game? (y|n)')
uc.wbkgd(win_prompt, uc.COLOR_PAIR(1))
uc.wrefresh(win_prompt)
answer = uc.wgetch(stdscr)
if answer == ord('y') or answer == ord('Y'):
uc.endwin()
exit()
else:
uc.delwin(win_prompt)
</code></pre>
<p>And the main:</p>
<pre><code>import unicurses as uc
stdscr = uc.initscr()
from setships import SetShips
from player import Player
p = Player('Bob', 10)
try:
s = SetShips(p)
while True:
s.input()
if s.all_set():
break
s.draw()
finally:
uc.endwin()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T23:55:24.427",
"Id": "389472",
"Score": "0",
"body": "Welcome to Code Review! 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 blo... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T22:33:59.310",
"Id": "202168",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"curses",
"battleship"
],
"Title": "Battleship game in python3 and the unicurses libary (oop)"
} | 202168 |
<p>Can the performance of the iterative approach be improved? I find that this approach lags behind many recursive options. no recursive answers, please. </p>
<p>Baseline recursive approach: takes 52 steps for this sized tree O(N) for every nested input each object is only touched once. </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 diameterOfBinaryTree(root) {
return diameterInternal(root).diameter;
};
function diameterInternal(root) {
if (root == null) {
return {
diameter: 0,
depth: 0
}
}
let left = diameterInternal(root.left);
let right = diameterInternal(root.right);
let diameter = left.depth + right.depth;
return {
diameter: Math.max(diameter, left.diameter, right.diameter),
depth: Math.max(left.depth, right.depth) + 1
};
}
let tree = {
"val": 3,
"right": {
"val": 20,
"right": {
"val": 7,
"right": null,
"left": null
},
"left": {
"val": 15,
"right": null,
"left": null
}
},
"left": {
"val": 9,
"right": null,
"left": null
}
}
console.log(diameterOfBinaryTree(tree))</code></pre>
</div>
</div>
</p>
<p>Iterative approach: takes 85 steps. However, the number of steps will double as the branches become more nested. That's because as you walk the nodes, they are walked in trios. Counting the roots while unpacking the right and left side. Culminating the counts on every retrograde unpacking, while passing every root object more than once. time complexity is O(N^2) for every nested object added it will be touched twice, once on entering and a second time on exiting. </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 diameterOfBinaryTree(root) {
let stack = [
[1, root]
];
let d = new WeakMap()
let diameter = 0;
while (stack.length) {
let [indicator, node] = [...stack.pop()];
if (indicator) {
let place = 0,
extend = [];
extend[place++] = [0, node]
if (node.right !== null) {
extend[place++] = [1, node.right]
}
if (node.left !== null) {
extend[place++] = [1, node.left]
}
stack.push.apply(stack, extend);
} else {
let left = d.get(node.left) + 1 || 0;
let right = d.get(node.right) + 1 || 0;
d.set(node, Math.max(left, right))
diameter = Math.max(diameter, left + right);
}
}
return diameter;
}
let tree = {
"val": 3,
"right": {
"val": 20,
"right": {
"val": 7,
"right": null,
"left": null
},
"left": {
"val": 15,
"right": null,
"left": null
}
},
"left": {
"val": 9,
"right": null,
"left": null
}
}
console.log(diameterOfBinaryTree(tree))</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T05:05:35.873",
"Id": "389479",
"Score": "0",
"body": "\"Lags behind in many recursive options\" in what way? Algorithmic complexity (what is the complexity of your implementation?)? Benchmarked runtime (can you demonstrate?)? Which ... | [
{
"body": "<h1>Tail calls</h1>\n<p>You have to be careful when evaluating recursive functions as there is a big difference between recursion that is tail called, and those that are not.</p>\n<p>As the problem requires a traverse back up the tree after locating an end node the tail of the recursive function shou... | {
"AcceptedAnswerId": "202366",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T00:31:29.100",
"Id": "202171",
"Score": "0",
"Tags": [
"javascript",
"performance",
"algorithm",
"stack",
"complexity"
],
"Title": "Iteratively determine the diameter of a binary tree"
} | 202171 |
<p>I wrote a function, <code>read_fox_rcu()</code> for getting an element from RCU-protected list in a linux device driver. <code>read_fox_rcu()</code> reads the first element, converts it to string , stores it to <code>tmp</code> and stores the first pointer to <code>ppfox</code>.</p>
<p>I wonder that I used locks (<code>rcu_read_lock()</code>, <code>synchronize_rcu()</code>, etc), in an appropriate way.</p>
<pre><code>static int read_fox_rcu(struct fox ** ppfox, char *tmp, size_t size){
struct fox *f;
rcu_read_lock();
f = list_first_or_null_rcu(&fox_list_rcu, struct fox, list);
if (f==NULL) {
rcu_read_unlock();
return -1;
}
snprintf(tmp, size, "%lu/%lu/%d\t",
f->tail_length, f->weight, f->is_fantastic);
*ppfox = f;
rcu_read_unlock();
return 0;
}
#define MAX_BUF_SIZE 1024
static ssize_t show_pop_fox_r(struct device *dev, struct device_attribute *attr, char *buf)
{
int ret;
struct fox * f;
char tmp[MAX_BUF_SIZE];
if (read_fox_rcu(&f, tmp, MAX_BUF_SIZE)) {
ret = scnprintf(buf, PAGE_SIZE, "failure on read_fox_rcu()\n");
return ret;
}
list_del_rcu(&f->list);
synchronize_rcu();
kfree(f);
ret = scnprintf(buf, PAGE_SIZE, "%s\n", tmp);
return ret;
}
static DEVICE_ATTR(pop_fox_r, S_IRUGO, show_pop_fox_r, NULL);
</code></pre>
<p><code>dev_attr_pop_fox_r.attr</code> is declared by <code>DEVICE_ATTR</code>. And <code>pop_fox_r</code> is created, by calling <code>sysfs_create_group()</code> in the probe function.</p>
<p><code>fox_list_rcu</code> and <code>struct fox</code> is defined like below.</p>
<pre><code>struct fox {
size_t tail_length;
size_t weight;
bool is_fantastic;
struct list_head list;
};
static LIST_HEAD(fox_list_rcu);
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T01:23:00.823",
"Id": "202172",
"Score": "2",
"Tags": [
"c",
"kernel"
],
"Title": "Getting an element from RCU-protected list in kernel"
} | 202172 |
<p>I did an initial technical phone screening with this company which went ok, they then sent me a programming exercise to complete and send back to them.</p>
<hr>
<p><b>The goal of the exercise:</b></p>
<p>-take input as a command line arguments (2017-06-03 USD 100 CAD)</p>
<p>-use the input to make a call to an API (<a href="https://api.exchangeratesapi.io" rel="nofollow noreferrer">https://api.exchangeratesapi.io</a> to get exchange rate USD,$100)</p>
<p>-print the output as a JSON object //will be USD $100 -> CAD $x</p>
<p>-complete some specified unit tests and integration tests</p>
<p>-use a linter to validate the JS is clean</p>
<hr>
<p>The program is able to take in arguments, call the API, get back the data, compute the data, and print the correct data.</p>
<p>So I am suspecting that I may not be following "best practices" for development in node.js.</p>
<p>If anyone can look through the code and let me know of any red flags, such as outdated JS stuff, improper methodologies, or just anything bad you can see that would be very helpful!!! </p>
<p><a href="https://github.com/mkbru/CiteRightChallenge" rel="nofollow noreferrer">https://github.com/mkbru/CiteRightChallenge</a></p>
<p>app.js</p>
<pre><code>const errorChecks = require("./utils/errorChecks");
const getExchangeRate = require("./utils/getExchangeRate");
const args = process.argv;
const date = args[2];
const bCurrency = args[3];
const bAmount = parseInt(args[4]);
const cCurrency = args[5];
//user input validation
errorChecks(process.argv);
getExchangeRate(date, bCurrency, bAmount, cCurrency).then(output =>{
console.log(output);
});
</code></pre>
<p>errorchecks.js</p>
<pre><code>const isCurrency = require('./isCurrency')
function errorChecks(args){
const date = args[2];
const bCurrency = args[3];
const bAmount = parseInt(args[4]);
const cCurrency = args[5];
if(args.length != 6){
console.log("Usage Error: Incorrect amount of arguments");
process.exit(1);
}
if(!(/^\d{4}[\-.]\d{1,2}[\-.]\d{1,2}$/.test(date))){
console.log("Usage Error: "+ date +" is not a date");
process.exit(1);
}
isCurrency(bCurrency).then(output => {
if(!output) {
console.log("Usage Error: " + cCurrency + " is not a currency.");
process.exit(1);
}
});
if(isNaN(bAmount)){
console.log("Usage Error: " + bAmount + " is not a number.");
process.exit(1);
}
isCurrency(cCurrency).then(output => {
if(!output){
console.log("Usage Error: " + cCurrency + " is not a currency.");
process.exit(1);
}
});
}
module.exports = errorChecks;
</code></pre>
<p>getExchangeRate.js</p>
<pre><code>const request = require('request-promise');
function getExchangeRate(date, bCurrency, bAmount, cCurrency){
const options = {
method: 'GET',
uri: 'https://api.exchangeratesapi.io/'+date+'?base='+bCurrency,
json: true
}
return request(options).
then(function (response){
exRate = response.rates[cCurrency]
cAmount = (exRate) * bAmount; //conversion rate * base amount
const output = {
date: date,
base_currency: bCurrency,
base_amount: bAmount,
conversion_currency: cCurrency,
conversion_amount: Math.round(cAmount * 100) / 100
}
return output;
}).
catch(function (err){
console.log(err)
})
}
module.exports = getExchangeRate;
</code></pre>
<p>getCurrencies.js</p>
<pre><code>const request = require('request-promise');
function getCurrencies(){
const options = {
method: 'GET',
uri: 'https://api.exchangeratesapi.io/latest',
json: true
}
return request(options).
then(function (response){
let currencies = [];
for(let k in response.rates) currencies.push(k);
return currencies;
}).
catch(function (err){
console.log(err)
})
}
module.exports = getCurrencies;
</code></pre>
<p>isCurrency.js</p>
<pre><code>const request = require('request-promise');
const getCurrencies = require('./getCurrencies')
function isCurrency(currency){
return getCurrencies().then(currencies => {
let isCurrency = currencies.includes(currency);
return isCurrency;
});
}
module.exports = isCurrency;
</code></pre>
<p>index.test.js </p>
<pre><code>const chai = require("chai");
const chaiHttp = require("chai-http");
const expect = require("chai").expect;
const getExchangeRate = require("../utils/getExchangeRate");
chai.use(chaiHttp);
describe("First test", () => {
it("Should assert true to be true", () => {
expect(true).to.be.true;
});
});
describe("Test if API is running",() =>{
it("Should assert to true", (done) => {
chai.request("https://api.exchangeratesapi.io")
.get('/latest')
.end((err,res) => {
expect(res).to.have.status(200);
done();
});
});
});
describe("getExchangeRate()_unit-test-1", () =>{
it("should assert true if obj1 === obj2", (done) => {
const date = "2011-06-03";
const base_currency = "USD";
const base_amount = 100;
const conversion_currency = "CAD";
const obj1 = {
date: "2011-06-03",
base_currency: "USD",
base_amount: 100,
conversion_currency: "CAD",
conversion_amount: 97.85,
};
getExchangeRate(date,base_currency,base_amount,conversion_currency).
then(obj2 => {
expect(obj1).to.eql(obj2);
done();
}).
catch(error => {
done(error);
});
});
});
describe("getExchangeRate()_unit-test-2", () =>{
it("should assert true if obj1 === obj2", (done) => {
const date = "2007-07-12";
const base_currency = "GBP";
const base_amount = 303;
const conversion_currency = "SEK";
const obj1 = {
date: "2007-07-12",
base_currency: "GBP",
base_amount: 303,
conversion_currency: "SEK",
conversion_amount: 4085.015
};
getExchangeRate(date,base_currency,base_amount,conversion_currency).
then(obj2 => {
expect(obj1).to.eql(obj2);
done();
}).
catch(error => {
done(error);
});
});
});
describe("getExchangeRate()_unit-test-3", () =>{
it("should assert true if obj1 === obj2", (done) => {
const date = "2004-08-07";
const base_currency = "EUR";
const base_amount = 5;
const conversion_currency = "PLN";
const obj1 = {
date: "2004-08-07",
base_currency: "EUR",
base_amount: 5,
conversion_currency: "PLN",
conversion_amount: 22.01,
};
getExchangeRate(date,base_currency,base_amount,conversion_currency).
then(obj2 => {
expect(obj1).to.eql(obj2);
done();
}).
catch(error => {
done(error);
});
});
});
describe("getExchangeRate()_unit-test-4", () =>{
it("should assert true if obj1 === obj2", (done) => {
const date = "2017-02-09";
const base_currency = "ZAR";
const base_amount = 132;
const conversion_currency = "TRY";
const obj1 = {
date: "2017-02-09",
base_currency: "ZAR",
base_amount: 132,
conversion_currency: "TRY",
conversion_amount: 36.3528,
};
getExchangeRate(date,base_currency,base_amount,conversion_currency).
then(obj2 => {
expect(obj1).to.eql(obj2);
done();
}).
catch(error => {
done(error);
});
});
});
</code></pre>
| [] | [
{
"body": "<p>Here's 5 things I noticed right away:</p>\n\n<ol>\n<li><p><code>errorChecks(process.argv)</code> is probably best before you try to parse the arguments. Some of that parsing is going to fail before getting to your nice error messages.</p></li>\n<li><p>Edit your tests-- remove boilerplate ones and ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T01:41:42.377",
"Id": "202173",
"Score": "0",
"Tags": [
"javascript",
"parsing",
"node.js",
"interview-questions",
"api"
],
"Title": "Nodejs Interview - API calls and exchange rate"
} | 202173 |
<p>I recently solved <a href="https://leetcode.com/problems/max-area-of-island/description/" rel="nofollow noreferrer">the problem below from leetcode</a>:</p>
<blockquote>
<p>Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical). Find the maximum area of an island in the given 2D array.</p>
</blockquote>
<p>This is how I normally write python code. I am thinking this might not be really Pythonic. Please help review the code.</p>
<pre><code>from operator import add
def max_area_of_island(grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rlen = len(grid)
clen = len(grid[0])
visited = [[0] * clen for _ in range(rlen)]
max_island = 0
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def add_dir(cur_loc, d):
cur_i, cur_j = cur_loc
new_i, new_j = tuple(map(add, cur_loc, d))
if new_i >= 0 and new_i < rlen and new_j >= 0 and new_j < clen:
#print("all good")
return new_i, new_j
#print("error")
return -1, -1
max_area = 0
for i in range(rlen):
for j in range(clen):
if grid[i][j] == 0 or visited[i][j]:
continue
area = 1
q = [(i,j)]
visited[i][j] = True
#print("before qsize", q.qsize())
while q:
#print("during qsize", q.qsize())
cur = q.pop()
for _,d in enumerate(dirs):
new_i, new_j = add_dir(cur, d)
if new_i < 0 or visited[new_i][new_j]: continue
if new_i >= 0 and grid[new_i][new_j]:
new_loc = (new_i, new_j)
q.append(new_loc)
visited[new_i][new_j] = True
area += 1
max_area = max(area, max_area)
return max_area
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T05:20:02.120",
"Id": "389480",
"Score": "0",
"body": "Assuming the question has the same input format, you may also find some useful information in this question about a similar question on leetcode: https://codereview.stackexchange... | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Nested functions are unusual; typically they would be neighbour functions instead. This ensures that all the context that each function needs is passed to it, making it easier to grasp the entire context involved in the processing in each function.</li>\n<li><p>P... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T02:25:24.973",
"Id": "202175",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"breadth-first-search"
],
"Title": "Find maximum area of island in matrix"
} | 202175 |
<p>The data file is <a href="https://drive.google.com/open?id=0B6u0ktUDM9nGc3ZNTXVZN2kwRVB4VFM4amVmc2ppZjE4aWlr" rel="nofollow noreferrer">here</a>.</p>
<p>Here are my codes:</p>
<pre><code>> ftable=read.table(file.choose())
> start.time=Sys.time()
> 1-length(which(ftable==1))/sum(ftable)
[1] 0.12
> end.time=Sys.time()
> end.time-start.time
Time difference of 0.004880905 secs
</code></pre>
<p>I understand that 0.00488 secs are not a lot. But I have to repeatedly do this calculation over different and larger tables. I am wondering if the function '<code>which</code>' can be replaced by a more efficient one.</p>
<p>Thanks in advance!</p>
<p>Note: This piece of codes is to calculate the percentage of singletons in ftable. If there is a more efficient way, please let me know. Thank you!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T08:24:14.963",
"Id": "389505",
"Score": "0",
"body": "Is dividing by `sum(df)` really what you want to calculate the \"percentage of singletons\"? Or do you rather need something along the lines of `prop.table(table(unlist(df, use.n... | [
{
"body": "<p>Try:</p>\n\n<pre><code>1-sum(ftable==1L)/sum(ftable)\n</code></pre>\n\n<p>Test on larger data:</p>\n\n<pre><code>n <- 1000000\nset.seed(21)\nftable <- data.frame(replicate(3, sample.int(4, n, replace = T))-1L)\n\nstart.time=Sys.time()\n1-length(which(ftable==1))/sum(ftable)\nend.time=Sys.tim... | {
"AcceptedAnswerId": "202186",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T03:12:33.193",
"Id": "202177",
"Score": "0",
"Tags": [
"performance",
"r"
],
"Title": "Is there a more efficient way of doing function 'which' in R?"
} | 202177 |
<p><strong>Problem statement</strong><br><br>
Construct a binary expression using infix expression. The infix expression uses extra parenthesis to enforce the priority of operators.</p>
<p>For example, infix expression <code>((1+2)+3)</code> can be expressed in a binary expression tree in the following:
<br>
+ <br>
/ \ <br>
+ 3 <br>
/ \ <br>
1 2 <br></p>
<p>Write down your assumptions in your code. Sometimes comment is also helpful for people to evaluate how good you are in terms of problem solving skills. </p>
<p><strong>My introduction</strong></p>
<p>It is very good algorithm to learn to use stack to parse the expression, even though it is not straightforward. In order to get optimal time complexity, linear time by scanning the infix expression once, using data structure stack. </p>
<p>The challenge is to write a solution in less than 30 minutes, and also show good design of object-oriented programming. </p>
<p>The infix expression is enforced to use extra open and close parenthesis. For example, <code>(1 + 2)</code> should be valid expression and then char <code>'('</code> defines the start of a new expression. One idea is to linear scan the expression, push <code>'('</code> into stack, and then <code>'1'</code> into stack, and then <code>'+'</code> into stack, <code>'2'</code> into stack, and then once <code>')'</code> is visited, then pop up stack for 2 operands one operator and one <code>'('</code> char to construct a binary tree using operator as the root. </p>
<p>Here is my C# code, please help me to review my solution. </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace infixExpressionToBinaryExpressionTree
{
class Program
{
internal class Node
{
public char Operand { get; set; } // operator sometimes;
public Node Left;
public Node Right;
public Node(char val)
{
Operand = val;
}
}
static void Main(string[] args)
{
//RunTestcase1();
RunTestcase2();
}
public static void RunTestcase1()
{
var node = InfixExpressionToBinaryExpressionTree("(1+2)");
Debug.Assert(node.Operand == '+');
}
public static void RunTestcase2()
{
var node = InfixExpressionToBinaryExpressionTree("((1+2)*(3-4))");
Debug.Assert(node.Operand.CompareTo("*") == 0);
}
public static string Operators = "+-*/";
public static string Operands = "0123456789"; // make it simple, one digit only first
/// <summary>
/// Time complexity: O(N), space complexity: using stack -> at most O(N)
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static Node InfixExpressionToBinaryExpressionTree(string expression)
{
if (expression == null || expression.Length == 0)
return null;
var stack = new Stack<Object>();
for (int i = 0; i < expression.Length; i++)
{
var current = expression[i];
var isCloseBracket = current == ')';
if (!isCloseBracket)
{
stack.Push(current);
}
else
{
if (stack.Count < 4)
return null;
var operand2 = stack.Pop();
var operatorChar = stack.Pop();
var operand1 = stack.Pop();
var openBracket = (char)stack.Pop();
if (openBracket != '(' ||
!checkOperand(operand2) ||
!checkOperand(operand1) ||
!checkOperator(operatorChar)
)
{
return null;
}
var root = new Node((char)operatorChar);
root.Left = (operand1.GetType() == typeof(Node)) ? (Node)operand1 : new Node((char)operand1);
root.Right = (operand2.GetType() == typeof(Node)) ? (Node)operand2 : new Node((char)operand2);
stack.Push(root);
}
}
if (stack.Count > 1 || stack.Count == 0)
return null;
return (Node)stack.Pop();
}
/// <summary>
/// code review July 6, 2018
/// </summary>
/// <param name="operand"></param>
/// <returns></returns>
private static bool checkOperand(Object operand)
{
if (operand.GetType() == typeof(Node))
return true;
var number = (char)operand;
return Operands.IndexOf(number) != -1;
}
private static bool checkOperator(Object operatorChar)
{
var arithmetic = (char)operatorChar;
return Operators.IndexOf(arithmetic) != -1;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T15:15:30.433",
"Id": "389841",
"Score": "1",
"body": "This fails to parse inputs like `1`, `(1)`, `1+2`, `( 1 + 2 )`, `(1+2+3)`, `(12+34)`, and so on. What exactly is the purpose of this exercise?"
},
{
"ContentLicense": "CC... | [
{
"body": "<h2>OOP</h2>\n<ol>\n<li><p>Let's start with : <code>private static bool checkOperator(Object operatorChar)</code>. You shouldn't use <code>Object</code> if you expect a <code>char</code>. If you want a <code>char</code> , demand a <code>char</code>. Also, <code>checkOperator</code> doesn't really mea... | {
"AcceptedAnswerId": "202227",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T05:20:33.393",
"Id": "202181",
"Score": "5",
"Tags": [
"c#",
"algorithm",
"programming-challenge",
"parsing",
"math-expression-eval"
],
"Title": "Use Infix expression to construct a binary expression tree"
} | 202181 |
<p>I'm making a full-blown OOP Battleship game in VBA <a href="https://codereview.stackexchange.com/q/202101/23788">(previous post: Battleship Grid)</a>, and I want this code to be as good as it gets - and better, if I can.</p>
<p>I've refactored a few things, introduced a <code>ShipType</code> enum, removed all globals, and finished implementing my second AI.. time for another post!</p>
<p>I hadn't presented the <strong>Ship</strong> class yet, so first, here is the <strong>IShip</strong> interface:</p>
<pre><code>'@Folder("Battleship.Model.Ship")
'@Interface
Option Explicit
Public Enum ShipType
Carrier
Battleship
Submarine
Cruiser
Destroyer
End Enum
Public Enum ShipOrientation
Horizontal
Vertical
End Enum
'@Description("Gets the type of the ship.")
Public Property Get ShipKind() As ShipType
End Property
'@Description("The name/description of the ship. Must be unique in a grid.")
Public Property Get Name() As String
End Property
'@Description("Use in 'With' blocks to get a reference to the scope variable.")
Public Property Get GridPosition() As GridCoord
End Property
'@Description("The number of grid squares (1-5) occupied by this ship.")
Public Property Get Size() As Byte
End Property
'@Description("The orientation of the ship.")
Public Property Get Orientation() As ShipOrientation
End Property
'@Description("True if this ship is sunken.")
Public Property Get IsSunken() As Boolean
End Property
'@Description("Gets all grid coordinates this ship was hit at.")
Public Property Get HitArea() As Collection
End Property
'@Description("Gets an array containing the state of each grid coordinate of the ship.")
Public Property Get StateArray() As Variant
End Property
'@Description("If the specified coordinate hits this ship, marks coordinate as a hit and returns True.")
Public Function Hit(ByVal coord As GridCoord) As Boolean
End Function
'@Description("Returns intersection coordinate if specified ship intersects with this instance.")
Public Function Intersects(ByVal shipSize As Byte, ByVal direction As ShipOrientation, ByVal position As GridCoord) As GridCoord
End Function
</code></pre>
<p>The interface is implemented by the <strong>Ship</strong> class, where I have moved a number of items that were previously in a <strong>Globals</strong> module - that module is now gone, and the <em>default instance</em> of the <strong>Ship</strong> class serves as a factory that also knows about all the ship types in the game, with their respective names and sizes.</p>
<pre><code>'@Folder("Battleship.Model.Ship")
Option Explicit
Private Const MinimumShipSize As Byte = 2
Private Const MaximumShipSize As Byte = 5
Private ShipSizes As Scripting.Dictionary
Private ShipNames As Scripting.Dictionary
Private Const ShipNameCarrier As String = "Aircraft Carrier"
Private Const ShipNameBattleship As String = "Battleship"
Private Const ShipNameSubmarine As String = "Submarine"
Private Const ShipNameCruiser As String = "Cruiser"
Private Const ShipNameDestroyer As String = "Destroyer"
Private Type TShip
ShipKind As ShipType
Name As String
GridPosition As GridCoord
Orientation As ShipOrientation
State As Scripting.Dictionary
IsHit As Boolean
End Type
Private this As TShip
Implements IShip
'@Description("Gets a dictionary associating all ship names with their respective size.")
Public Property Get Fleet() As Scripting.Dictionary
Dim names As Variant
names = ShipNames.Items
Dim sizes As Variant
sizes = ShipSizes.Items
Dim result As Scripting.Dictionary
Set result = New Scripting.Dictionary
Dim i As Long
For i = LBound(names) To UBound(names)
result.Add names(i), sizes(i)
Next
Set Fleet = result
End Property
'@Description("Gets an array of all valid ShipKind enum values.")
Public Property Get ShipKinds() As Variant
ShipKinds = ShipNames.Keys
End Property
'@Description("The minimum valid ship size. Invoke from the default instance.")
Public Property Get MinimumSize() As Byte
MinimumSize = MinimumShipSize
End Property
'@Description("The maximum valid ship size. Invoke from the default instance.")
Public Property Get MaximumSize() As Byte
MaximumSize = MaximumShipSize
End Property
'@Description("Use from the class' default instance to create a new ship instance using parameters.")
Public Function Create(ByVal kind As ShipType, ByVal direction As ShipOrientation, ByVal position As GridCoord) As Ship
ValidateInputs kind, direction, position
With New Ship
.ShipKind = kind
.Name = ShipNames(kind)
.Orientation = direction
Set .GridPosition = position
Dim Offset As Byte
For Offset = 0 To ShipSizes(kind) - 1
Dim currentPoint As GridCoord
Set currentPoint = New GridCoord
currentPoint.X = position.X + IIf(direction = Horizontal, Offset, 0)
currentPoint.Y = position.Y + IIf(direction = Vertical, Offset, 0)
' each element is a Boolean, keyed with a grid coordinate:
.State.Add item:=False, Key:=currentPoint.ToString
Next
Set Create = .Self
End With
End Function
Private Sub ValidateInputs(ByVal kind As ShipType, ByVal Orientation As ShipOrientation, ByVal position As GridCoord)
Dim shipSize As Byte
shipSize = ShipSizes(kind)
Select Case True
Case Orientation <> Horizontal And Orientation <> Vertical
OnInvalidArgument "orientation", "Invalid orientation."
Case Orientation = Horizontal And position.X + shipSize - 1 > PlayerGrid.Size
OnInvalidArgument "position", "Invalid position; ship exceeds right edge of the grid."
Case Orientation = Vertical And position.Y + shipSize - 1 > PlayerGrid.Size
OnInvalidArgument "position", "Invalid position; ship exceeds bottom edge of the grid."
End Select
End Sub
Private Sub OnInvalidArgument(ByVal argName As String, ByVal message As String)
Err.Raise 5, TypeName(Me), message
End Sub
Public Property Get Self() As Ship
Set Self = Me
End Property
Public Property Get ShipKind() As ShipType
ShipKind = this.ShipKind
End Property
Public Property Let ShipKind(ByVal value As ShipType)
this.ShipKind = value
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Orientation() As ShipOrientation
Orientation = this.Orientation
End Property
Public Property Let Orientation(ByVal value As ShipOrientation)
this.Orientation = value
End Property
Public Property Get GridPosition() As GridCoord
Set GridPosition = this.GridPosition
End Property
Public Property Set GridPosition(ByVal value As GridCoord)
Set this.GridPosition = value
End Property
Public Property Get State() As Scripting.Dictionary
Set State = this.State
End Property
Private Sub Class_Initialize()
If Me Is Ship Then
'default instance
Set ShipSizes = New Scripting.Dictionary
With ShipSizes
.Add ShipType.Carrier, 5
.Add ShipType.Battleship, 4
.Add ShipType.Submarine, 3
.Add ShipType.Cruiser, 3
.Add ShipType.Destroyer, 2
End With
Set ShipNames = New Scripting.Dictionary
With ShipNames
.Add ShipType.Carrier, ShipNameCarrier
.Add ShipType.Battleship, ShipNameBattleship
.Add ShipType.Submarine, ShipNameSubmarine
.Add ShipType.Cruiser, ShipNameCruiser
.Add ShipType.Destroyer, ShipNameDestroyer
End With
Else
Set this.State = New Scripting.Dictionary
End If
End Sub
Private Sub Class_Terminate()
Set ShipSizes = Nothing
Set ShipNames = Nothing
Set this.State = Nothing
End Sub
Private Property Get IShip_GridPosition() As GridCoord
Set IShip_GridPosition = this.GridPosition
End Property
Private Function IShip_Hit(ByVal coord As GridCoord) As Boolean
Dim coordString As String
coordString = coord.ToString
If this.State.Exists(coordString) Then
'this.State.Remove coordString
this.State(coordString) = True
this.IsHit = True
IShip_Hit = this.State(coordString)
End If
End Function
Private Function IShip_Intersects(ByVal shipSize As Byte, ByVal direction As ShipOrientation, ByVal position As GridCoord) As GridCoord
Dim gridOffset As Long
For gridOffset = 0 To shipSize - 1
Dim current As GridCoord
Set current = position.Offset( _
IIf(direction = Horizontal, gridOffset, 0), _
IIf(direction = Vertical, gridOffset, 0))
If this.State.Exists(current.ToString) Then
Set IShip_Intersects = current
Exit Function
End If
Next
End Function
Private Property Get IShip_HitArea() As VBA.Collection
Dim result As VBA.Collection
Set result = New VBA.Collection
Dim currentPoint As Variant
For Each currentPoint In this.State.Keys
If this.State(currentPoint) Then
result.Add GridCoord.FromString(currentPoint)
End If
Next
Set IShip_HitArea = result
End Property
Private Property Get IShip_IsSunken() As Boolean
If Not this.IsHit Then Exit Property
Dim currentPoint As Variant
For Each currentPoint In this.State.Items
If Not currentPoint Then Exit Property
Next
IShip_IsSunken = True
End Property
Private Property Get IShip_Name() As String
IShip_Name = this.Name
End Property
Private Property Get IShip_Orientation() As ShipOrientation
IShip_Orientation = this.Orientation
End Property
Private Property Get IShip_ShipKind() As ShipType
IShip_ShipKind = this.ShipKind
End Property
Private Property Get IShip_Size() As Byte
IShip_Size = this.State.Count
End Property
Private Property Get IShip_StateArray() As Variant
IShip_StateArray = this.State.Items
End Property
</code></pre>
<p>The <strong>PlayerGrid.FindHitArea</strong> method calls into this parameterless <code>IShip.HitArea</code>, which returns a collection of grid positions that belong to a given ship - but only the previous hits: the AI is responsible for doing whatever it wants to do with this information, and it doesn't need to "remember" its "last hit position" to do it.</p>
<p>In my game an <strong>IPlayer</strong> can be either <code>HumanControlled</code> or <code>ComputerControlled</code>. Here's the interface:</p>
<pre><code>'@Folder("Battleship.Model.Player")
Option Explicit
Public Enum PlayerType
HumanControlled
ComputerControlled
End Enum
'@Description("Gets the player's grid/state.")
Public Property Get PlayGrid() As PlayerGrid
End Property
'@Description("Identifies the player class implementation.")
Public Property Get PlayerType() As PlayerType
End Property
'@Description("Attempts to make a hit on the enemy grid.")
Public Function Play(ByVal enemyGrid As PlayerGrid) As GridCoord
End Function
'@Description("Places specified ship on game grid.")
Public Sub PlaceShip(ByVal currentShip As IShip)
End Sub
</code></pre>
<p>The <strong>HumanPlayer</strong> class is rather uninteresting (<code>PlaceShip</code> and <code>Play</code> implementations are no-op / empty). The <strong>AIPlayer</strong> class (which <em>also</em> has a <em>default instance</em> - I hope this is becoming quite an apparent pattern by now), on the other hand, gets injected with an <strong>IGameStrategy</strong>:</p>
<pre><code>'@Folder("Battleship.Model.Player")
Option Explicit
Implements IPlayer
Private Type TPlayer
GridIndex As Byte
PlayerType As PlayerType
PlayGrid As PlayerGrid
Strategy As IGameStrategy
End Type
Private this As TPlayer
Public Function Create(ByVal grid As Byte, ByVal gameStrategy As IGameStrategy) As AIPlayer
With New AIPlayer
.PlayerType = ComputerControlled
.GridIndex = grid
Set .Strategy = gameStrategy
Set .PlayGrid = PlayerGrid.Create(grid)
Set Create = .Self
End With
End Function
Public Property Get Self() As AIPlayer
Set Self = Me
End Property
Public Property Get Strategy() As IGameStrategy
Set Strategy = this.Strategy
End Property
Public Property Set Strategy(ByVal value As IGameStrategy)
Set this.Strategy = value
End Property
Public Property Get PlayGrid() As PlayerGrid
Set PlayGrid = this.PlayGrid
End Property
Public Property Set PlayGrid(ByVal value As PlayerGrid)
Set this.PlayGrid = value
End Property
Public Property Get GridIndex() As Byte
GridIndex = this.GridIndex
End Property
Public Property Let GridIndex(ByVal value As Byte)
this.GridIndex = value
End Property
Public Property Get PlayerType() As PlayerType
PlayerType = this.PlayerType
End Property
Public Property Let PlayerType(ByVal value As PlayerType)
this.PlayerType = value
End Property
Private Property Get IPlayer_PlayGrid() As PlayerGrid
Set IPlayer_PlayGrid = this.PlayGrid
End Property
Private Sub IPlayer_PlaceShip(ByVal currentShip As IShip)
this.Strategy.PlaceShip this.PlayGrid, currentShip
End Sub
Private Function IPlayer_Play(ByVal enemyGrid As PlayerGrid) As GridCoord
Set IPlayer_Play = this.Strategy.Play(enemyGrid)
End Function
Private Property Get IPlayer_PlayerType() As PlayerType
IPlayer_PlayerType = this.PlayerType
End Property
</code></pre>
<p>A <em>game strategy</em> is defined as follows:</p>
<pre><code>'@Folder("Battleship.AI")
'@Interface
Option Explicit
Public Enum AIDifficulty
Unspecified
RandomAI
FairplayAI
MercilessAI
End Enum
'@Description("Places the specified ship on the specified grid.")
Public Sub PlaceShip(ByVal grid As PlayerGrid, ByVal currentShip As IShip)
End Sub
'@Description("Gets the grid coordinate to attack on the specified enemy grid.")
Public Function Play(ByVal enemyGrid As PlayerGrid) As GridCoord
End Function
</code></pre>
<p>Now I plan to implement 3 of these. At this point I have a <strong>RandomShotStrategy</strong> that places its ships completely randomly and shoots anywhere, regardless of the grid state:</p>
<pre><code>'@Folder("Battleship.AI")
' dumbest possible AI game strategy: randomly places ships, randomly shoots
Option Explicit
Implements IGameStrategy
Private Type TStrategy
RNG As IRandomizer
End Type
Private this As TStrategy
Public Function Create(ByVal randomizer As IRandomizer) As IGameStrategy
With New RandomShotStrategy
Set .RNG = randomizer
Set Create = .Self
End With
End Function
Public Property Get Self() As RandomShotStrategy
Set Self = Me
End Property
Public Property Get RNG() As IRandomizer
Set RNG = this.RNG
End Property
Public Property Set RNG(ByVal value As IRandomizer)
Set this.RNG = value
End Property
Private Sub IGameStrategy_PlaceShip(ByVal grid As PlayerGrid, ByVal currentShip As IShip)
Do
Dim gridX As Long
gridX = this.RNG.Between(1, PlayerGrid.Size)
Dim direction As ShipOrientation
If gridX + currentShip.Size - 1 > PlayerGrid.Size Then
direction = Vertical
Else
direction = IIf(this.RNG.NextSingle < 0.5, Horizontal, Vertical)
End If
Dim gridY As Long
If direction = Horizontal Then
gridY = this.RNG.Between(1, PlayerGrid.Size)
Else
gridY = this.RNG.Between(1, PlayerGrid.Size - currentShip.Size)
End If
Dim position As GridCoord
Set position = GridCoord.Create(gridX, gridY)
Loop Until grid.CanAddShip(position, direction, currentShip.Size)
grid.AddShip Ship.Create(currentShip.ShipKind, direction, position)
If grid.ShipCount = PlayerGrid.ShipsPerGrid Then grid.Scramble
End Sub
Private Function IGameStrategy_Play(ByVal enemyGrid As PlayerGrid) As GridCoord
Do
Dim position As GridCoord
Set position = GridCoord.Create( _
xPosition:=this.RNG.Between(1, PlayerGrid.Size), _
yPosition:=this.RNG.Between(1, PlayerGrid.Size))
Loop Until enemyGrid.State(position) <> PreviousHit And _
enemyGrid.State(position) <> PreviousMiss
Set IGameStrategy_Play = position
End Function
</code></pre>
<p>Here's the <strong>FairPlayStrategy</strong>, which now cares to avoid placing ships adjacent to each other, shoots randomly until it hits something - then proceeds to destroy that target:</p>
<pre><code>'@Folder("Battleship.AI")
Option Explicit
Implements IGameStrategy
Private Type TStrategy
RNG As IRandomizer
End Type
Private this As TStrategy
Public Function Create(ByVal randomizer As IRandomizer) As IGameStrategy
With New FairPlayStrategy
Set .RNG = randomizer
Set Create = .Self
End With
End Function
Public Property Get Self() As FairPlayStrategy
Set Self = Me
End Property
Public Property Get RNG() As IRandomizer
Set RNG = this.RNG
End Property
Public Property Set RNG(ByVal value As IRandomizer)
Set this.RNG = value
End Property
Private Sub IGameStrategy_PlaceShip(ByVal grid As PlayerGrid, ByVal currentShip As IShip)
Do
Dim gridX As Long
gridX = this.RNG.Between(1, PlayerGrid.Size)
Dim direction As ShipOrientation
If gridX + currentShip.Size - 1 > PlayerGrid.Size Then
direction = Vertical
Else
direction = IIf(this.RNG.NextSingle < 0.5, Horizontal, Vertical)
End If
Dim gridY As Long
If direction = Horizontal Then
gridY = this.RNG.Between(1, PlayerGrid.Size)
Else
gridY = this.RNG.Between(1, PlayerGrid.Size - currentShip.Size)
End If
Dim position As GridCoord
Set position = GridCoord.Create(gridX, gridY)
DoEvents
Loop Until grid.CanAddShip(position, direction, currentShip.Size) And _
Not grid.HasAdjacentShip(position, direction, currentShip.Size)
grid.AddShip Ship.Create(currentShip.ShipKind, direction, position)
If grid.ShipCount = PlayerGrid.ShipsPerGrid Then grid.Scramble
End Sub
Private Function IGameStrategy_Play(ByVal enemyGrid As PlayerGrid) As GridCoord
Dim result As GridCoord
Do
Dim area As Collection
Set area = enemyGrid.FindHitArea
If Not area Is Nothing Then
Dim inferredDirection As ShipOrientation
inferredDirection = TryInferDirection(area)
If inferredDirection = Horizontal Then
If this.RNG.NextSingle < 0.5 Then
Set result = FindLeftMostHit(area).Offset(xOffset:=-1)
If result.X = 1 Or enemyGrid.State(result) = PreviousMiss Then
Set result = FindRightMostHit(area).Offset(xOffset:=1)
End If
Else
Set result = FindRightMostHit(area).Offset(xOffset:=1)
If result.X = PlayerGrid.Size Or enemyGrid.State(result) = PreviousMiss Then
Set result = FindLeftMostHit(area).Offset(xOffset:=-1)
End If
End If
Else
If this.RNG.NextSingle < 0.5 Then
Set result = FindTopMostHit(area).Offset(yOffset:=-1)
If result.Y = 1 Or enemyGrid.State(result) = PreviousMiss Then
Set result = FindBottomMostHit(area).Offset(yOffset:=1)
End If
Else
Set result = FindBottomMostHit(area).Offset(yOffset:=1)
If result.Y = PlayerGrid.Size Or enemyGrid.State(result) = PreviousMiss Then
Set result = FindTopMostHit(area).Offset(yOffset:=-1)
End If
End If
End If
Else
'no hit area: just shoot *somewhere*
Set result = ShootRandom
End If
Loop Until result.X >= 1 And result.X <= PlayerGrid.Size And _
result.Y >= 1 And result.Y <= PlayerGrid.Size And _
enemyGrid.State(result) <> PreviousHit And _
enemyGrid.State(result) <> PreviousMiss
Set IGameStrategy_Play = result
Exit Function
End Function
Private Function ShootRandom() As GridCoord
Set ShootRandom = GridCoord.Create( _
xPosition:=this.RNG.Between(1, PlayerGrid.Size), _
yPosition:=this.RNG.Between(1, PlayerGrid.Size))
End Function
Private Function TryInferDirection(ByVal area As Collection) As ShipOrientation
Dim previousPosition As GridCoord
Dim currentPosition As GridCoord
For Each currentPosition In area
If previousPosition Is Nothing Then
Set previousPosition = currentPosition
'could be either (ignoring remaining enemy ships)
TryInferDirection = IIf(this.RNG.NextSingle < 0.5, Horizontal, Vertical)
Else
If currentPosition.Y = previousPosition.Y Then
TryInferDirection = Horizontal
Else
TryInferDirection = Vertical
End If
End If
Next
End Function
Private Function FindLeftMostHit(ByVal area As Collection) As GridCoord
Dim leftMost As GridCoord
Set leftMost = area(1)
Dim current As GridCoord
For Each current In area
If current.X < leftMost.X Then Set leftMost = current
Next
Set FindLeftMostHit = leftMost
End Function
Private Function FindRightMostHit(ByVal area As Collection) As GridCoord
Dim rightMost As GridCoord
Set rightMost = area(1)
Dim current As GridCoord
For Each current In area
If current.X > rightMost.X Then Set rightMost = current
Next
Set FindRightMostHit = rightMost
End Function
Private Function FindTopMostHit(ByVal area As Collection) As GridCoord
Dim topMost As GridCoord
Set topMost = area(1)
Dim current As GridCoord
For Each current In area
If current.Y < topMost.Y Then Set topMost = current
Next
Set FindTopMostHit = topMost
End Function
Private Function FindBottomMostHit(ByVal area As Collection) As GridCoord
Dim bottomMost As GridCoord
Set bottomMost = area(1)
Dim current As GridCoord
For Each current In area
If current.Y > bottomMost.Y Then Set bottomMost = current
Next
Set FindBottomMostHit = bottomMost
End Function
</code></pre>
<p><a href="https://www.dropbox.com/s/xiksgkb68ivypea/AI-vs-AI%20%28FairPlay%29.mp4?dl=0" rel="noreferrer">Here's two of them playing against each other</a>. Now, I'm going to be implementing a <strong>MercilessStrategy</strong> that will no longer shoot completely randomly without a target - it will be taking into account the available empty spots, vs what enemy ships remain to sink.</p>
<p>But I will likely need to reuse much of the code of the <strong>FairPlayStrategy</strong> (even that one duplicates the random shot code), so I'm thinking to extract a utility class and <em>compose</em> my AI strategies - or is there a better solution? In .NET I'd probably make an abstract <code>GameStrategyBase</code> class, shove all the base methods in there, and derive the strategies from it.</p>
<p>Anything sticks out? Again, <em>please be picky!</em></p>
<p><img src="https://i.stack.imgur.com/j6RoY.png" alt="RandomShotStrategy vs FairPlayStrategy - FairPlay wins"></p>
<p><sup>RandomShotStrategy vs FairPlayStrategy - guess which AI is in which grid!</sup></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T06:04:02.977",
"Id": "389486",
"Score": "0",
"body": "`grid` is a byte, not a byte array? That's a little confusing given everything is a \"grid\", I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-0... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T05:34:52.450",
"Id": "202184",
"Score": "14",
"Tags": [
"object-oriented",
"vba",
"ai",
"battleship"
],
"Title": "BattleShip - Ships & Players"
} | 202184 |
<p>In <a href="http://www.codeabbey.com/index/task_view/yacht-or-dice-poker" rel="noreferrer">Dice Poker (or Yacht)</a>, a player rolls 5 standard dice (sides 1 - 6) and the resulting roll is given a score based on combinations:</p>
<ul>
<li>Two matching dice only - pair</li>
<li>Three matching dice only - three</li>
<li>Four matching dice only - four</li>
<li>Five matching dice - yacht</li>
<li>two pairs, full house, small straight, large straight, you get the idea</li>
</ul>
<p>A player rolls the dice and the input is in a space-delimited format e.g.</p>
<pre><code>3 6 5 6 1 - pair
1 6 6 1 6 - full-house
2 4 3 5 1 - small-straight
</code></pre>
<p>I'm reading these results from column A on Sheet1 (we'll say). I'm not convinced I'm checking the hands for results very effectively. It works, but it seems incoherent.</p>
<hr>
<p>First I have an <code>Enum</code> of the results as well as a function for getting the name of the result -</p>
<pre><code>Option Explicit
Private Enum Combination
none
pair
three
four
Yacht
twopair
fullhouse
smallstraight
bigstraight
End Enum
Private Function GetEnum(ByVal value As Combination) As String
Select Case value
Case 0
GetEnum = "none"
Case 1
GetEnum = "pair"
Case 2
GetEnum = "three"
Case 3
GetEnum = "four"
Case 4
GetEnum = "yacht"
Case 5
GetEnum = "two-pairs"
Case 6
GetEnum = "full-house"
Case 7
GetEnum = "small-straight"
Case 8
GetEnum = "big-straight"
End Select
End Function
</code></pre>
<p>The meat of it is here:</p>
<pre><code>Sub YachtHands()
Dim lastRow As Long
Dim dice As Variant
lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
Dim index As Long
Dim result As String
For index = 1 To lastRow
dice = Split(Sheet1.Cells(index, 1), " ")
result = result & EvaluateHand(dice)
Next
Debug.Print Trim$(result)
End Sub
Private Function EvaluateHand(ByVal dice As Variant) As String
Dim score As Combination
Dim bucket() As Long
Dim threeFlag As Boolean
Dim twoFlag As Boolean
ReDim bucket(1 To 6)
Dim i As Long
For i = LBound(dice) To UBound(dice)
bucket(dice(i)) = bucket(dice(i)) + 1
Next
For i = LBound(bucket) To UBound(bucket)
If bucket(i) > 3 Then
score = bucket(i) - 1
GoTo Eval
End If
If bucket(i) = 3 Then
If twoFlag Then
score = fullhouse
GoTo Eval
Else
threeFlag = True
End If
End If
If bucket(i) = 2 Then
If threeFlag Then
score = fullhouse
GoTo Eval
ElseIf twoFlag Then
score = twopair
GoTo Eval
Else
twoFlag = True
End If
End If
Next
If threeFlag Then
score = three
GoTo Eval
End If
If twoFlag Then
score = pair
GoTo Eval
End If
score = CheckStraight(bucket)
Eval:
EvaluateHand = GetEnum(score) & " "
End Function
Private Function CheckStraight(ByVal bucket As Variant) As Combination
If bucket(1) = 1 And bucket(2) = 1 And bucket(3) = 1 And bucket(4) = 1 And bucket(5) = 1 Then CheckStraight = smallstraight
If bucket(2) = 1 And bucket(3) = 1 And bucket(4) = 1 And bucket(5) = 1 And bucket(6) = 1 Then CheckStraight = bigstraight
End Function
</code></pre>
<p>I think my straight checking function is sort of ridiculous. My main evaluation also uses a lot of <code>GoTo</code> which in general should be avoided. It also suffers some arrow-code. I think this all stems from whatever algorithm I'm using.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T20:35:20.907",
"Id": "389670",
"Score": "0",
"body": "Don't have time for an answer at the moment - but the one thing that jumped out at me is the `Select` and enum combination. An Enum is effectively a `Long`, so you can assign val... | [
{
"body": "<p>Some general notes:</p>\n\n<ul>\n<li><code>GetEnum</code> function:</li>\n</ul>\n\n<blockquote>\n<pre><code>Select Case value\n Case 0\n GetEnum = \"none\"\n</code></pre>\n</blockquote>\n\n<p>This kind of hard-coding of values is very risky, if you change the enumeration your fun... | {
"AcceptedAnswerId": "202224",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T07:08:44.637",
"Id": "202189",
"Score": "7",
"Tags": [
"vba",
"dice"
],
"Title": "Evaluating Dice Poker results"
} | 202189 |
<p>For Job shop scheduling, I built a fitness function:</p>
<pre><code>def makespan_timeCalculation(lot_size, RHS, setup_time, processing_time, sequence, mc_op):
machine_assigne_time =[[0 for i in range(mc_op[k])] for k in range(len(mc_op))]
max_c = [0 for i in range(len(lot_size))] # Equal number of job
completion_time = [0 for i in range(len(RHS))]
# Check all indices of RHS (Step 2 + 3 + 6)
for r in range(len(RHS)):
procTime = run_time(r, lot_size, RHS, sequence, processing_time) + setup_time[RHS[r][2]]
if lot_size[RHS[r][0]][RHS[r][1]] > 0: # Lot size not zero (Step 4)
if (machine_assigne_time[RHS[r][2]][RHS[r][3]] == 0 and RHS[r][2] == sequence[RHS[r][0]][0]):
# Step 5.1: First assignment to machine m and operation equal first operation in sequence
completion_time[r] = setup_time[RHS[r][2]] + procTime
machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1
elif (machine_assigne_time[RHS[r][2]][RHS[r][3]] == 0 and RHS[r][2] != sequence[RHS[r][0]][0]):
# Step 5.2: First assignment to machine m and operation over first operation in sequence
curent_sequence_index = sequence[RHS[r][0]].index(RHS[r][2]) # Calculate index sequence of current chromosome
prev_sequence = sequence[RHS[r][0]][curent_sequence_index-1] # Return previous sequence operation of current chromosome
prev_operation_comp_index = [i[0:3] for i in RHS].index([RHS[r][0], RHS[r][1], prev_sequence]) # Return previous chromosome of current job + sublot
completion_time[r] = max(setup_time[RHS[r][2]], completion_time[prev_operation_comp_index]) + procTime
machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1
#print(curent_sequence_index, RHS[r])
elif (machine_assigne_time[RHS[r][2]][RHS[r][3]] > 0 and RHS[r][2] == sequence[RHS[r][0]][0]):
# Step 5.3: First operation in sequence and machine m assignment > 1 (dung de xem xet khi co su khac nhau giua setup time ban dau, va setup time doi part)
prev_op_mc_RHS_index = max([i for i, al in enumerate(RHS[:r]) if RHS[r][2:] == al[2:]])
completion_time[r] = completion_time[prev_op_mc_RHS_index] + procTime
machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1
elif (machine_assigne_time[RHS[r][2]][RHS[r][3]] > 0 and RHS[r][2] != sequence[RHS[r][0]][0]):
# Step 5.4 Operation over first operation in sequence and machine m assignment > 1
curent_sequence_index = sequence[RHS[r][0]].index(RHS[r][2]) # Calculate index sequence of current chromosome
prev_sequence = sequence[RHS[r][0]][curent_sequence_index-1] # Return previous sequence operation of current chromosome
prev_operation_comp_index = [i[0:3] for i in RHS].index([RHS[r][0], RHS[r][1], prev_sequence]) # Return previous chromosome of current job + sublot
prev_op_mc_RHS_index = max([i for i, al in enumerate(RHS[:r]) if RHS[r][2:] == al[2:]])
completion_time[r] = max(completion_time[prev_operation_comp_index], completion_time[prev_op_mc_RHS_index]) + procTime
machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1
max_c[RHS[r][0]] = max(max_c[RHS[r][0]], completion_time[r])
return max(max_c)
</code></pre>
<p>The result is fine but speed is very slow. Could you help to have a look and advise on improvement?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T09:20:24.357",
"Id": "389515",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ... | [
{
"body": "<p>I think the biggest boost to readability will come from giving things proper names. You currently have a lot of <code>RHS[r][i]</code> going on, with <code>i = 0, 1, 2, 3</code>. For someone who does not know what these things are (including possibly you in a few months), this makes the code basic... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T07:15:12.667",
"Id": "202190",
"Score": "2",
"Tags": [
"python",
"performance",
"genetic-algorithm"
],
"Title": "Genetic algorithm fitness function for scheduling"
} | 202190 |
<p>I come more from a frontend background and have been reading up on more backend approaches and algorithms while solving a TicTacToe grid to see if there are any wins normally, I'd probably use something like this</p>
<pre><code>for (let i = 0; i < rows; i++) {
if (arr[i][0] === arr[i][1] && arr[i][0] === arr[i][2]) {
</code></pre>
<p>but with what I've been studying, I thought it'd be better to use a map and iterate through them instead</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>'use strict';
const board = [
['x','x','x'],
['x','o','o'],
['x','x','x']
]
const matches = [
[1,4,7],
[2,5,8],
[3,6,9],
[1,2,3],
[4,5,6],
[7,8,9],
[1,5,9],
[3,5,7]
]
const solver = (board, matches) => {
// build map
let counter = 1;
const map = {};
// convert array to object
for (let row of board) {
for (let char of row) {
map[counter] = char;
counter++;
}
}
for (let match of matches) {
// create a new array with the values
const arr = [...map[match[0]],map[match[1]],map[match[2]]];
// check for duplicates
const arr2 = [...new Set(arr)].join("");
// console log if length is 1
if (arr2.length === 1) console.log(`match found at set: ${match}`)
}
}
solver(board, matches)</code></pre>
</div>
</div>
</p>
<p>Is this efficient? Is there a better way of doing this?</p>
<p>It looks a lot cleaner than</p>
<pre><code>if (arr[i][0] === arr[i][1] && arr[i][0] === arr[i][2])
</code></pre>
<p>for sure, but then again, that itself could have probably been designed more efficiently.</p>
<p>Is there a better way to generate the coordinates dynamically?</p>
| [] | [
{
"body": "<h1>Use loops</h1>\n<p>The game setup is not really conducive to optimization. Tic Tac Toe does not require a board, only each player's moves matter, which makes the game logic much simpler.</p>\n<h2>Your code</h2>\n<p>Anyways to your code.</p>\n<p>Don't be shy of using standard loops to solve proble... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T07:24:00.643",
"Id": "202191",
"Score": "2",
"Tags": [
"javascript",
"tic-tac-toe"
],
"Title": "TicTacToe solver in JavaScript"
} | 202191 |
<p>So I'm working on my website which is done though 3dcart, in their infinite wisdom for some reason I cannot work on anything to do with the backend (no database interactions or anything), so this is all front end stuff. And it's all cobbled together over a few days of trying to make things work correctly.</p>
<p>So this code basically just grabs the shopping cart information, and then puts this in a pdf format using jsPDF. It also goes through 7,000 products in a csv file, using regex to compare the names of the products in the cart to the csv file, if it matches it then takes the product code from the csv file and then uses this. The code also adds 4 images to the pdf all of which have to be base64 type images.</p>
<p>Getting the date part of the code</p>
<pre><code>//Set up the months and days so we can get a better date format
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
min = "0" + min;
}
var ampm = "am";
if (hr > 12) {
hr -= 12;
ampm = "pm";
}
var date = d.getDate();
var month = months[d.getMonth()];
var year = d.getFullYear();
//Concat the hell out of the date to format when the quote was generated
var newdat = "Quote generated" + ":" + day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
</code></pre>
<p>Go and get the shopping cart, and compare the names to a csv file part the code.</p>
<pre><code> $(document).on('click', '#submit1', function() {
//Storing html elements into variables
const itemToStore = document.getElementsByClassName("itemName");
const itemQty = document.getElementsByClassName("quoteQty");
const itemPrices = document.getElementsByClassName("quotePrice");
const itemTotal = document.getElementsByClassName("quoteTotal");
const totalCost = "Total Cost" + ":" + document.getElementById("quoteTotalCost").innerText;
const listOfCodes = []; //Array to store item codes
$.ajax({ //Ajax request, getting CSV file
type: "GET",
url: "assets/exports/pipeNew2.csv",
dataType: "text",
success: function(data) {
const listOfItems = []; //array to store itemNames from html for looping
const names = document.getElementsByClassName("itemName");
//Go through returned element, replace the , and " in text and the push to array
for (z = 0; z < names.length; z++) {
listOfItems.push(names[z].innerText.replace(/,/g, '').replace(/"/g, '').replace(/\//g, '').replace(/\s/g, ''));
}
// Remove \n and split by , (for csv)
var listPipe = data.split('\r\n').map(function(row) {
return row.replace(/"/g, '').replace(/\//g, '').replace(/\s/g, '').split(',');
});
//For loops to loop through item and pipe array, and compare
for (y = 0; y < itemToStore.length; y++) {
// Array of arrays like be generated
for (var i = 0; i < listPipe.length; i++) {
//if the item[y] matches pipe[i] then get the first elemenet in the pipe array and push it to a code array
if ($.inArray(listOfItems[y], listPipe[i]) !== -1) {
console.log('matched with: ' + '' + listOfItems[y] + '' + listPipe[i])
listOfCodes.push(listPipe[i][0]);
}
}
}
}
}).then(function() { //promises, so to wait for ajax to do its thing
//Store the column names to be used in pdf
const columns = ["Name", "Qty", "Price", "Item total", "Item Code"];
//Store rows in an array so we can add the innerHTML
const rows = [];
for (var k = 0; k < itemToStore.length; k++) {
rows.push([itemToStore[k].innerText, itemQty[k].value, itemPrices[k].innerHTML, itemTotal[k].innerHTML, listOfCodes[k]]);
};
// Only pt supported (not mm or in)
const doc = new jsPDF('p', 'pt');
const totalPagesExp = "{total_pages_count_string}";
//jsPDF does not like anything other than base64 imgs, i hate the length of this
const base64Img = //massive amount of chars
const iso = //massive amount of chars
const wras = //massive amount of chars
const living = //massive amount of chars
//Contact us string
const test = "" // info omitted here for privacy
//VAT number
const businessText = "" //info omitted here for privacy
const valid = 'Quote Valid for 30 days.';
doc.addImage(base64Img, 'JPEG', 20, 10, 200, 47);
doc.addImage(iso, 'JPEG', 20, 780, 60, 30)
doc.addImage(bsra, 'JPEG', 200, 780, 60, 30)
doc.addImage(wras, 'JPEG', 340, 780, 60, 30)
doc.addImage(living, 'JPEG', 480, 780, 60, 30)
//Adding the columns and rows to the table
doc.autoTable(columns, rows, {
margin: {
top: 100
}
});
doc.setFontSize(13);
doc.text(test, 240, 30);
//total cost
doc.text(totalCost, 20, 660);
//Date generated
doc.text(20, 680, newdat);
doc.text(20, 700, valid)
doc.setLineWidth(1.5);
doc.line(560, 720, 40, 720);
doc.setFontSize(10);
doc.text(240, 740, businessText);
doc.setLineWidth(1.5);
doc.line(560, 760, 40, 760);
doc.save('ShopQuote.pdf');
});
});
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T07:38:35.000",
"Id": "202192",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Shopping cart to pdf generator"
} | 202192 |
<p><a href="https://en.wikipedia.org/wiki/Kademlia" rel="nofollow noreferrer">Kademlia</a> is a DHT (distributed hash table) which uses a specific type of routing table, dependent on the Hamming distance between the "addresses" of two peers on the network. I'm attempting to implement a modified version of it in Java. To find which "bucket" in the routing table a peer should go into, I xor the peer's address with my client's address and try to find the index of the first true bit in the result. So far I've been using this code:</p>
<pre><code> private int findBucket(byte[] address) {
byte[] xorresult = xor(nodeAddress, address);
for (int i = 0; i < 20; i++) {
int temp = toBinaryString(xorresult[i]).indexOf('1');
if (temp != -1) {
return (i * 8) + temp;
}
}
return -1;
}
private static String toBinaryString(byte n) {
StringBuilder sb = new StringBuilder("00000000");
for (int bit = 0; bit < 8; bit++) {
if (((n >> bit) & 1) > 0) {
sb.setCharAt(7 - bit, '1');
}
}
return sb.toString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T12:53:26.230",
"Id": "389559",
"Score": "0",
"body": "Why not use the java.util.BitSet? It has build in xor(), nextSetBit() and conversion from/to byte[]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-... | [
{
"body": "<p>Java has some useful functions to search for set bits in the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html\" rel=\"nofollow noreferrer\">Integer</a> class, including <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#numberOfLeadingZeros(int)\" ... | {
"AcceptedAnswerId": "202230",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T08:32:50.337",
"Id": "202195",
"Score": "0",
"Tags": [
"java",
"bitwise"
],
"Title": "Kademlia bucketing"
} | 202195 |
<p>Here's the flow,</p>
<ul>
<li>Load XML file</li>
<li>Deserialize to list in c#</li>
<li>Map xml object to c# list</li>
<li><p>Merge orders but increment order's product count</p>
<pre><code>public Order[] Load(string path)
{
var element = XElement.Load(path);
var orders = new List<XElement>();
orders = element.Elements();
var _orders = new List<Order>();
var _alreadyAddedOrders = new List<string>();
foreach (var order in orders)
{
var orderTemp = new Order();
orderTemp.OrderDate = Convert.ToInt32(order.Attribute("date").ToString());
orderTemp.Id = Convert.ToInt32(order.Attribute("id").ToString());
orderTemp.CategoryId = Convert.ToInt32(order.Attribute("categoryId").ToString());
orderTemp.ProductCount = Convert.ToInt32(order.Attribute("productCount").ToString());
foreach (var secondOrder in _orders)
{
var orderMatches = (orderTemp.OrderDate == secondOrder.OrderDate &&
orderTemp.Id == secondOrder.Id &&
orderTemp.CategoryId == secondOrder.CategoryId);
if (orderMatches)
{
orderTemp.ProductCount += secondOrder.ProductCount;
_alreadyAddedOrders.Add(secondOrder.OrderDate.ToString() + secondOrder.Id.ToString() + secondOrder.CategoryId.ToString());
}
}
if(!_alreadyAddedOrders.Contains(orderTemp.OrderDate.ToString() + orderTemp.Id.ToString() + orderTemp.CategoryId.ToString()))
_orders.Add(orderTemp);
}
return _orders.ToArray();
}
public class Order
{
public int Id;
public int CategoryId;
public int OrderDate;
public int ProductCount;
}
</code></pre></li>
</ul>
<p>and XML is like this, more then 20,000 rows,</p>
<pre><code><orders>
<order date='2000-04-20' Id='1' categoryId='100' productCount='3' />
<order date='2000-06-21' Id='2' categoryId='101' productCount='14' />
</orders>
</code></pre>
<p>Note : Order ID is not unique, date + id + category, is unique altogether</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T14:22:06.107",
"Id": "389592",
"Score": "0",
"body": "@Mathematics: This code is still not working. All the `Convert`-statements are invalid and the conversion of the date should be to `DateTime`. Please make sure, that you post tes... | [
{
"body": "<h2>Naming</h2>\n<pre><code>var orders = new List<XElement>();\nvar _orders = new List<Order>();\n</code></pre>\n<p>First, according to the C# naming convention, you should never have underscores in your variable names declared inside methods. Second, this is pretty confusing.</p>\n<p>How... | {
"AcceptedAnswerId": "202276",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T09:20:40.567",
"Id": "202199",
"Score": "1",
"Tags": [
"c#",
"xml"
],
"Title": "Deserialize, Copy and Merge Orders from XML to C#"
} | 202199 |
<p>The idea here is to keep a small number of "fingers" that point to linked list <strong>nodes</strong>. Now, when, say, the client programmer asks for a node in the list, a closest finger is chosen and is shifted to the target node. Analogously, when adding an element, a closest finger is moved to it. Finally, when removing an element, a closest finger is moved to some of removed node's sibling. </p>
<p>Pictorially:</p>
<p><a href="https://i.stack.imgur.com/kEOxr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kEOxr.png" alt="FingerList fingering"></a></p>
<p>The demo driver and the unit tests may be found <a href="https://github.com/coderodde/FingerList" rel="nofollow noreferrer">here</a>.</p>
<pre><code>package net.coderodde.util.experimental;
import java.util.Objects;
/**
* This class implements an experimental linked list data structure that
* maintains a small set of so called fingers that are just references to the
* linked list nodes.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 18, 2018)
*/
public final class FingerList<T> {
/**
* This static inner class defines a node in the linked list.
*
* @param <T> the element type.
*/
private static final class FingerListNode<T> {
private T element;
private FingerListNode<T> previousNode;
private FingerListNode<T> nextNode;
FingerListNode(T element) {
this.element = element;
}
// Used for debugging.
@Override
public String toString() {
return "[" + Objects.toString(element) + "]";
}
}
/**
* This static inner class defines a finger to a node.
*
* @param <T> the element type.
*/
private static final class Finger<T> {
private FingerListNode<T> node;
private int index;
// Used for debugging.
@Override
public String toString() {
return "[" + index + ", " + Objects.toString(node.element) + "]";
}
}
private FingerListNode<T> headNode;
private FingerListNode<T> tailNode;
private Finger<T>[] fingers;
private int size;
public FingerList(int numberOfFingers) {
numberOfFingers = Math.max(1, numberOfFingers);
this.fingers = new Finger[numberOfFingers];
for (int i = 0; i < numberOfFingers; i++) {
this.fingers[i] = new Finger<>();
}
}
public FingerList() {
this(3);
}
public void add(int index, T element) {
checkAddIndex(index);
if (size == 0) {
// Empty list. Just add the node and set all the fingers point to
// it:
headNode = new FingerListNode(element);
tailNode = headNode;
size = 1;
// Set all the fingers to point to the only node:
for (Finger<T> finger : fingers) {
finger.index = 0;
finger.node = headNode;
}
} else if (size == index) {
// Append the input element. Here, this list is not empty so that
// the tail node exists:
FingerListNode<T> nodeToAdd = new FingerListNode<>(element);
tailNode.nextNode = nodeToAdd;
nodeToAdd.previousNode = tailNode;
tailNode = nodeToAdd;
// Find the closest finger:
int shortestFingerDistance = Integer.MAX_VALUE;
Finger<T> closestFinger = null;
for (Finger<T> finger : fingers) {
int fingerDistance = Math.abs(index - finger.index);
if (shortestFingerDistance > fingerDistance) {
shortestFingerDistance = fingerDistance;
closestFinger = finger;
}
}
closestFinger.index = size;
closestFinger.node = tailNode;
size++;
} else {
// The element to add will have both a previous and a next nodes:
FingerListNode<T> nodeToAdd = new FingerListNode<>(element);
int shortestFingerDistance = Integer.MAX_VALUE;
Finger<T> closestFinger = null;
for (Finger<T> finger : fingers) {
int fingerDistance = Math.abs(index - finger.index);
if (shortestFingerDistance > fingerDistance) {
shortestFingerDistance = fingerDistance;
closestFinger = finger;
}
}
// Closest finger found. Now move it to point to the node in front
// of which we will insert the new node:
if (index <= closestFinger.index) {
closestFinger.index -= shortestFingerDistance;
while (shortestFingerDistance > 0) {
shortestFingerDistance--;
closestFinger.node = closestFinger.node.previousNode;
}
} else {
closestFinger.index += shortestFingerDistance;
while (shortestFingerDistance > 0) {
shortestFingerDistance--;
closestFinger.node = closestFinger.node.nextNode;
}
}
// Insert the new node:
if (closestFinger.index == 0) {
// Set as the head node:
nodeToAdd.nextNode = headNode;
headNode.previousNode = nodeToAdd;
headNode = nodeToAdd;
} else {
// Insert a new node before closestFinger.node:
nodeToAdd.nextNode = closestFinger.node;
nodeToAdd.previousNode = closestFinger.node.previousNode;
closestFinger.node.previousNode.nextNode = nodeToAdd;
closestFinger.node.previousNode = nodeToAdd;
closestFinger.index = index;
}
// Because the new node shifts all the fingers on its right side
// one position to the right, update the relevant finger indices:
for (Finger<T> finger : fingers) {
if (finger.index >= index) {
finger.index++;
}
}
size++;
}
}
public T get(int index) {
checkAccessIndex(index);
// Find the closest finger:
int bestFingerDistance = Integer.MAX_VALUE;
Finger<T> bestFinger = null;
for (Finger<T> finger : fingers) {
int currentDistance = Math.abs(finger.index - index);
if (bestFingerDistance > currentDistance) {
bestFingerDistance = currentDistance;
bestFinger = finger;
}
}
FingerListNode<T> node = bestFinger.node;
// Update the closest finger by moving it to the target node:
if (index < bestFinger.index) {
bestFinger.index -= bestFingerDistance;
while (bestFingerDistance > 0) {
bestFingerDistance--;
node = node.previousNode;
}
bestFinger.node = node;
} else {
bestFinger.index += bestFingerDistance;
while (bestFingerDistance > 0) {
bestFingerDistance--;
node = node.nextNode;
}
bestFinger.node = node;
}
return node.element;
}
public void remove(int index) {
checkAccessIndex(index);
int bestFingerDistance = Integer.MAX_VALUE;
Finger<T> bestFinger = null;
// Find the closest finger:
for (Finger<T> finger : fingers) {
int currentDistance = Math.abs(finger.index - index);
if (bestFingerDistance > currentDistance) {
bestFingerDistance = currentDistance;
bestFinger = finger;
}
}
FingerListNode<T> removedNode = bestFinger.node;
// Move the closest finger to the node being removed:
if (index < bestFinger.index) {
bestFinger.index -= bestFingerDistance;
while (bestFingerDistance > 0) {
bestFingerDistance--;
removedNode = removedNode.previousNode;
}
} else {
bestFinger.index += bestFingerDistance;
while (bestFingerDistance > 0) {
bestFingerDistance--;
removedNode = removedNode.nextNode;
}
}
// Remove the node:
if (size == 1) {
headNode = null;
tailNode = null;
// Set all node references so that the garbage collector can claim
// them:
for (Finger<T> finger : fingers) {
finger.node = null;
}
} else if (removedNode.previousNode == null) {
// Once here, removedNode is the head node.
for (Finger<T> finger : fingers) {
if (finger.index > 0) {
finger.index--;
} else if (finger.node == removedNode) {
finger.node = finger.node.nextNode;
}
}
// Update the head node:
headNode = headNode.nextNode;
if (headNode != null) {
headNode.previousNode = null;
bestFinger.node = headNode;
bestFinger.index = 0;
}
} else if (removedNode.nextNode == null) {
// Once here, removedNode is the tail node:
tailNode = tailNode.previousNode;
if (tailNode != null) {
tailNode.nextNode = null;
bestFinger.node = tailNode;
bestFinger.index--;
}
// Move all the fingers referencing the tail one position to the
// left:
for (Finger<T> finger : fingers) {
if (finger.index == index) {
finger.index--;
finger.node = finger.node.previousNode;
}
}
} else {
// Once here, removedNode has both previous and next nodes:
bestFinger.node = removedNode.nextNode;
for (Finger<T> finger : fingers) {
if (finger.index > index) {
finger.index--;
}
}
removedNode.nextNode.previousNode = removedNode.previousNode;
removedNode.previousNode.nextNode = removedNode.nextNode;
}
size--;
}
public int size() {
return size;
}
boolean hasCorrectState() {
if (size == 0) {
for (Finger<T> finger : fingers) {
if (finger.node != null) {
return false;
}
}
} else {
int index = 0;
for (FingerListNode<T> node = headNode;
node != null;
node = node.nextNode, index++) {
for (Finger<T> finger : fingers) {
if (finger.node == node && finger.index != index) {
return false;
} else if (finger.index < 0) {
return false;
}
}
}
}
return true;
}
private void checkAccessIndex(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("index(" + index + ") < 0");
}
if (index >= size) {
throw new IndexOutOfBoundsException(
"index(" + index + ") >= (" + size + ")");
}
}
private void checkAddIndex(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("index(" + index + ") < 0");
}
if (index > size) {
throw new IndexOutOfBoundsException(
"index(" + index + ") > (" + size + ")");
}
}
}
</code></pre>
<p><strong>Performance figures</strong></p>
<pre><code>FingerList.add in 814 ms.
FingerList.get in 1707 ms.
FingerList.remove in 884 ms.
FingerList total time: 3405 ms.
LinkedList.add in 7437 ms.
LinkedList.get in 18837 ms.
LinkedList.remove in 9346 ms.
LinkedList total time: 35620 ms.
</code></pre>
<p><strong>Critique request</strong></p>
<p>Please tell me anything that comes to mind.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T12:12:06.297",
"Id": "389547",
"Score": "0",
"body": "As I don't share your obsession with linked lists, I will not go into review, but one remark: your benchmark does not include a warmup phase and therefore is bound to report some... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T09:44:42.910",
"Id": "202200",
"Score": "1",
"Tags": [
"java",
"performance",
"linked-list"
],
"Title": "Speeding up a linked list by using fingers in Java"
} | 202200 |
<p>The number fizz buzz is composed of two numbers that are fizz and buzz.</p>
<p>fizz represents the numbers that are divisible by 3 and buzz are the numbers that are divisible by 5.</p>
<p>combining both fizz buzz are the numbers that are divisible by both 3 and 5 both. So how can we get all the fizz buzz numbers sum in a given range?</p>
<p>If we analyze and try to find out the numbers that are divisible by both 3 and 5 we get series like this: </p>
<p>3*5*1, 3*5*2, 3*5*3, .....,3*5*n</p>
<p>analyzing this here is my C# code to find all fizz buzz numbers sum in a given range.</p>
<p>I am looping through the entire range and add all numbers whose remainder with 15 is 0.</p>
<pre><code>int start_range = Convert.ToInt32(Console.ReadLine());
int end_range = Convert.ToInt32(Console.ReadLine());
int sum = 0;
for(int i= start_range; i<= end_range; i++)
{
if(i%15==0)
{
sum = sum + i;
}
}
Console.WriteLine(sum);
Console.ReadKey();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T11:29:55.513",
"Id": "389533",
"Score": "3",
"body": "Try to use the fact that \\$15+30+45+...+15n = 15(1+2+3+...+n) = 15\\frac{n(n+1)}{2}\\$, which should give you the optimal solution. Explanation can be found [here](https://brill... | [
{
"body": "<p>I don't have much to say for the code itself, it is concise, readable and does what you want it to do. That's a good start. My only critique is that you handle input and output in the same place, if you plan on reusing the code maybe consider making a method.</p>\n\n<hr>\n\n<p>So since the code is... | {
"AcceptedAnswerId": "202211",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T10:38:52.763",
"Id": "202205",
"Score": "5",
"Tags": [
"c#",
"performance",
"algorithm",
"fizzbuzz"
],
"Title": "Solution for sum of all fizzbuzz numbers in a given range"
} | 202205 |
<p>on a change of first select, second select options are being dynamically changed. How can I shorten it (jQuery or vanilla JS)? It is 3 way street - therefore class toggle is not an option?</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 () {
$("#selectBox").on("change", function () {
if ($("#selectBox").val() === "widget") {
$("#formSelectColour").removeClass("d-none");
$('#selectWidget option[value="liveAndAverages"]').addClass("d-none");
$('#selectWidget option[value="energy"]').removeClass("d-none");
$('#selectWidget option[value="alerts"]').removeClass("d-none");
} else {
$("#selectWidget").val("live");
$("#formSelectColour").addClass("d-none");
$('#selectWidget option[value="liveAndAverages"]').removeClass("d-none");
$('#selectWidget option[value="energy"]').addClass("d-none");
$('#selectWidget option[value="alerts"]').addClass("d-none");
}
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.d-none {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formSelectBox" class="form-group">
<label for="selectBox">Container: </label>
<select class="form-control" name="selectBox" id="selectBox">
<option selected value="widget">Widget</option>
<option value="graph">Graph</option>
<option value="table">Table</option>
</select>
</div>
<div id="formSelectWidget" class="form-group">
<label for="selectWidget">Data: </label>
<select class="form-control" name="selectWidget" id="selectWidget">
<option value="live">Live</option>
<option value="alerts">Alerts</option>
<option value="energy">Energy</option>
<option class="d-none" value="liveAndAverages">Live and averages</option>
</select>
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T17:49:47.767",
"Id": "389638",
"Score": "0",
"body": "Please include the `formSelectColour` element in your demonstration as well, so that the code makes sense."
}
] | [
{
"body": "<p>I usually use <code>toggleClass</code> in these situations. It accepts an add/remove flag something like:</p>\n\n<pre><code>$(function () {\n $(\"#selectBox\").on(\"change\", function () {\n var is_widget = $(\"#selectBox\").val() === \"widget\"; \n if (!is_widget)\n $(... | {
"AcceptedAnswerId": "202232",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T10:41:27.200",
"Id": "202206",
"Score": "-1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Shortening jQuery 3 way selects (+class toggle)"
} | 202206 |
<p>I am beginner in programming and recently I wrote an editor, inspired by the Notepad program, with all basic features any editor should have, like finding, undoing, copying, etc.</p>
<p>The problem is I do not "feel" OOP completely yet. I wrote the whole program in a single class with few inner classes for actions, a frame for finding and replacing etc. I only wrote one separate class for style settings, like textArea Color etc, yet implementation of this class was poor in my belief.</p>
<p>In the result I was happy with the fact I managed to create fully working notepad; however I cannot stop thinking how messy is the code underneath it. So I decided to rewrite it just for exercise and make it more structured.</p>
<p>I read about MVC pattern and I tried to apply it to my code. I wrote 2 view classes - Main View (with textArea and menuBar) and FindAndReplace frame in separate class. Then I created model and controller.</p>
<p>Can you tell me if this makes any sense? Is this good implementation of MVC or I misunderstood it completely?</p>
<h2>MainGUI.java</h2>
<pre><code>import javax.swing.*;
import java.awt.*;
public class MainGUI extends JFrame{
public MainGUI(){
initMainFrame();
initMenuBar();
initToolBar();
}
private JTextArea textArea = new JTextArea();
void initMainFrame(){
setBounds(300,300,300,300);
add(textArea);
setDefaultCloseOperation(3);
}
public JMenuBar menuBar;
public JMenu menuEdit;
public JMenuItem findAndReplace = new JMenuItem("Find and replace");
void initMenuBar(){
this.add(menuBar=new JMenuBar(),BorderLayout.NORTH);
menuBar.add(menuEdit = new JMenu("Edit"));
menuEdit.add(findAndReplace);
}
void initToolBar()
{
/**
* toolbar
*/
}
public void setText(String text){
textArea.setText(text);
}
public String getText(){
return textArea.getText();
}
public void selectText(int selectionStart, int selectionEnd){
textArea.select(selectionStart, selectionEnd);
}
}
</code></pre>
<h2>FindAndReplaceGUI.Java</h2>
<pre><code>import javax.swing.*;
import java.awt.*;
public class FindAndReplaceGUI extends JFrame{
private JTextField findTextField = new JTextField(10);
private JTextField replaceTextField = new JTextField(10);
private JButton findTextBtn = new JButton(" Find Text ");
private JButton replaceTextBtn = new JButton("Replace Text");
public FindAndReplaceGUI(){
initComponents();
}
void initComponents(){
setBounds(300,300,300,100);
setResizable(false);
setDefaultCloseOperation(3);
JPanel TopPanel = new JPanel();
add(TopPanel,BorderLayout.NORTH);
TopPanel.add(findTextField);
TopPanel.add(findTextBtn);
JPanel bottomPanel = new JPanel();
add(bottomPanel,BorderLayout.CENTER);
bottomPanel.add(replaceTextField);
bottomPanel.add(replaceTextBtn);
}
public String getTextFieldText(){
return findTextField.getText();
}
public JButton getFindButton(){
return findTextBtn;
}
public String getReplaceFieldText(){
return replaceTextField.getText();
}
public JButton getReplaceButton(){
return replaceTextBtn;
}
}
</code></pre>
<h2>Model.Java</h2>
<pre><code>public class Model {
private int selectionStart=-1;
private int selectionEnd=0;
void findText(String textToFind, String textArea)
{
selectionStart=textArea.indexOf(textToFind, selectionStart+1);
if (selectionStart == -1)
{
selectionStart = textArea.indexOf(textToFind);
}
if (selectionStart >= 0)
{
selectionEnd=selectionStart+textToFind.length();
}
if(!textArea.contains(textToFind))
selectionEnd=0;
System.out.println(selectionStart);
System.out.println(selectionEnd);
}
void replaceText(String textForReplacement, String textArea)
{
/**
* replace text method
*/
}
int getSelectionStart(){
return selectionStart;
}
int getSelectionEnd(){
return selectionEnd;
}
}
</code></pre>
<h2>Controler.Java</h2>
<pre><code>public class Controler {
MainGUI mainGui=new MainGUI();
FindAndReplaceGUI finder = new FindAndReplaceGUI();
Model model = new Model();
Controler()
{
mainGui.setVisible(true);
}
public void control()
{
mainGui.findAndReplace.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
finder.setLocationRelativeTo(mainGui);
finder.setVisible(true);
}
});
/**
* Find and Replace control
*/
finder.getFindButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
model.findText(finder.getTextFieldText(), mainGui.getText());
mainGui.selectText(model.getSelectionStart(), model.getSelectionEnd());
}
});
finder.getReplaceButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.replaceText(finder.getReplaceFieldText(), mainGui.getText());
}
});
}
public static void main(String[] args) {
new Controler().control();
}
}
</code></pre>
<p>Does it make sense to put all ActionListeners to controller?</p>
<p>And I am wondering how should I access menu items from controller class? Does it make sense to set them on public (<code>MainGUI</code> and <code>FindAndReplace</code> are in different package) and calling them from in <code>Controler</code> class from the object mainGUI directly.</p>
<p>I am still learning to code simple and clean yet I feel I am still complicating things..</p>
| [] | [
{
"body": "<p>as picture overview does looks like a beginner nice job, you miss something in <code>MODEL</code> part (a good model does not performs business logic: if you implement a <code>find()</code> method in <code>Controller</code>, you'll can modularize it to find between more files, just as example).</p... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T12:35:29.560",
"Id": "202212",
"Score": "3",
"Tags": [
"java",
"beginner",
"mvc",
"text-editor"
],
"Title": "Text editor using MVC pattern"
} | 202212 |
<p>In the last months I have written an application that, among other things, parses financial documents. This application has grown quite organically and I am not happy with that.
I split the application into several libraries by functionality and intended to use simple DTOs. These DTOs will be created in the library responsible for the parsing and passed around into other libraries to work with (which I am already not too happy in terms of dependency).</p>
<p>One example of such a DTO is this (the fields are all nullable on purpose since I might not be able to fill them):</p>
<pre><code>public class KidData
{
public string ISIN { get; set; }
public Uri DownloadLink { get; set; }
public string WKN { get; set; }
public string Emittent { get; set; }
public string ProductName { get; set; }
public int? SRI { get; set; }
public string ScenarioCurrency { get; set; }
public Scenario StressScenario { get; set; }
public Scenario PessimisticScenario { get; set; }
public Scenario MediumScenario { get; set; }
public Scenario OptimisticScenario { get; set; }
public string BaseValue { get; set; }
public DateTime? CreationDate { get; set; }
public float? AskPrice { get; set; }
public DateTime? EmissionDate { get; set; }
public DateTime? DateOfRepayment { get; set; }
public float? Strike { get; set; }
public string StrikeUnit { get; set; }
public FinProductData Product { get; set; }
}
</code></pre>
<p>There is a class with extension methods for this DTO that fills the data by string values like this (this mapping is not trivial in all cases and may require calculations):</p>
<pre><code>public static SetValue(this KidData data, string field, string value)
{
switch(field)
{
case "ISIN":
data.ISIN = value;
break;
case ...
}
}
</code></pre>
<p>This seemed like the best approach to me to limit the visibility of the functionality to fill my data to this very library. However due to inheritance I was not able to keep this pattern for all my DTOs as you can see:</p>
<pre><code>public abstract class FinProductData
{
public string Name { get; set; }
protected float? _faceValue;
public abstract float? FaceValue { get; protected set; }
private static Logger logger = LogManager.GetCurrentClassLogger();
public virtual void SetValue(string field, string value)
{
switch (field)
{
case "Name":
Name = value;
break;
case "FaceValue":
FaceValue = StringOperations.ParseEuroCurrency(value);
break;
default:
logger.Warn($"Unsupported descriptor ({field}), it will be ignored");
break;
}
}
}
</code></pre>
<p>Here is an example of an overriding class:</p>
<pre><code>public class ExpressCertificate : FinProductData
{
public override float? FaceValue
{
get => _faceValue;
protected set => _faceValue = value;
}
public float? RepayThreshold { get; set; }
public List<EarlyRepayment> EarlyRepayments { get; set; } = new List<EarlyRepayment>();
private static Logger logger = LogManager.GetCurrentClassLogger();
public override void SetValue(string descriptor, IList<(string groupName, string newValue)> groups, KidData availableData)
{
switch (descriptor)
{
case "RepayThreshold":
RepayThreshold = StringOperations.ParseEuroCurrency(groups.First().newValue);
break;
case "EarlyRepayment":
EarlyRepayments = EarlyRepayments ?? new List<EarlyRepayment>();
EarlyRepayments.Add(new EarlyRepayment(groups, availableData));
break;
case "CalculatedEarlyRepayments":
EarlyRepayments = CalculateEarlyRepayments(groups);
break;
default:
base.SetValue(descriptor, groups, availableData);
break;
}
}
</code></pre>
<p>You will probably agree that this 'solution' is very ugly, but I don't know how to improve it. I thought about keeping this class and generating a true DTO from it, but I am not really sure if that's the way to go. I also thought about having some sort of factory to create my DTOs but there are dependencies between data entries and I can also not really guarantee a specific order of completion of my objects.</p>
<p>So my question is pretty much how to solve this specific question or improve the overall design.</p>
<p><strong>EDIT:</strong></p>
<p>Since I have received several answers on how to structure my <code>SetValue</code> function: This is not my main concern. I would really appreciate the a better solution here, but sadly <code>field</code> is not a one-to-one correspondence to the field names.
My main concern is how I can separate my data from my functionality.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T13:10:37.613",
"Id": "389563",
"Score": "1",
"body": "Welcome to Code Review. I have some difficulties understanding your needs. Why is `SetValue` virtual in `FinProductData`? Could you provide example where it gets overriden? I can... | [
{
"body": "<p>If performance aren't critical (measure, do not guess) then you can use some Reflection:</p>\n\n<pre><code>public virtual void SetValue(string field, string value)\n{\n var property = GetType().GetProperty(field);\n property.SetValue(this, value);\n}\n</code></pre>\n\n<p>This will handle all... | {
"AcceptedAnswerId": "202215",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T12:36:17.543",
"Id": "202213",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Separate the creation logic of a DTO from actual data"
} | 202213 |
<pre><code>#loop to get input that is not blank, strips input of whitespace
def ckin(a):
while a=='':
a=input().strip()
return a
#creates list with includes user admin
user_names = ['admin']
#Ask for 5 names to store as usernames
print('Please enter 5 user names: ')
#if username is valid, add to list
for i in range(0,5)
lib_name=input().strip()
lib_name=ckin(lib_name)
user_names.append(lib_name)
#asks for login name, must be valid
print('Enter login name:')
log_name=input().strip()
log_name=ckin(log_name)
#Create a test list that is lower case to compare login
#against without altering the cases used by user to creat username list
test=[name.lower() for name in user_names]
#if login name not in list continue to prompt
while log_name.lower() not in test:
print('Enter login name:')
log_name=input().strip()
log_name=ckin(log_name)
#find login name in test, then return either response for admin, or login name using
#case formatting that original used for original entry
for i in range(len(test)):
if log_name.lower() == 'admin':
print('Hello admin, would you like to see a status report?')
break
elif log_name.lower() == test[i]:
print('Hello '+user_names[i]+', thank you for logging in again')
break
</code></pre>
<p>Looking for general review self-teaching, Day 4</p>
<p>I haven't learned much but I keep attempting to do what I'm learning with user inputs instead of set entries</p>
<p>My goal here was to be able to create a list that keeps the original entry cases to be used for responding. I created a second list in lower cases to compare to and then responded using the cases the entries were stored as.</p>
<p>Any comments are greatly appreciated!</p>
| [] | [
{
"body": "<h1>General</h1>\n\n<p>Read and familiarize yourself with</p>\n\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a></li>\n<li>Functions</li>\n<li>The <code>if __name__ == '__main__':</code> check</li>\n</ul>\n\n<p>Make sure, the function and variable names con... | {
"AcceptedAnswerId": "202226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T13:50:09.777",
"Id": "202219",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Code for testing user inputs in python3"
} | 202219 |
<p>The question is taken for a coding interview I had, it is also in geeks for geeks, <a href="https://www.geeksforgeeks.org/zigzag-tree-traversal/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/zigzag-tree-traversal/</a></p>
<p>you are given a binary tree and you need to print it in a ZigZag/Snake order
for level one from left to right and the next level from right to left and so on.</p>
<p>I was asked only to come up with a solution I used a queue and a stack in the real interview, when I coded it now I tried using 2 stacks.</p>
<p>Please review the code as if it was a real interview, complexity, coding style, assume I have 20-30 minutes to code. you can ignore the test case.</p>
<p>Thanks. </p>
<pre><code>using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
[TestClass]
public class PrintBinaryTreeZigZag
{
[TestMethod]
public void PrintBinaryTreeZigZagTest()
{
BinaryTree root = new BinaryTree
{
Value = 1,
Left = new BinaryTree { Value = 2 },
Right = new BinaryTree { Value = 3 }
};
root.Left.Left = new BinaryTree { Value = 7 };
root.Left.Right = new BinaryTree { Value = 6 };
root.Right.Left = new BinaryTree { Value = 5 };
root.Right.Right = new BinaryTree { Value = 4 };
List<int> res = PrintBinaryZigZag(root);
List<int> expected = new List<int> { 1, 3, 2, 7, 6, 5, 4 };
CollectionAssert.AreEqual(expected, res);
}
public List<int> PrintBinaryZigZag(BinaryTree root)
{
if (root == null)
{
return null;
}
Stack<BinaryTree> currentLevel = new Stack<BinaryTree>();
Stack<BinaryTree> nextLevel = new Stack<BinaryTree>();
List<int> result = new List<int>();
currentLevel.Push(root);
bool leftToRight = true;
while (currentLevel.Count > 0)
{
BinaryTree temp = currentLevel.Peek();
currentLevel.Pop();
if (temp != null)
{
//same as print
result.Add(temp.Value);
if (leftToRight)
{
if (temp.Left != null)
{
nextLevel.Push(temp.Left);
}
if (temp.Right != null)
{
nextLevel.Push(temp.Right);
}
}
else
{
if (temp.Right != null)
{
nextLevel.Push(temp.Right);
}
if (temp.Left != null)
{
nextLevel.Push(temp.Left);
}
}
}
if (currentLevel.Count == 0)
{
leftToRight = !leftToRight;
Stack<BinaryTree> tempStack = currentLevel;
currentLevel = nextLevel;
nextLevel = tempStack;
}
}
return result;
}
}
public class BinaryTree
{
public BinaryTree Left { get; set; }
public BinaryTree Right { get; set; }
public int Value { get; set; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T15:16:59.677",
"Id": "389603",
"Score": "0",
"body": "An example of input/output in a clearer format that a test case would be great to understand the context of your problem"
}
] | [
{
"body": "<p>The algorithm seems okay so I'll review the OOP aspect.</p>\n<h2>Naming</h2>\n<ol>\n<li>The method named <code>PrintBinaryZigZag</code> but it doesn't print anything.</li>\n<li>The class named <code>BinaryTree</code> isn't really a binary tree, it's more of a <code>Node</code>.</li>\n</ol>\n<h2>Im... | {
"AcceptedAnswerId": "202242",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T14:01:57.660",
"Id": "202221",
"Score": "4",
"Tags": [
"c#",
"tree",
"interview-questions"
],
"Title": "ZigZag tree travesal"
} | 202221 |
<p>I am learning Python 3. One thing I am doing to get some repetition is going through checkio. It is a website with coding exercises. One of the exercises gives an input string as follows:</p>
<pre><code>str_to_nbrs("(2,2),(6,2),(2,6)")
str_to_nbrs("(3,7),(6,10),(9,7)")
</code></pre>
<p>I need the output of this code to produce a list of sub lists with the pairs of numbers so I can put them into variables to use for calculations. </p>
<p>This exercise actually has to do with x and y coordinates and circles. I am not sure why this input was in the form of a string. But, it gives me a chance to learn how to use the tools to convert a string like this to numbers that I can use in mathematical processes.</p>
<p>I figured out how to accomplish what I need. I am relatively new to Python 3. But, from what I have seen already, it is a well-thought-out and efficient language. I would bet there is a better way to do it with less code. </p>
<p>Please note that I added the big obvious comments to explain what the code is doing. They are not part of my regular coding style.</p>
<p>One more thing: I am still trying to come up with a convention for variable names. I have started lists with "l_". I try to give things meaningful names, but also try to keep them relatively short. I know "l_work" isn't a good name. But, I just wanted to finish that section of code, and used that...err...unimaginative name.</p>
<pre><code>import re
# str_to_nbrs("(2,2),(6,2),(2,6)")
def str_to_nbrs(data):
print("String input:")
print(data)
print()
new_data = re.sub(r"\(","",data)
new_data = new_data + ","
print("Remove left parenthesis and add a comma a the end for split method:")
print(new_data)
print()
l_data = new_data.split("),")
l_data.pop()
print("Reformatted string data in a list:")
print(l_data)
print()
l_work = []
l_nbrs = []
l_all = []
for i in l_data:
l_work = i.split(",")
for j in l_work:
l_nbrs.append(int(j))
l_all.append(l_nbrs)
l_nbrs = []
print("Integers in sub lists:")
print(l_all)
print()
print("---------------------")
print()
str_to_nbrs("(2,2),(6,2),(2,6)")
str_to_nbrs("(3,7),(6,10),(9,7)")
</code></pre>
| [] | [
{
"body": "<p><code>re.sub(r\"\\(\",\"\",data)</code> is not a very good use of regular expressions. You could have more easily achieved the same result with <code>data.replace(\"(\", \"\")</code>.</p>\n\n<p>But since you are already using regular expressions, why not use them to do more:</p>\n\n<pre><code>>... | {
"AcceptedAnswerId": "202228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T14:20:28.150",
"Id": "202222",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "Converting an input string to a list of sub lists with numbers"
} | 202222 |
<p>I'm trying to quickly and efficiently find every recurring position of small byte arrays (4 bytes) in large binary files (several GBs). My current method is as follows:</p>
<pre><code>Stream stream = File.OpenRead(filepath);
List<long> searchResults = new List<long>(); //The results as offsets within the file
int searchPosition = 0; //Track of how much of the array has been matched
int[] searchPattern = { 0x00, 0x01, 0x02, 0x03 }; // The array to search
while(true) //Loop until we reach the end of the file
{
var latestbyte = stream.ReadByte();
if(latestbyte == -1) break; //We have reached the end of the file
if(latestbyte == searchPattern[searchPosition]
{
searchPosition++;
if(searchPosition == searchPattern.Length)
{
searchResults.Add(stream.Position);
}
}
else
{
searchPosition = 0;
}
}
</code></pre>
<p>It's slow, and seems quite inefficient (3-4 seconds for a small 174MB file, 35 seconds for a 3GB one). </p>
<p>How can I improve the performance? </p>
<p>I looked into Boyer-Moore, but is it really worth it, considering the pattern i'm looking for is only 4 bytes?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T16:36:35.460",
"Id": "389614",
"Score": "1",
"body": "Ok, now that this is fixed, let me ask you two questions: 1. Can there be same bytes (or sub-sequences) in the search pattern? Because you could skip start of the sequence being ... | [
{
"body": "<p>You should be aware, that if you have a search pattern like:</p>\n\n<pre><code>byte[] pattern = { 0x00, 0x01, 0x02, 0x03 };\n</code></pre>\n\n<p>and a file sequence as </p>\n\n<pre><code>..., 0x00, 0x00, 0x01, 0x02, 0x03,...\n</code></pre>\n\n<p>Then it won't be found, because the first <code>0x00... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T16:03:52.547",
"Id": "202235",
"Score": "1",
"Tags": [
"c#",
"search"
],
"Title": "Finding specific small byte arrays in large binary files"
} | 202235 |
<p>Although having very little C++ experience, I was tasked to implement several statistics objects that are safe to be asynchronous accessed by different threads, that collect data in relatively small memory caches and do the math when asked. Many of those I need to write are based on averaging, so help me by inspecting basic averaging class. I just hope to avoid any strategic errors in design of my cargo-cult code-gluing efforts. </p>
<pre><code>#include <mutex>
template <typename T, int N> class Average {
T data[N];
int head;
double avg;
int itr;
int counter;
std::mutex _mutex;
public:
Average() : head(0), avg(0.), itr(0), counter(0) {
};
void empty() {
std::unique_lock<std::mutex> lock(this->_mutex);
head = 0;
avg = 0.;
itr = 0;
counter = 0;
}
int count() {
std::unique_lock<std::mutex> lock(this->_mutex);
return counter;
}
void push(T value) {
std::unique_lock<std::mutex> lock(this->_mutex);
counter++;
data [head] = value;
double tmp = 0.;
if (++head == N) {
head = 0;
for (int i = 0; i < N; i++) {
tmp = tmp + data[i];
}
tmp = tmp / N;
avg = (avg * itr) + tmp;
itr += 1;
avg = avg / itr;
}
}
double average() {
std::unique_lock<std::mutex> lock(this->_mutex);
double tmp = 0.;
if (head == 0){
if (itr == 0) return 0.0;
return avg;
}
for (int i = 0; i < head; i++) {
tmp = tmp + data[i];
}
if (itr == 0) return tmp / head;
tmp = tmp/N;
return ((avg * itr) + tmp) / ((double)itr + (double)head/(double)N);
}
};
</code></pre>
<p>As an usage example, by extending the Average class, I implemented a RunningAverage class which averages only let say last N pushed values. I got a worker pool that perform Monte Carlo simulation where it is preferred to maintain step acceptance rate 0.5+/-0.1 and when rate falls outside, I adjust model parameters. So I got something like: </p>
<pre><code>#define ACCEPT_STEP 1
#define DECLINE_STEP 0
RunningAverage <float, ACC_BUFFER_LEN> global_acceptance_rate;
</code></pre>
<p>and thread do something like:</p>
<pre><code>global_acceptance_rate.push(ACCEPT_STEP); // or
global_acceptance_rate.push(DECLINE_STEP);
</code></pre>
<p>So this allows me to dynamically control simulation.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T19:02:15.740",
"Id": "389651",
"Score": "2",
"body": "Could you add an example of how to use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T01:42:22.227",
"Id": "389707",
"Score": "0",
... | [
{
"body": "<h2>Code</h2>\n\n<ul>\n<li>Prefer <code>std::array</code> over plain C-style arrays. It has more normal copy / assignment semantics (which admittedly isn't relevant here), but also allows you to access the size directly from the array.</li>\n<li><p>Naming:</p>\n\n<ul>\n<li><code>head</code> is usuall... | {
"AcceptedAnswerId": "202290",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T17:35:49.597",
"Id": "202243",
"Score": "11",
"Tags": [
"c++",
"thread-safety",
"statistics"
],
"Title": "C++ thread-safe averaging"
} | 202243 |
<p>I was recently building a form to add contacts to a play app I'm making and I finally got it to work. The problem is I'm not too happy with it. </p>
<p>It's my first time building an application with React, so I don't really have any experience on my toolbelt, but I can see the responsabilities aren't too well sorted out. I can imagine in an ideal scenario I would have smaller components, but I can't see how to break this down any further.</p>
<p>If you guys can correct me overall good/bad practices when coding with JS/React and also suggest how I could further break down the form into smaller pieces, I would be supergrateful!</p>
<p>Just as a heads up, I'm trying not to use Redux or Flux. Just plain JS and React. I wanted to learn these two properly before adding more pieces to the puzzle.</p>
<p>I'll attach the two main components involved in the application, as well as a simplified container for them, just so you guys can simply copy-paste it to get it working :)</p>
<p>This component represents a simple form field.</p>
<pre><code>import React, { PureComponent } from 'react';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap';
export class FormField extends PureComponent {
constructor(props) {
super(props);
this.state = { value: '' };
}
render() {
return (
<FormGroup controlId={this.props.id}>
<ControlLabel>{this.props.label}</ControlLabel>
<FormControl {...this.props} onChange={this.props.handleChange} />
{this.props.help && <HelpBlock>{this.props.help}</HelpBlock>}
</FormGroup>
);
}
}
</code></pre>
<p>But then, the actual form looks like this:</p>
<pre><code>import React, { Component } from 'react';
import { Modal, Glyphicon, Form, FormGroup, Col, Row, Button } from 'react-bootstrap';
import { FormField } from '../common/FormField';
export default class NewContactModal extends Component {
constructor(props, context) {
super(props, context);
this.handleClose = this.handleClose.bind(this);
this.state = {
show: this.props.show,
name: '',
email: '',
username: ''
};
}
handleClick = () => {
var opts = {
method: 'POST',
body: JSON.stringify({
name: this.state.name,
username: this.state.username,
email: this.state.email
}),
headers: {
"Content-Type": "application/json"
}
};
fetch('api/contacts', opts)
.then(response => response.json())
.then(data => {
console.log('Added!')
});
}
handleNameChange = event => {
this.setState({
name: event.target.value,
});
};
handleUsernameChange = event => {
this.setState({
username: event.target.value,
});
};
handleEmailChange = event => {
this.setState({
email: event.target.value,
});
};
handleClose() {
this.setState({ show: false });
}
componentWillReceiveProps(nextProps) {
// You don't have to do this check first, but it can help prevent an unneeded render
if (nextProps.show !== this.state.show) {
this.setState({ show: nextProps.show });
}
}
render() {
return (
<div>
<Modal show={this.state.show} onHide={this.handleClose}>
<Form horizontal>
<Modal.Header closeButton>
<Modal.Title>
<Glyphicon glyph='user' /> New contact
</Modal.Title>
</Modal.Header>
<Modal.Body className="mx-auto" style={{ margin: '20px' }}>
<Row>
<Col md={5}>
<FormField
id="formName"
label="Name"
placeholder="Name"
handleChange={this.handleNameChange} />
</Col>
<Col md={5} mdOffset={2}>
<FormField
id="formUsername"
label="Username"
placeholder="Username"
handleChange={this.handleUsernameChange} />
</Col>
</Row>
<Row>
<Col md={5}>
<FormField
id="formEmail"
label="Email"
placeholder="Email"
type="email"
handleChange={this.handleEmailChange} />
</Col>
<Col md={5} mdOffset={2}>
<FormField
id="formGithub"
label="Github"
placeholder="Github"
handleChange={this.handleUsernameChange} />
</Col>
</Row>
</Modal.Body>
<Modal.Footer>
<FormGroup style={{ 'margin-right': '5px' }}>
<Button bsStyle="primary" type="submit" onClick={(evt) => this.handleClick()}>Save</Button>
</FormGroup>
</Modal.Footer>
</Form>
</Modal>
</div>
);
}
}
</code></pre>
<p>Here are the relevant parts of the container code:</p>
<pre><code>import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import NewContactModal from './NewContactModal';
export class ContainerComponent extends Component {
displayName = ContainerComponent.name
constructor(props) {
super(props);
this.state = {
show: false
}
this.handleShow = this.handleShow.bind(this);
}
handleShow() {
this.setState({ show: true });
}
render() {
return (
<div>
<Button bsStyle="primary" onClick={this.handleShow}>Add Contact</Button>
<NewContactModal show={this.state.show}/>
</div>
);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T20:00:19.893",
"Id": "389659",
"Score": "0",
"body": "Please note that \"somewhat like this\" makes this a marginal Code Review question, since the [help/on-topic] rules require you to post real code. If you choose to simplify the c... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T19:08:14.103",
"Id": "202246",
"Score": "1",
"Tags": [
"form",
"react.js",
"jsx"
],
"Title": "React form to add contacts to an app"
} | 202246 |
<p>I'm not an experienced Linux user and I wanted an easy way to run shell scripts as root from a PHP script, I came up with this:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
int main(int argc, char *argv[])
{
if (access(argv[1], F_OK) != -1)
{
struct stat filestat;
if (stat(argv[1], &filestat) == 0)
{
if ((filestat.st_uid == 0) && (filestat.st_gid == 0) && (filestat.st_mode & S_IXUSR) && (!(filestat.st_mode & S_IWOTH)))
{
char* match = strrchr(argv[1], '.');
if ((match != NULL) && (strcasecmp(match, ".sh") == 0))
{
if (setuid(0) != -1)
{
execl("/usr/bin/sudo", "/usr/bin/sudo", argv[1], (char*) NULL);
return 0;
}
}
}
}
}
return 1;
}
</code></pre>
<p>Any potential security issues with this? If so how can I improve it?</p>
<p><strong>Example Usage:</strong></p>
<p>Lets say I have a script located at:</p>
<pre><code>/some/path/script.sh
</code></pre>
<p>With the following in it:</p>
<pre><code>#!/bin/bash
echo $USER
</code></pre>
<p>Now lets say I compile the above C code to a binary and place it at:</p>
<pre><code>/some/path/run-as
</code></pre>
<p>and do:</p>
<pre><code>chown root:root /some/path/run-as
chmod 6755 /some/path/run-as
</code></pre>
<p>Now I run this PHP script owned by www-data (via browser / local apache web server):</p>
<pre><code><?php
echo exec('/some/path/run-as /some/path/script.sh');
?>
</code></pre>
<p>I expect the script to output 'root' when ran.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T20:36:32.063",
"Id": "389671",
"Score": "0",
"body": "@TobySpeight I went ahead and edited the post with example usage to give you an idea of what I'm trying to do, also I'm not too familiar with Linux so I'm not even sure If my ide... | [
{
"body": "<p>This is an ambitious thing to try, with many pitfalls - especially for environments which are Web-accessible. I urge you to learn how to configure and use <code>sudo</code> instead - that's not foolproof, but it <em>is</em> a good deal safer than rolling your own.</p>\n\n<p>That said, I'll make s... | {
"AcceptedAnswerId": "202254",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T20:02:39.957",
"Id": "202249",
"Score": "1",
"Tags": [
"c",
"security",
"linux",
"wrapper",
"child-process"
],
"Title": "Running shell script as root via external binary"
} | 202249 |
<p>I wanted to write a custom session to act as proxy for a Dapper connection that could support transactions without having to expose any other DB related entities.</p>
<p>At first, I thought of opening a connection upon creation of the session and keeping it open for the whole life of the instance. As I researched about the subject, I've learned that opening and closing the connections as needed would yield better performance because of the connection pool implemented by ADO.NET. So I tried the following implementation:</p>
<pre><code>public class DBSession : IDisposable
{
private readonly IConnectionFactory _connectionFactory;
private IDbConnection _activeConnection;
private IDbTransaction _activeTransaction;
public DBSession(IConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
private void PreExecuteSingleStatement()
{
//Open DB connection if no transaction is open.
if (_activeTransaction != null)
return;
_activeConnection = _connectionFactory.GetOpenConnection();
if (_activeConnection.State != ConnectionState.Open)
_activeConnection.Open();
}
private void PostExecuteSingleStatement()
{
//Close DB connection if no transaction is open.
if (_activeTransaction != null)
return;
if (_activeConnection.State == ConnectionState.Open)
_activeConnection.Dispose();
_activeConnection = null;
}
public void BeginTransaction()
{
if (_activeTransaction != null)
throw new InvalidOperationException("Não é possível criar uma nova transação pois já há uma transação aberta.");
if (_activeConnection == null)
_activeConnection = _connectionFactory.GetOpenConnection();
if (_activeConnection.State != ConnectionState.Open)
_activeConnection.Open();
_activeTransaction = _activeConnection.BeginTransaction();
}
public void CommitTransaction()
{
if (_activeTransaction == null)
throw new InvalidOperationException("Não é possível comitar uma transação pois não há nenhuma transação aberta.");
_activeTransaction.Commit();
_activeTransaction.Dispose();
_activeTransaction = null;
_activeConnection.Dispose();
_activeConnection = null;
}
public void RollbackTransaction()
{
if (_activeTransaction == null)
throw new InvalidOperationException("Não é possível dar rollback numa transação pois não há nenhuma transação aberta.");
_activeTransaction.Rollback();
_activeTransaction.Dispose();
_activeTransaction = null;
_activeConnection.Dispose();
_activeConnection = null;
}
public void Insert<T>(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
PreExecuteSingleStatement();
_activeConnection.Insert<T>(value);
PostExecuteSingleStatement();
}
public void Dispose()
{
if (_activeTransaction != null)
{
_activeTransaction.Rollback();
_activeTransaction.Dispose();
_activeTransaction = null;
}
if (_activeConnection != null)
_activeConnection.Dispose();
}
}
</code></pre>
<p><code>IConnectionFactory</code> code:</p>
<pre><code>internal interface IConnectionFactory
{
IDbConnection GetOpenConnection();
}
</code></pre>
<p>For now, I only implemented an <code>Insert</code> method. I plan to write other methods for different operations that will follow almost the same steps as this method.</p>
<p>This code seems somewhat convoluted to me. Lots of checks makes it look very hack-y.</p>
<p>Is there a better way to approach this problem?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T20:28:34.877",
"Id": "202252",
"Score": "2",
"Tags": [
"c#",
"asp.net-core",
"dapper"
],
"Title": "A custom session with transaction support using Dapper"
} | 202252 |
<p>So I am trying to delete a list having n number of objects and thereby I divided the list in 4 parts and let it to be deleted in parallel. The intention here is to do it in parallel so as to make it fast rather than sequential. deleteObject(x) can be assumed as an API which finally deletes an object has the code to take care of concurrency. It returns true on successful delete and false otherwise</p>
<p>I have few question here </p>
<ol>
<li>So as I have 4 parallel method which I am executing though invokeAll
and there are 4 threads declared by Executors.newFixedThreadPool(4)
would there always be 1 thread be assigned to 1 method?</li>
<li>Do I need to synchronize and use volatile for iterator 'i' in the for loop of parallelDeleteOperation() method. The reason I am asking this is supposing if 1st thread has not completed its task (deleting listDir1 and the for loop has not completed) and supposing in midway it got context switch and 2nd thread starts executing the same task(deleting listDir1). Just wondering if 2nd thread can get IndexOutOfBound exception in this case.</li>
<li>Is there any advantage of dividing list in 4 parts and executing this rather than having multiple threads executing delete operation on a very big list.</li>
<li><p>If one of the operation of ExecutorService returns false then on the whole deleteMain() API would return false </p>
<pre><code>public boolean deleteMain(List<Integer> listDir) {
if(listDir.size()<4){
return parallelDeleteOperation(listDir);
}
final List<Integer> listDir1 = listDir.subList(0, listDir.size() / 4);
final List<Integer> listDir2 = listDir.subList(listDir.size() / 4, listDir.size() / 2);
final List<Integer> listDir3 = listDir.subList(listDir.size() / 2, (listDir.size()/ 4) *3);
final List<Integer> listDir4 = listDir.subList((listDir.size()/ 4)*3, listDir.size());`
Set<Callable<Boolean>> callables = new HashSet<Callable<Boolean>>();
callables.add(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return parallelDeleteOperation(listDir1);
}
});
callables.add(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return parallelDeleteOperation(listDir2);
}
});
callables.add(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return parallelDeleteOperation(listDir3);
}
});
callables.add(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return parallelDeleteOperation(listDir4);
}
});
ExecutorService service = Executors.newFixedThreadPool(4);
try {
List<Future<Boolean>> futures = service.invokeAll(callables);
for(Future<Boolean> future : futures){
if( future.get() != true)
return future.get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally{
service.shutdown();
}
return true;
}
public boolean parallelDeleteOperation(List<Integer> listDir) {
for (int i = 0; i < listDir.size(); i++) {
int x = listDir.get(i);
deleteObject(x);
if(deleteObject(x)!=true)
return false;
}
return true;
}
</code></pre></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T03:38:58.370",
"Id": "389713",
"Score": "1",
"body": "Your code will not work properly as written. Objects will be deleted twice, which should immediately fail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2... | [
{
"body": "<p>First of all, regarding your questions:</p>\n\n<ol>\n<li>Yes. The 4 Futures will be mapped to 4 executor threads for all practical considerations. There might be edge-cases, where the first future is finished before the last is submitted and a thread gets reused, but this does not lead to any prac... | {
"AcceptedAnswerId": "202279",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T23:29:16.660",
"Id": "202258",
"Score": "0",
"Tags": [
"java",
"multithreading"
],
"Title": "Executor tasks for parallelizing a method"
} | 202258 |
<p>I would like to ask for code review for my <a href="https://leetcode.com/problems/lru-cache/description/" rel="nofollow noreferrer">LRU Cache implementation</a> from leetcode. </p>
<blockquote>
<p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.</p>
<ul>
<li><code>get(key)</code> - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.</li>
<li><code>put(key, value)</code> - Set or insert the value if the key is not already present. When the cache reached its capacity, it should
invalidate the least recently used item before inserting a new item.</li>
</ul>
<p>Follow up:
Could you do both operations in O(1) time complexity?</p>
</blockquote>
<p>I make sure that I used the <code>LinkedListNode</code> class to make sure the solution is optimal with O(1) time complexity.</p>
<pre><code>class ListNode(object):
def __init__(self, key, val):
self.val = val
self.key = key
self.next = None
self.prev = None
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def insert(self, node):
node.next, node.prev = None, None # avoid dirty node
if self.head is None:
self.head = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
def delete(self, node):
if node.prev:
node.prev.next = node.next
else:
self.head = node.next
if node.next:
node.next.prev = node.prev
else:
self.tail = node.prev
node.next, node.prev = None, None # make node clean
class LRUCache(object):
# @param capacity, an integer
def __init__(self, capacity):
self.list = LinkedList()
self.dict = {}
self.capacity = capacity
def _insert(self, key, val):
node = ListNode(key, val)
self.list.insert(node)
self.dict[key] = node
# @return an integer
def get(self, key):
if key in self.dict:
val = self.dict[key].val
self.list.delete(self.dict[key])
self._insert(key, val)
return val
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def put(self, key, val):
if key in self.dict:
self.list.delete(self.dict[key])
elif len(self.dict) == self.capacity:
del self.dict[self.list.head.key]
self.list.delete(self.list.head)
self._insert(key, val)
</code></pre>
<p>This passes the leetcode tests.</p>
| [] | [
{
"body": "<p>Usual comment: add <code>\"\"\"docstrings\"\"\"</code> to public methods at the very least. </p>\n\n<p>Avoid double (and triple) lookups. Python has fast exception handling. Instead of testing for existence, and then fetching the value, just fetch the value. And don’t fetch it more than once. ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T00:28:04.593",
"Id": "202261",
"Score": "0",
"Tags": [
"python",
"programming-challenge",
"linked-list",
"cache"
],
"Title": "LRU Cache in constant time"
} | 202261 |
<p>The program takes in a set of coordinates that defines the polygon. It then takes in a set of points. The idea is to find out how many of these points lie strictly inside the convex polygon (not on the edge or outside). First the program checks if the first set of points form a convex polygon or not. If yes, the program proceeds. Then each point is checked to see if it is strictly inside the convex polygon. If yes, <code>count</code> variable is increased. Here is the code:</p>
<pre><code>#include <iostream>
#include <vector>
// Calculate perpendicular dot product
int perdot(const std::pair<int, int> a, const std::pair<int, int> b, const std::pair<int, int> c)
{
int ab_x = b.first - a.first;
int ab_y = b.second - a.second;
int ac_x = c.first - a.first;
int ac_y = c.second - a.second;
int per_dot = ab_x * ac_y - ab_y * ac_x;
if(per_dot < 0)
{
return -1;
}
else if(per_dot > 0)
{
return 1;
}
else
{
return 0;
}
}
// Check if given set of points form a convex polygon
bool is_convex(const std::vector<std::pair<int, int>>& convex_polygon)
{
int n = convex_polygon.size();
int sense = perdot(convex_polygon[n - 1], convex_polygon[0], convex_polygon[1]);
for(int i = 0; i < n - 1; i++)
{
int new_sense;
if(i == (n - 2))
{
new_sense = perdot(convex_polygon[i], convex_polygon[i + 1], convex_polygon[0]);
}
else
{
new_sense = perdot(convex_polygon[i], convex_polygon[i + 1], convex_polygon[i + 2]);
}
if(sense == 0)
{
sense = new_sense;
}
if(new_sense == (-sense) && sense != 0)
{
return false;
}
}
return true;
}
// Check if a point is STRICTLY inside the convex polygon
bool is_inside(const std::vector<std::pair<int, int>>& convex_polygon, const std::pair<int, int> point)
{
int n = convex_polygon.size();
int sense = perdot(convex_polygon[n - 1], point, convex_polygon[0]);
if(sense == 0)
{
return false;
}
for(int i = 0; i < n - 1; i++)
{
int new_sense;
new_sense = perdot(convex_polygon[i], point, convex_polygon[i + 1]);
if(new_sense == (-sense) || new_sense == 0)
{
return false;
}
}
return true;
}
// Count the number of points STRICTLY inside the convex polygon
int p_inside(const std::vector<std::pair<int, int>>& convex_polygon, const std::vector<std::pair<int, int>>& points)
{
int count = 0;
for(auto point : points)
{
bool inside = is_inside(convex_polygon, point);
if(inside)
{
count++;
}
}
return count;
}
// Main
int main()
{
int k, n;
std::cin >> k >> n;
std::vector<std::pair<int, int>> convex_polygon(k);
std::vector<std::pair<int, int>> points(n);
for(size_t i = 0; i < convex_polygon.size(); i++)
{
int x, y;
std::cin >> x >> y;
convex_polygon[i] = {x, y};
}
bool convex = is_convex(convex_polygon);
if(!convex)
{
std::cout << "Input not convex...Exiting" << std::endl;
return 0;
}
for(size_t i = 0; i < points.size(); i++)
{
int x, y;
std::cin >> x >> y;
points[i] = {x, y};
}
int count = p_inside(convex_polygon, points);
std::cout << "Points inside: " << count << std::endl;
return 0;
}
</code></pre>
<p>1) Should <code>std::pair</code> be passed as reference? Is there an exact criteria to see if a given object is large enough to be passed as reference?</p>
<p>2) Is the use of <code>const</code> correct? </p>
<p>3) What other improvements can be made?</p>
<p>4) I am planning to test it extensively using <code>Catch2</code> framework. I am learning this framework myself. What suggestions do you have to maintain professional test quality?</p>
| [] | [
{
"body": "<p>I'm unfamiliar with the algorithm, so I cannot speak for that.</p>\n\n<h3><code>perdot()</code></h3>\n\n<p>The function can be declared with the <code>constexpr</code> keyword.</p>\n\n<p>When you are passing something by <code>const</code>, if it is not a <a href=\"https://en.cppreference.com/w/cp... | {
"AcceptedAnswerId": "202268",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T00:57:41.103",
"Id": "202264",
"Score": "7",
"Tags": [
"c++",
"unit-testing",
"computational-geometry"
],
"Title": "Program to see how many points lie strictly inside a convex polygon"
} | 202264 |
<p>When G cell divides, it is divided into two G + 1 cells. </p>
<p>In order for the G cell to divide, energy as much as G is required.</p>
<p>What is the minimum energy required to make the total number of cells x?</p>
<p>Input Example (G for each of 2 cells, total number of cells)</p>
<p>1 3 4</p>
<p>Output Example (minimum energy)</p>
<p>3</p>
<p>Input Description
Assuming that there is one cell of the first generation and one cell of the first generation in the beginning, the energy required to make a total of four cells is as follows.
1G 3G -> Generation 1 (Energy 1 required)
2G 2G 3G -> Generation 2 (energy 2 required)
2G 3G 3G 3G (total 4 completed final energy 3)</p>
<p>I've answered the question in C #. </p>
<p>Is there a better way or a way to speed it up?</p>
<p>ex) If Sum is 10 million</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StringBuilder m_strbuilder = new StringBuilder();
List<int> Cells = new List<int>();
int MinIndex = 0;
int Sum = 0;
int FirstCell = 0;
int SecondCell = 0;
bool etc = true;
ulong Result = 0;
string Inputdata = null;
string[] Textdata = null;
while (etc)
{
try
{
Cells.Clear();
Inputdata = Console.ReadLine();
Textdata = Inputdata.Split(' ');
if (Textdata[0] != null && Textdata[1] != null && Textdata[2] != null)
{
int.TryParse(Textdata[0], out FirstCell);
int.TryParse(Textdata[1], out SecondCell);
int.TryParse(Textdata[2], out Sum);
}
else
continue;
if ( 0 < FirstCell && FirstCell <= 10000000)
{
if (0 < SecondCell && SecondCell <= 10000000)
{
if (2 <= Sum && Sum <= 100000000)
etc = false;
else
continue;
}
else
continue;
}
else
continue;
}
catch (ArgumentException e)
{
Console.WriteLine("Unable to add {0}", e.ToString());
}
catch (NullReferenceException e)
{
Console.WriteLine("Unable to add {0}", e.ToString());
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Unable to add {0}", e.ToString());
}
}
Cells.Add(FirstCell);
Cells.Add(SecondCell);
if (Cells[0] > Cells[1])
{
int TempNum = Cells[1];
Cells[1] = Cells[0];
Cells[0] = TempNum;
}
for (int i = 2; i < Sum; i++)
{
Result += (ulong)Cells[MinIndex];
Cells[MinIndex] += 1;
Cells.Insert(MinIndex + 1, Cells[MinIndex]);
if (MinIndex + 1 != Cells.Count - 1)
{
if (Cells[MinIndex + 2] < Cells[MinIndex])
MinIndex = MinIndex + 2;
else
MinIndex = 0;
}
else
MinIndex = 0;
}
m_strbuilder.Append(Result);
Console.WriteLine(m_strbuilder);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T09:29:09.317",
"Id": "389772",
"Score": "2",
"body": "Is this from some (public) programming challenge? In that case it would be helpful to add a link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T... | [
{
"body": "<blockquote>\n<pre><code>namespace ConsoleApplication1\n{ \n class Program\n</code></pre>\n</blockquote>\n\n<p>These names tell no-one anything useful about what the program does, and there's no comment either. If you find this file on your hard drive in a year's time, will you remember what it's ... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T03:37:48.750",
"Id": "202269",
"Score": "0",
"Tags": [
"c#",
"performance",
"algorithm"
],
"Title": "Cell division Solving algorithm problems"
} | 202269 |
<p>Here is the problem description: <a href="https://www.hackerrank.com/challenges/ctci-array-left-rotation" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/ctci-array-left-rotation</a></p>
<blockquote>
<p>A left rotation operation on an array of size \$n\$ shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array \$[1,2,3,4,5]\$, then the array would become \$[3,4,5,1,2]\$.</p>
<p>Given an array of \$n\$ integers and a number, \$d\$, perform \$d\$ left rotations on the array. Then print the updated array as a single line of space-separated integers.</p>
</blockquote>
<p>My code passes all test cases but is stuck on Hacker rank timeout. I want to know where is the part that takes too long to execute, in order to optimize my code.</p>
<pre><code><?php
function rotateOnce($a)
{
if ($a[0] >= 1 && $a[0] <= 1000000) {
$left = array_shift($a);
$a[] = $left;
}
return $a;
}
function checkConstrains($d, $n)
{
if ($d >= 1 && $d <= $n && $n >= 1 && $n <= 10 ^ 5)
return true;
return false;
}
// Complete the rotLeft function below.
function rotLeft($a, $d)
{
global $n;
if (checkConstrains($d, $n)) {
for ($i = 0; $i < $d; $i++) {
$a = rotateOnce($a);
}
}
return $a;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%[^\n]", $nd_temp);
$nd = explode(' ', $nd_temp);
$n = intval($nd[0]);
$d = intval($nd[1]);
fscanf($stdin, "%[^\n]", $a_temp);
$a = array_map('intval', preg_split('/ /', $a_temp, -1, PREG_SPLIT_NO_EMPTY));
$result = rotLeft($a, $d);
fwrite($fptr, implode(" ", $result) . "\n");
fclose($stdin);
fclose($fptr);
</code></pre>
| [] | [
{
"body": "<p>Your code is inefficient. The 3 sample test cases your code passes have small inputs. The actual tests typically have larger inputs.</p>\n\n<p><code>array_shift</code> function needs to re-index the entire array every time you use it. Suppose an array has \\$10^5\\$ elements. And you have to rotat... | {
"AcceptedAnswerId": "202284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T03:54:49.623",
"Id": "202270",
"Score": "2",
"Tags": [
"php",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Hacker rank - Left rotation - PHP code feedback for Timeout"
} | 202270 |
<p><a href="https://i.stack.imgur.com/S88Zl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S88Zl.png" alt="overview"></a></p>
<p>So I have two lists which have the same size. One is called roadS and the second one is called simTime. My aim is to calculate the difference between two indexes which lie next to each other and divide them with the difference of the other list. On the picture above you see what I mean. </p>
<p>This is my current function:</p>
<pre><code>public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS){
List<Double> speedS = new ArrayList<>();
for(int idx = 1; idx < roadS.size();idx++){
double curSpeedS = (roadS.get(idx)-roadS.get(idx-1))/(simTime.get(idx)-simTime.get(idx-1));
speedS.add(curSpeedS);
}
return speedS;
}
</code></pre>
<p>Now although the function is quite short, I aim to find a better or faster solution.</p>
<p>For eg. in phyton you could you <code>pantas</code> library and do this:</p>
<pre><code>player.df['speedS'] = player.df.roadS.diff().shift(-1) / player.df.simTime.diff().shift(-1)
</code></pre>
<p>My aim is to solve this problem more efficient. Does Java or another library maybe provide such functions where I can for calculate the differences </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T10:41:08.047",
"Id": "389798",
"Score": "0",
"body": "To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);"
}
] | [
{
"body": "<p>To simplify <code>speed</code> collection creation logic you can replace actual values in <code>roadS</code> and <code>simTime</code> with the corresponding differences, e.g.:<br><br>\n<code>roadS = {2, 0, 2, 1}</code><br>\n<code>simTime= {3, 1, 1, 1}</code><br><br>\nThen you can use one of the ex... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T07:51:54.553",
"Id": "202286",
"Score": "1",
"Tags": [
"java",
"performance",
"calculator"
],
"Title": "Calculate the difference between the elements in a list"
} | 202286 |
<p>We have to calculate a lot of different fixed factors with user input values.
Every single calculation has a different min value.</p>
<p>This block of code</p>
<pre><code>result.Calculation_VK = input.km_past_year * 0.040m;
if (result.Calculation_VK <= 300)
result.Calculation_VK = 300;
result.Calculation_VK *= Constant.MWST;
</code></pre>
<p>Is repeated over and over again with different constant factors and input variables. My question is, is it possible to simplify the lines</p>
<pre><code>if (result.Calculation_VK <= 300)
result.Calculation_VK = 300;
</code></pre>
<p>while still keeping the code readable?</p>
<p>We tried working with the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator" rel="nofollow noreferrer"><code>?</code> Operator</a>, but this doens't really clean up the code. Especially considering that these lines will be repeated over and over again.</p>
<pre><code>result.Calculation_VK = input.km_past_year * 0.040m <= 300 ? 300 : result.Calculation_VK * 0.040m;
result.Calculation_VK *= Constant.MWST;
</code></pre>
<p>I thought about creating properties with default values inside the getters. But as we are using common and reusable objects that are shared over several classes and methods it would lead to creating objects for each single method.</p>
<p>For my understanding this would nullify the advantage of using objects to pass needed values into our calculations.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T08:22:28.307",
"Id": "389758",
"Score": "0",
"body": "Why do you want to simplify it? It's clear, it's simple and it won't break."
}
] | [
{
"body": "<p>Well, the most simple way would be to use Math.Max() like so </p>\n\n<pre><code>result.Calculation_VK = Math.Max(input.km_past_year * 0.040m, 300) * Constant.MWST \n</code></pre>\n\n<p>which could be as well in a method like </p>\n\n<pre><code>public static decimal CalculateVK(decimal pastYear,... | {
"AcceptedAnswerId": "202289",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T08:12:48.083",
"Id": "202288",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Simplifying calculation with min value in C#"
} | 202288 |
<p>I implemented a binary expression tree, I've used <a href="https://codereview.stackexchange.com/questions/201232/shunting-yard-algorithm">my previous shunting-yard parser</a> to provide it the post-fix expression. </p>
<p>I have a few specific questions outside of just comments about making it more pythonic:</p>
<ul>
<li><p>Should I check the type when assigning <code>left</code> and <code>right</code> nodes? I read that type checking is usually discouraged (<a href="https://stackoverflow.com/a/6725913/1693004">https://stackoverflow.com/a/6725913/1693004</a>), but the <code>Node</code> class is inside the binary_expression_tree module.</p></li>
<li><p>Should the <code>BinaryExpressionTree</code> constructor take in the post-fix token expression from the shunting yard parser, or should it take in an infix expression and convert it internally?</p></li>
</ul>
<p>Code:</p>
<pre><code>import shunting_yard_parser
class Node:
_left = None
_right = None
_token = None
def __init__(self, token):
self._token = token
@property
def left(self):
return self._left
@left.setter
def left(self, value):
if not isinstance(value, Node):
raise TypeError("Left node must be of type Node")
self._left = value
@property
def right(self):
return self._right
@right.setter
def right(self, value):
if not isinstance(value, Node):
raise TypeError("Right node must be of type Node")
self._right = value
@property
def token(self):
return self._token
class BinaryExpressionTree:
_root = None
def __init__(self, postfix_tokens):
stack = list()
for token in postfix_tokens:
if token.kind == shunting_yard_parser.TokenSpecification.OPERAND:
stack.append(Node(token))
if token.kind == shunting_yard_parser.TokenSpecification.OPERATOR:
operator_node = Node(token)
if len(stack) < 2:
raise TypeError('Incorrectly formatted expression - check operators.')
operator_node.right = stack.pop()
operator_node.left = stack.pop()
stack.append(operator_node)
if len(stack) > 1:
raise TypeError('Incorrectly formatted expression - check operands.')
self._root = stack.pop()
def solve(self):
assert self._root is not None
return self._solve(self._root)
@staticmethod
def _solve(node):
if node.token.kind == shunting_yard_parser.TokenSpecification.OPERAND:
return int(node.token.value)
left_value = BinaryExpressionTree._solve(node.left)
right_value = BinaryExpressionTree._solve(node.right)
operator = node.token.value
if operator == '+':
return left_value + right_value
if operator == '-':
return left_value - right_value
if operator == '*':
return left_value * right_value
if operator == '/':
return left_value / right_value
if __name__ == "__main__":
while True:
infix_expression = input('Enter infix expression:')
postfix_expression = ""
try:
postfix_expression = shunting_yard_parser.parse(infix_expression)
except ValueError as e:
print(e)
if postfix_expression != "":
binaryExpressionTree = BinaryExpressionTree(postfix_expression)
solution = binaryExpressionTree.solve()
print(solution)
</code></pre>
<p>Unit tests:</p>
<pre><code>from unittest import TestCase
import binary_expression_tree
import shunting_yard_parser
class TestBinaryExpressionTree(TestCase):
def test_only_operands(self):
# arrange
postfix_expression = [shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERAND, '2'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERAND, '5')]
# act & assert
self.assertRaises(TypeError, lambda: binary_expression_tree.BinaryExpressionTree(postfix_expression))
def test_only_operators(self):
# arrange
postfix_expression = [shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERATOR, '+'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERATOR, '*')]
# act & assert
self.assertRaises(TypeError, lambda: binary_expression_tree.BinaryExpressionTree(postfix_expression))
def test_unbalanced_expression(self):
# arrange
postfix_expression = [shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERAND, '2'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERATOR, '+'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERATOR, '*')]
# act & assert
self.assertRaises(TypeError, lambda: binary_expression_tree.BinaryExpressionTree(postfix_expression))
def test_balanced_expression(self):
# arrange
postfix_expression = [shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERAND, '2'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERAND, '5'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERATOR, '+'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERAND, '10'),
shunting_yard_parser.Token(shunting_yard_parser.TokenSpecification.OPERATOR, '*')]
# act
tree = binary_expression_tree.BinaryExpressionTree(postfix_expression)
# assert
result = tree.solve()
self.assertEqual(70, result)
</code></pre>
<p>Shunting-yard algorithm (only for reference, already reviewed):</p>
<pre><code>from collections import namedtuple, deque
from enum import Enum
import re
class TokenSpecification(Enum):
PARENTHESES = 1
OPERAND = 2
OPERATOR = 3
IGNORE = 4
JUNK = 5
class Token(namedtuple("Token", "kind value")):
_operatorPrecedence = {"*": 3,
"/": 3,
"+": 2,
"-": 2}
@property
def precedence(self):
if self.kind == TokenSpecification.OPERATOR:
return self._operatorPrecedence[self.value]
else:
raise TypeError("")
def _tokenize(expression):
token_specification = [
(TokenSpecification.PARENTHESES.name, r'[()]'),
(TokenSpecification.OPERAND.name, r'\d+'),
(TokenSpecification.OPERATOR.name, r'[+\-*/]'),
(TokenSpecification.IGNORE.name, r'\s+'),
(TokenSpecification.JUNK.name, r'\S+?\b')
]
tokenizer_regex = '|'.join('(?P<{kind}>{pattern})'.format(kind=kind, pattern=pattern)
for kind, pattern in token_specification)
tokenizer = re.compile(tokenizer_regex)
for match in tokenizer.finditer(expression):
kind = match.lastgroup
value = match.group(kind)
if kind == TokenSpecification.JUNK:
raise ValueError('Unrecognized token: {0}'.format(value))
elif kind != TokenSpecification.IGNORE:
yield Token(TokenSpecification[kind], value)
def parse(infix_expression):
operators = deque()
for token in _tokenize(infix_expression):
if token.kind == TokenSpecification.OPERAND:
yield token
elif token.kind == TokenSpecification.OPERATOR:
while (operators
and operators[0].value != '('
and operators[0].precedence >= token.precedence):
yield operators.popleft()
operators.appendleft(token)
elif token.value == '(':
operators.appendleft(token)
elif token.value == ')':
# Pop all the operators in front of the "(".
while operators and operators[0].value != '(':
yield operators.popleft()
# The previous operation would have removed all the operators
# because there is no matching opening parenthesises.
if not operators:
raise ValueError('Unmatched )')
# Remove matching parenthesis.
operators.popleft()
for operator in operators:
# If there are still opening parenthesises in the stack this means
# we haven't found a matching closing one.
if operator.value == '(':
raise ValueError('Unmatched (')
yield operator
if __name__ == "__main__":
while True:
action = input('Enter infix expression:')
try:
postfix_expression = parse(action)
print([op.value for op in postfix_expression])
except ValueError as e:
print(e.args)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T09:02:25.013",
"Id": "202293",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"math-expression-eval"
],
"Title": "Binary Expression Tree"
} | 202293 |
<p>We have an MVC application, which performs actions on a referral. We are added the business logic, to ensure that we can't perform invalid actions on the referral due to it not being in the correct state. We have something that works, but it looks pretty smelly, however we are unsure how to improve it. </p>
<p>I feel like there <strong>has to be a better way</strong>. Any ideas how to improve the <strong>mass of if</strong> checks in the <strong>CanPerformEvent method</strong>? Thanks.</p>
<pre class="lang-c# prettyprint-override"><code>public abstract class ReferralTask : IReferralTask
{
public async Task<bool> RunAsync()
{
Validate();
var success = await RunTaskAsync();
await LogEventAsync(success);
return success;
}
protected void Validate()
{
if (!Referral.CanPerformEvent(Event))
{
throw new InvalidReferralStateException(Referral.Id, Event, Referral.ValidNextEvents());
}
OnValidate();
}
}
public abstract class Referral
{
public bool CanPerformEvent(ReferralEventEnum referralEvent)
{
var validNextEvents = ValidNextEvents();
return validNextEvents.Contains(referralEvent);
}
public ReferralEventEnum[] ValidNextEvents()
{
// Get all the successful events for the referral.
var successfulEvents = ReferralHistory
.Where(h => h.Successful)
.Select(h => h.EventId)
.ToList();
// Initialise list for valid next events.
var validNextEvents = new List<ReferralEventEnum>();
// If the request has been recieved by the portal...
if (successfulEvents.Contains(ReferralEventEnum.RequestReceived))
{
// ...but not completed, it can be completed.
if (!successfulEvents.Contains(ReferralEventEnum.RequestCompleted))
{
validNextEvents.Add(ReferralEventEnum.RequestCompleted);
}
// ...but not notified, a notification can be sent.
if (!successfulEvents.Contains(ReferralEventEnum.RequestNotificationSent))
{
validNextEvents.Add(ReferralEventEnum.RequestNotificationSent);
}
}
// If request completed and not accepted or refused, it can be accepted or refused.
if (successfulEvents.Contains(ReferralEventEnum.RequestCompleted) &&
!successfulEvents.Contains(ReferralEventEnum.ReferralAcceptedInPortal) &&
!successfulEvents.Contains(ReferralEventEnum.ReferralRefusedInPortal))
{
validNextEvents.Add(ReferralEventEnum.ReferralAcceptedInPortal);
validNextEvents.Add(ReferralEventEnum.ReferralRefusedInPortal);
}
// If the referral has been accepted in the portal...
if (successfulEvents.Contains(ReferralEventEnum.ReferralAcceptedInPortal))
{
// ...but the acceptance request hasn't been sent, it can be sent.
if (!successfulEvents.Contains(ReferralEventEnum.ReferralAcceptedRequestSent))
{
validNextEvents.Add(ReferralEventEnum.ReferralAcceptedRequestSent);
}
// ...but provider update form not created, it can be created.
if (!successfulEvents.Contains(ReferralEventEnum.ReferralAcceptedFormCreated))
{
validNextEvents.Add(ReferralEventEnum.ReferralAcceptedFormCreated);
}
// ...and not updated or failed, it can be updated, delayed and failed.
if (!successfulEvents.Contains(ReferralEventEnum.ReferralUpdatedInPortal) &&
!successfulEvents.Contains(ReferralEventEnum.ReferralFailedInPortal))
{
validNextEvents.Add(ReferralEventEnum.ReferralUpdatedInPortal);
validNextEvents.Add(ReferralEventEnum.ReferralFailedInPortal);
// If all delays have been successfully completed, can delay again.
if (successfulEvents.Count(x => x == ReferralEventEnum.ReferralDelayInPortal) ==
successfulEvents.Count(x => x == ReferralEventEnum.ReferralDelayRequestSent))
{
validNextEvents.Add(ReferralEventEnum.ReferralDelayInPortal);
}
}
}
// If refused in portal but request not sent, can send request.
if (successfulEvents.Contains(ReferralEventEnum.ReferralRefusedInPortal) &&
!successfulEvents.Contains(ReferralEventEnum.ReferralRefused))
{
validNextEvents.Add(ReferralEventEnum.ReferralRefused);
}
// If refusal request sent, but the referral hasn't been removed, it can be removed.
if (successfulEvents.Contains(ReferralEventEnum.ReferralRefused) &&
!successfulEvents.Contains(ReferralEventEnum.RemovedFromPortal))
{
validNextEvents.Add(ReferralEventEnum.RemovedFromPortal);
}
// If the referral has had a failed service start in the portal
if (successfulEvents.Contains(ReferralEventEnum.ReferralFailedInPortal))
{
// ...but the form hasn't been updated, it can be updated.
if (!successfulEvents.Contains(ReferralEventEnum.FailedServiceStartFormUpdated))
{
validNextEvents.Add(ReferralEventEnum.FailedServiceStartFormUpdated);
}
// ...but failed service start request not sent, it can be sent.
if (!successfulEvents.Contains(ReferralEventEnum.FailedServiceStartRequestSent))
{
validNextEvents.Add(ReferralEventEnum.FailedServiceStartRequestSent);
}
}
// If the failed service start request has been sent and form is created, but the referral hasn't been removed, it can be removed.
if (successfulEvents.Contains(ReferralEventEnum.FailedServiceStartRequestSent) &&
successfulEvents.Contains(ReferralEventEnum.FailedServiceStartFormUpdated) &&
!successfulEvents.Contains(ReferralEventEnum.RemovedFromPortal))
{
validNextEvents.Add(ReferralEventEnum.RemovedFromPortal);
}
// If not every delay in portal has had its request sent, can send the delay in portal request.
if (successfulEvents.Count(x => x == ReferralEventEnum.ReferralDelayInPortal) >
successfulEvents.Count(x => x == ReferralEventEnum.ReferralDelayRequestSent))
{
validNextEvents.Add(ReferralEventEnum.ReferralDelayRequestSent);
}
// If the referral has been updated in the portal
if (successfulEvents.Contains(ReferralEventEnum.ReferralUpdatedInPortal))
{
// ...but not sent request, can send request.
if (!successfulEvents.Contains(ReferralEventEnum.UpdateCompletedRequestSent))
{
validNextEvents.Add(ReferralEventEnum.UpdateCompletedRequestSent);
}
// ...but not created form, can create form.
if (!successfulEvents.Contains(ReferralEventEnum.UpdateCompleted))
{
validNextEvents.Add(ReferralEventEnum.UpdateCompleted);
}
// ...and not submitted actuals, can submit actuals.
if (!successfulEvents.Contains(ReferralEventEnum.ProvideActualsInPortal))
{
validNextEvents.Add(ReferralEventEnum.ProvideActualsInPortal);
}
}
// If submitted actuals in portal and not created step, can create step.
if (successfulEvents.Contains(ReferralEventEnum.ProvideActualsInPortal) &&
!successfulEvents.Contains(ReferralEventEnum.ProviderActualsStepCreated))
{
validNextEvents.Add(ReferralEventEnum.ProviderActualsStepCreated);
}
// If actuals have been sent, the referral can be removed from the portal.
if (successfulEvents.Contains(ReferralEventEnum.ProviderActualsStepCreated) &&
!successfulEvents.Contains(ReferralEventEnum.RemovedFromPortal))
{
validNextEvents.Add(ReferralEventEnum.RemovedFromPortal);
}
return validNextEvents.ToArray();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T12:48:07.267",
"Id": "389803",
"Score": "1",
"body": "Would State design pattern be a good move?"
}
] | [
{
"body": "<p>Depending on you effort you want to put in your redesing, you coud use some kind of <a href=\"https://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow noreferrer\">state pattern</a>, and therefore just kow the valid events, instead of calculating them every time.</p>\n\n<p>Or you just simply t... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T10:11:02.400",
"Id": "202295",
"Score": "1",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Validation in BLL, many ifs - Suggestions how to refactor what I think looks smelly"
} | 202295 |
<p>I have create one class and interface for finding SuburbName based on Location or LatLong coordinates.</p>
<p>My interface</p>
<pre><code>public interface IGeoCodeService
{
string GetSuburbName(double latitude, double longitude);
string GetSuburbName(string location);
string GetGoogleStaticMapImageUrl(string location);
}
</code></pre>
<p>My Class</p>
<pre><code>public class GeoCodeService : IGeoCodeService
{
private static readonly string GoogleApiKey = "*****MyAPI KEY*****";
private static readonly string GoogleStaticMapUrl = "http://maps.googleapis.com/maps/api/staticmap";
public string GetSuburbName(string location)
{
if (!string.IsNullOrEmpty(location))
{
using (var clientService = new HttpClientService<GeoCodeResponse>("https://maps.googleapis.com"))
{
var param = new Dictionary<string, string>();
param.Add("address", location);
param.Add("components", "country:AU");
param.Add("result_type", "locality");
param.Add("key", GoogleApiKey);
var apiResult = clientService.GetAPI("maps/api/geocode/json", param);
return FindSuburbName(apiResult);
}
}
return string.Empty;
}
public string GetSuburbName(double latitude, double longitude)
{
using (var clientService = new HttpClientService<GeoCodeResponse>("https://maps.googleapis.com"))
{
var param = new Dictionary<string, string>();
param.Add("latlng", $"{latitude},{longitude}");
param.Add("result_type", "locality");
param.Add("key", GoogleApiKey);
var apiResult = clientService.GetAPI("maps/api/geocode/json", param);
return FindSuburbName(apiResult);
}
}
private string FindSuburbName(GeoCodeResponse result)
{
var response = string.Empty;
if (result != null || result.results != null && result.results.Count > 0)
{
var addressObj = result.results.FirstOrDefault();
if (addressObj != null)
{
var component = addressObj.AddressComponents.Where(x => x.Types.Contains("locality")).FirstOrDefault();
if (component != null)
{
return component.LongName;
}
}
}
return response;
}
public string GetGoogleStaticMapImageUrl(string location)
{
return $"{GoogleStaticMapUrl}?size=350x200&markers={location}";
}
}
</code></pre>
<p>And lastly the <code>GeoCodeResponse</code> class to store response from the google api call.</p>
<pre><code>public class GeoCodeResponse
{
[JsonProperty("results")]
public List<Results> results { get; set; }
[JsonProperty("status")]
public string status { get; set; }
}
public class Results
{
public Results()
{
AddressComponents = new List<AddressComponent>();
}
[JsonProperty("address_components")]
public List<AddressComponent> AddressComponents { get; set; }
}
public class AddressComponent
{
[JsonProperty("long_name")]
public string LongName { get; set; }
[JsonProperty("short_name")]
public string ShortName { get; set; }
[JsonProperty("types")]
public string[] Types { get; set; }
}
</code></pre>
<p>Can you please suggest me if what I have implemented is right or require any change. Your help will improve my code quality.</p>
<p>The <a href="https://codereview.stackexchange.com/questions/186303/generic-implementation-for-api-call-in-c">HttpClientService</a> class is used for call api </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T14:42:22.343",
"Id": "389829",
"Score": "0",
"body": "Please include the `HttpClientService` class even if it's already been reviewed. You never know what someone else can find :)"
}
] | [
{
"body": "<p>I would reccomend using <code>string.IsNullOrWhitespace(..)</code> instead of <code>string.IsNullOrEmpty(..)</code>, but this depends on how you call your method and what input is possible.\nAlso I prefer returning early, instead of having all my actual code in an if-block:</p>\n\n<pre><code>publ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T11:32:18.303",
"Id": "202299",
"Score": "4",
"Tags": [
"c#",
"beginner",
"object-oriented",
"geospatial",
"google-maps"
],
"Title": "Find SuburbName from latlong or location"
} | 202299 |
<p><strong>Introduction</strong></p>
<p>This simple data structure combines <code>ArrayList</code> with <code>LinkedList</code>. In other words, it is a linked list of arrays:</p>
<p><a href="https://i.stack.imgur.com/3Qvtk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Qvtk.png" alt="LinkedBlockList"></a></p>
<p><strong>Code</strong></p>
<pre><code>package net.coderodde.util.experimental;
/**
* This class implements an experimental linked list data structure that
* combines linked list with array-based list.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 22, 2018)
*/
public final class LinkedBlockList<T> {
private static final int DEFAULT_BLOCK_CAPACITY = 64;
private static final int MINIMUM_BLOCK_CAPACITY = 4;
/**
* This static inner class implements the actual blocks storing the
* elements.
*
* @param <T> the element type.
*/
private static final class Block<T> {
/**
* The length of {@code array}.
*/
final int capacity;
/**
* The mask used for modulo computation.
*/
final int indexMask;
/**
* The number of elements in this block.
*/
int size;
/**
* The index of the very first element in this block.
*/
int headIndex;
/**
* The array holding all the elements belonging to this block.
*/
T[] array;
/**
* The previous block.
*/
Block<T> previousBlock;
/**
* The next block.
*/
Block<T> nextBlock;
Block(int capacity) {
this.capacity = capacity;
this.indexMask = capacity - 1;
this.array = (T[]) new Object[capacity];
}
T get(int logicalIndex) {
return array[(headIndex + logicalIndex) & indexMask];
}
void setNull(int logicalIndex) {
array[(headIndex + logicalIndex) & indexMask] = null;
}
}
/**
* The number of elements in this list.
*/
private int size;
/**
* The number of blocks contained by this list.
*/
private int blocks;
/**
* The first block in the chain.
*/
private Block<T> headBlock;
/**
* The last block in the chain.
*/
private Block<T> tailBlock;
/**
* The block capacity.
*/
private int blockCapacity;
/**
* The mask used for index computation.
*/
private int indexMask;
public LinkedBlockList(int blockCapacity) {
blockCapacity = Math.max(blockCapacity, MINIMUM_BLOCK_CAPACITY);
blockCapacity = ceilToPowerOfTwo(blockCapacity);
this.blockCapacity = blockCapacity;
this.indexMask = blockCapacity - 1;
}
public LinkedBlockList() {
this(DEFAULT_BLOCK_CAPACITY);
}
public void add(int index, T element) {
checkAddIndex(index);
if (size == 0) {
headBlock = new Block<>(blockCapacity);
tailBlock = headBlock;
headBlock.array[0] = element;
headBlock.size = 1;
size = 1;
return;
}
Block<T> block = headBlock;
while (index > block.size) {
index -= block.size;
block = block.nextBlock;
}
if (block.size == block.capacity) {
// Create a new block and move to it as little elements as possible:
int elementsOnLeft = index;
int elementsOnRight = block.size - index;
Block<T> newBlock = new Block<>(blockCapacity);
if (elementsOnLeft < elementsOnRight) {
// Add newBlock before block and move to it the prefix of the
// current block and append the new element:
for (int newBlockIndex = 0;
newBlockIndex < elementsOnLeft;
newBlockIndex++) {
newBlock.array[newBlockIndex] = block.get(newBlockIndex);
block.setNull(newBlockIndex);
}
newBlock.array[elementsOnLeft] = element;
newBlock.size = elementsOnLeft + 1;
newBlock.nextBlock = block;
newBlock.previousBlock = block.previousBlock;
block.previousBlock = newBlock;
block.size -= elementsOnLeft;
block.headIndex =
(block.headIndex + elementsOnLeft) & indexMask;
if (newBlock.previousBlock == null) {
headBlock = newBlock;
} else {
newBlock.previousBlock.nextBlock = newBlock;
}
} else {
block.size -= elementsOnRight;
newBlock.array[0] = element;
int targetIndex = 1;
for (int newBlockIndex = index;
newBlockIndex < elementsOnRight;
newBlockIndex++) {
newBlock.array[targetIndex] = block.get(newBlockIndex);
block.setNull(newBlockIndex);
targetIndex++;
}
newBlock.size = elementsOnRight + 1;
newBlock.previousBlock = block;
newBlock.nextBlock = block.nextBlock;
block.nextBlock = newBlock;
if (newBlock.nextBlock == null) {
tailBlock = newBlock;
} else {
newBlock.nextBlock.previousBlock = newBlock;
}
}
} else {
// The current block is not full so insert into it:
int elementsOnLeft = index;
int elementsOnRight = block.size - index;
if (elementsOnLeft < elementsOnRight) {
// Shift the leftmost elements one position to the left:
for (int elementIndex = 0;
elementIndex < elementsOnLeft;
elementIndex++) {
int sourceIndex =
(block.headIndex + elementIndex)
& indexMask;
int targetIndex =
(block.headIndex + elementIndex - 1)
& indexMask;
block.array[targetIndex] = block.array[sourceIndex];
}
block.array[(block.headIndex + index - 1) & indexMask] =
element;
block.headIndex = (block.headIndex - 1) & indexMask;
block.size++;
} else {
// Shift the rightmost elements one position to the right:
for (int elementIndex = 0;
elementIndex < elementsOnRight;
elementIndex++) {
int sourceIndex =
(block.headIndex + block.size - elementIndex - 1)
& indexMask;
int targetIndex =
(block.headIndex + block.size - elementIndex)
& indexMask;
block.array[targetIndex] = block.array[sourceIndex];
}
block.array[(block.headIndex + index) & indexMask] = element;
block.size++;
}
}
size++;
}
public T get(int index) {
checkAccessIndex(index);
Block<T> block = headBlock;
while (index >= block.size) {
index -= block.size;
block = block.nextBlock;
}
return block.get(index);
}
public void remove(int index) {
checkAccessIndex(index);
Block<T> targetBlock = headBlock;
while (index >= targetBlock.size) {
index -= targetBlock.size;
targetBlock = targetBlock.nextBlock;
}
if (targetBlock.size == 1) {
// The target block contains only one element. Unlink it from the
// chain of blocks:
if (targetBlock == headBlock) {
headBlock = headBlock.nextBlock;
if (headBlock != null) {
headBlock.previousBlock = null;
}
} else {
targetBlock.previousBlock.nextBlock = targetBlock.nextBlock;
}
if (targetBlock == tailBlock) {
tailBlock = tailBlock.previousBlock;
if (tailBlock != null) {
tailBlock.nextBlock = null;
}
} else {
targetBlock.nextBlock.previousBlock = targetBlock.previousBlock;
}
} else {
int elementsOnLeft = index;
int elementsOnRight = targetBlock.size - index - 1;
if (elementsOnLeft < elementsOnRight) {
// Shift the leftmost elements in the target block one position
// to the right:
for (int i = index - 1; i >= 0; i--) {
int sourceIndex = (targetBlock.headIndex + i) & indexMask;
int targetIndex = (targetBlock.headIndex + i + 1)
& indexMask;
targetBlock.array[targetIndex] =
targetBlock.array[sourceIndex];
}
targetBlock.setNull(0);
targetBlock.headIndex = (targetBlock.headIndex + 1) & indexMask;
targetBlock.size--;
} else {
// Shift the rightmost elements in the target block one position
// to the left:
for (int i = index + 1; i < targetBlock.size; i++) {
int sourceIndex = (targetBlock.headIndex + i) & indexMask;
int targetIndex = (targetBlock.headIndex + i - 1)
& indexMask;
targetBlock.array[targetIndex] =
targetBlock.array[sourceIndex];
}
targetBlock.size--;
targetBlock.setNull(targetBlock.size);
}
}
size--;
}
public int size() {
return size;
}
/**
* Returns a number between zero and one indicating how densely the blocks
* are.
*
* @return density factor.
*/
public float getDensityFactor() {
return ((float) size) / blocks * blockCapacity;
}
private void checkAccessIndex(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("index(" + index + ") < 0");
}
if (index >= size) {
throw new IndexOutOfBoundsException(
"index(" + index + ") >= (" + size + ")");
}
}
private void checkAddIndex(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("index(" + index + ") < 0");
}
if (index > size) {
throw new IndexOutOfBoundsException(
"index(" + index + ") > (" + size + ")");
}
}
private static int ceilToPowerOfTwo(int number) {
int ret = 1;
while (ret < number) {
ret <<= 1;
}
return ret;
}
}
</code></pre>
<p><strong>Performance figures</strong></p>
<blockquote>
<pre>
<code>
LinkedBlockList.add in 106 ms.
LinkedBlockList.get in 214 ms.
LinkedBlockList.remove in 223 ms.
LinkedBlockList total time: 543 ms.
LinkedList.add in 4810 ms.
LinkedList.get in 13839 ms.
LinkedList.remove in 7292 ms.
LinkedList total time: 25941 ms.
</code>
</pre>
</blockquote>
<p>See <a href="https://github.com/coderodde/LinkedBlockList" rel="nofollow noreferrer">GitHub</a> for pseudo-benchmark and unit tests.</p>
<p>Any critique is much appreciated.</p>
| [] | [
{
"body": "<p>Unneeded is</p>\n\n<ul>\n<li><code>Block.capacity</code> - at one spot simply use <code>blockCapacity</code>.</li>\n</ul>\n\n<p>Still a bug:</p>\n\n<pre><code> for (int newBlockIndex = index; \n newBlockIndex < elementsOnRight;\n</code></pre>\n\n<p>should be (I th... | {
"AcceptedAnswerId": "202324",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T12:15:34.920",
"Id": "202301",
"Score": "0",
"Tags": [
"java",
"performance",
"array",
"linked-list"
],
"Title": "A simple linked list of arrays in Java"
} | 202301 |
<p>I recently posted a <a href="https://codereview.stackexchange.com/questions/201740/hex-dump-utility-in-x86-64-assembly-under-linux">code review</a> and received some very useful feedback. I have spent some time implementing the suggested improvements/fixes, and wish to post a follow up review, with the new and improved version of the program. </p>
<hr>
<h3>Changes Made:</h3>
<p><strong>Comments Section(s)</strong>:</p>
<p>I have added an additional ‘Register Use’ section to the comments block, at the header of the main program. The section describes how the main registers are used through-out the main program. For information regarding individual procedures/macros, please see the relevant header sections. </p>
<p>In addition, I have taken onboard the feedback with regards to line length. Originally, some lines of source code were in excess of 200 columns. All lines now wrap at a column count of 80. </p>
<p><strong>Fix the Bug - One:</strong></p>
<p>The main fault with the program was that it had a fatal bug. In short, the program had originally attempted to create the entirety of its output in a relative small memory reserve of 64K. The fix was given in the accepted answer to the original question. By handling the data one line at a time, the program would only require a small memory reserve, as each line of data would be written to the console, prior to the subsequent read from file. This also had the added benefit of reducing the amount of necessary data processing, as I was able to declare the output line formatting (vertical bars etc.) in memory, as data, as opposed to implementing the formatting by way of code.</p>
<p>As a general note, the reason I chose not to structure the code in this manner in the first instance, was because I was attempting to write the most efficient code possible. My concern was that, by handling data one line at a time, I would unnecessarily be increasing the number of system calls, in this instance <code>sys_write</code> calls, and consequently my program would be slower overall. Ultimately though, efficiency is not of significance, if the program does not work to begin with!</p>
<p><strong>Fix the Bug – Two:</strong></p>
<p>Procedure 'CharToHex' had originally assumed that the high bytes of <code>EAX</code> and <code>EBX</code> were zero (thanks to @1201ProgramAlarm). Whilst looking up the individual nibbles of the input chars, in lookup-table 'Digits', if the high bytes were in fact nonzero, then the procedure may have ended up referencing memory out of bounds. Or, at the very least, it would most certainly have not been pointing to the correct table address. The fix was to clear both registers at the start of the procedure, using <code>XOR</code>. </p>
<p><strong>Measurements / Testing:</strong></p>
<p>I tested the program, both before and after the restructure, using the <code>strace</code> utility. My prediction was that by handling the data one line at a time, the program would be notably slower; this has to be the case, as system calls can not have a zero cost.</p>
<p>I measured the average execution time, by running each version of the program through <code>strace</code> ten times, recording each result, and then by taking the average of the ten measurements. N.B. I appreciate my measurements are somewhat crude.</p>
<p>The results show that on average, the program, as originally constructed, took <code>0.0199</code> seconds to execute. Using the same test data, the average time taken for the program to execute, after the restructuring (i.e. handling data one line at a time), was <code>0.0700</code> seconds. Therefore, handling the data one line at a time does indeed slow down the program. The program is now, roughly, three and a half times slower. This is as expected.</p>
<p><strong>Avoid Slow Instructions:</strong></p>
<p>I have significantly changed the procedure ‘ConvertControlChars’. There were two main reasons to do so. Firstly, the procedure originally made use of a translation table, to convert any non-printable ASCII characters in the ‘InputBuff’ string, to printable ASCII period characters (2Eh). To implement this functionality, the program utilized the <code>XLAT</code> instruction, in order to scan the string and convert any relevant chars. As pointed out in the original review, <code>XLAT</code> is a relatively slow instruction, <a href="https://www.agner.org/optimize/instruction_tables.pdf" rel="nofollow noreferrer">Agner Fog's</a> instruction tables, show that this is indeed in the case. <code>XLAT</code> also demands the use of implicit operands/registers, which can be somewhat limiting, and can require additional processing, if the demanded registers are already in use. </p>
<p>The same result is now achieved through the implementation of a conditional loop. The loop scans the ‘InputBuff’ string, and by using the <code>CMP</code> instruction, decides on whether or not the char requires conversion. The outcome is that the size of the procedure has been reduced from a total of 16 instructions, to 12. Moreover, it avoids the use of the relatively slow <code>XLAT</code> instruction. </p>
<p>The translation table, <code>PeriodXLat</code>, has also been removed, as it is surplus to requirements. This reduces the overall program size by a minimum of 256 bytes; the number of declared bytes in the table. </p>
<p><strong>Use Fast Instructions:</strong></p>
<p>The section of code, that handles the processing of the output line padding, as also been restructured. I have reduced the necessary instruction count from 16 to 7, a significant saving. This has mainly be achieved by removing the conditional loops ‘CharPadding’ and ‘RowBuffer’, and replacing them with a simple <code>STOSB</code> instruction. </p>
<p><strong>Use of the Stack</strong></p>
<p>I have reduced the total number of push/pop instructions by 8. </p>
<p><strong>Be wary of using <code>RBP</code> as a data pointer:</strong></p>
<p>The original program made heavy use of the <code>EBP</code> register as a data pointer. As kindly pointed out, this is not generally good practice, as its usual use is as a stack frame pointer. Using the register in this manner can lead to potential issues. The program now uses <code>EBX</code> as a pointer instead. </p>
<p><strong>Rethink Error Handling</strong></p>
<p>Error messages are now written to <code>stderr</code> as opposed to <code>stdout</code>, as can be seen in the changes made to the ‘ErrorHandler’ macro. I have also updated the header section of this particular macro, to more accurately reflect the macros purpose and use of registers. </p>
<hr>
<h3>Changes Not Implemented:</h3>
<p><strong>Use Memory Efficiently:</strong></p>
<p>One suggested improvement, was to eliminate the necessity of separate input and output buffers, by reading data directly into place, and carrying out the necessary processing from within the one memory buffer. However, I do not think that this is possible, as for each byte read from file, two bytes are written to stdout. Attempting to convert the characters <em>in situ</em>, would mean overwriting the second character, during the conversion of the first, and so on and so forth. For example, when reading char “A” from file, the underlying binary stored in memory, is 41h, one byte. In order to print “41” to the terminal, the single byte read from file, is converted to two bytes, 3431h. If the conversion was done ‘in place’, the byte 31h would overwrite the second byte read from file, before it had been processed. </p>
<hr>
<h3>Review Request:</h3>
<p>I believe my program is now bug free. I have tested it more thoroughly this time, using much larger files. Again, though, I would very much appreciate someone with the requisite knowledge pointing out my ignorance, if I happen to be incorrect. </p>
<p>I would also appreciate a general critique; what areas of code would you consider still require improvement; what fine-tuning, if any, can still be made; and, importantly, are there any particular areas where you would have done things differently, and why. </p>
<p>Ultimately, I am trying to learn as much as possible, text books etc. are useful, but I have no way of knowing it I am internalizing/implementing the teachings correctly; I have no test. I would very much appreciate a final critique. What advice can you give, with regards to what I should be thinking about going forward, prior to embarking on my next project. </p>
<hr>
<p><sub>Notes:</sub></p>
<p><sub>i. In my project, macros are treated as %include files, and procedures are assembled separately into their own object files. All modules have been assembled as one for the purposes of posting this review request.</sub></p>
<p><sub>ii. NASM version 2.11.08 | Architecture x86-64 | Ubuntu 18.04</sub></p>
<hr>
<pre><code>; Executable name: hexdumpadvanced
; Version : 1.1
; Creation date : 22/08/2018
; Last updated : 22/08/2018
; Author : Andrew Hardiman
; Architecture : x86-64
; Register Use : Registers in the main program are used as follows: EBX is
; used as a pointer to memory data, specifically to offset
; `InputBuff`; ECX is used as a counter register, for example
; it is used within the main program loop `ReadFile`, to count
; the number of passes through the loop itself; EDI is used to
; store the destination memory offset, when moving, or storing
; data to memory. For example, EDI is used as a pointer to the
; string 'OutputHex', the output string of the main program.
; For register usage within specific procedures/macros, please
; see the relevant procedure/macro heading section.
; Description : A hex dump utility. The program reads data from stdin and
; and converts the input to rows of hexadecimal pairs,
; representing the underlying binary notation of the data.
; The hex editor also displays the related ASCII chars
; alongside each row of hexadecimal pairs. The length of the
; program output, i.e. how many hex-pairs per row in the
; terminal is dictated by the constant 'INPUTLEN'. NB If
; changing 'INPUTLEN' strings 'OutputHex' and 'OutputChars'
; will need to be changed also, to match.
; Macros : The program includes macro files: "system_call_macros" and
; "string_macros".
; Procedures : There are two externally linked procedures: 'CharTohex.o'
; and 'ConvertControlChars.o'.
;
; Run with the following commands:
; ./hexdumpadvanced < [Input_File]
;
; Build with the following commands:
; ld -o hexdumpadvanced hexdumpadvanced.o
; nasm -f elf64 -g -F dwarf hexdumpadvanced.asm
SECTION .data ; initialised data
; A lookup table for use with procedure 'CharToHex':
Digits: db "0123456789ABCDEF"
; Error message to stderr when an error code is returned from kernel `syscall`:
ErrorMSG: db "There has been an unexpected error, your program has"
db " terminated",0Ah
ERRORLEN: equ $-ErrorMSG
; Message printed to stdout, when the file passed to stdin contains no data:
ZeroInput: db "The input file did not contain any data, the program"
db " has terminated",0Ah
ZEROLEN: equ $-ZeroInput
; Predefined output buffer, to recieve the input chars converted into their
; binary notation, and the ASCII chars, delimited by vertical bars (7Ch):
OutputHex: db "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 "
OutputChars: db "|................|",0AH
OUTPUTLEN: equ $-OutputHex
SECTION .bss ; uninitialised data
INPUTLEN: equ 16 ; Read from file, 16 bytes at a time
InputBuff: resb INPUTLEN
SECTION .text ; section containing code
;-------------------------------------------------------------------------------
; MACROS START HERE
;-------------------------------------------------------------------------------
;-------------------------------------------------------------------------------
; ReadInput : Invokes x86-64 sys_read. Kernel `syscall` no. 0
; Updated : 19/08/2018
; IN : %1 is the memory offset to read to; %2 is the byte count
; Returns : RAX will contain the number of bytes read to memory
; Modifies : RAX as the return value; R11 is clobbed with the value of RFLAGS
; Calls : Kernel `syscall`
; Description : ReadInput simplifies invoking kernel `syscall` in x86-64,
; specifically for `syscall` number 0; sys_read. The macro
; preserves and restores the callers registers.
%macro ReadInput 2
; Save callers registers.
push rcx ; kernel syscall stores RIP in RCX
push rdx ; Used to store the read byte count
push rdi ; Stores file descriptor, stdin '0'
push rsi ; Memory offset to read file
; Prepare registers, and invoke kernel sys_read:
mov eax,0 ; sys_read
mov edi,0 ; stdin
mov esi,%1 ; Memory offset to read to
mov edx,%2 ; Byte count read from file
syscall ; Kernel system call
; Restore callers registers:
pop rsi
pop rdi
pop rdx
pop rcx
%endmacro
;-------------------------------------------------------------------------------
; WriteOutput : Invokes x86-64 sys_write. Kernel `syscall` no. 1
; Updated : 19/08/2018
; IN : %1 memory offset delimiting the start of data to write to
; output; %2 number of bytes to write to output.
; Returns : Possible error code to RAX
; Modifies : RAX possible error code; R11 is clobbed with the value of RFLAGS
; Calls : Kernel `syscall`
; Description : WriteOutput simplifies invoking kernel `syscall` in x86-64,
; specifically for `syscall` number 1; sys_write. The macro
; preserves and restores the callers registers.
%macro WriteOutput 2
; Save callers registers. RAX will be clobbered with `syscall` return code:
push rcx ; Kernel `syscall` stores RIP in RCX
push rdx ; Byte count to write to stdout
push rdi ; File descriptor 1, stdout
push rsi ; Offset of data to written to stdout
; Prepare registers, and invoke kernel `sys_write`:
mov eax,1 ; sys_write
mov edi,1 ; stdout
mov esi,%1 ; Offset of data written to stdout
mov edx,%2 ; Number of bytes written to stdout
syscall ; Invoke kernel `syscall`.
; Restore callers registers:
pop rsi
pop rdi
pop rdx
pop rcx
%endmacro
;-------------------------------------------------------------------------------
; ExitProgram : Invokes x86-64 sys_exit. Kernel `syscall` no. 60
; Updated : 19/08/2018
; IN : Nothing
; Returns : Return code to RAX
; Modifies : RAX contains return code; RDI int error_code (typically) zero;
; RCX stores RIP, R11 store RFLAGS.
; Calls : Kernel `syscall`
; Description : Exits program elegantly and hands control back to the kernel
; from user space; probable segmentation fault without invocation
; of kernel sys_exit.
%macro ExitProgram 0
; Prepare resgiters, and invoke kernel sys_exit:
mov eax,60 ; Kernel syscall no. 60, sys_exit
mov edi,0 ; Return error code 0
syscall
%endmacro
;-------------------------------------------------------------------------------
; ErrorHandler : Displays error message to stderr and exits program elegantly
; Updated : 21/08/2018
; IN : To be included in `SECTION .data` of main program: `ErrorMSG:
; db "There has been an unexpected error, your program has
; terminated"` and `ERRORLEN: equ $-ErrorMSG`.
; Returns : RAX will contain the return code from `sys_exit` kernel call
; Modifies : RAX will contain the return code from `sys_exit` kernel call;
; RDI will be 0; RCX stores RIP, R11 stores RFLAGS; RSI will be
; the memory offset of string 'ErrorMSG'; RDX will be the byte
; count of string 'ErrorMSG', stored in label 'ERRORLEN'.
; Calls : Includes 'ExitProgram' macros, from file "system_call_macros"
; Description : To be invoked after a `syscall`, to check RAX for an error
; return code. Under Linux, error return codes are within the
; range -4095..... -1. If error code returned from `syscall`,
; error message is written to stderr and program exits
; through 'ExitProgram' macro.
%macro ErrorHandler 0
cmp rax,0FFFFFFFFFFFFF000h ; Error range under Linux is -4095 ...... -1
jna %%exit ; Return value > RAX indicates error
; Write error message to stderr:
mov eax,1 ; Kernel syscall no. 1, sys_write
mov edi,2 ; File descriptor 2, stderr
mov esi,ErrorMSG ; Offset of string to write to stderr
mov edx,ERRORLEN ; Length of message to write to stderr
syscall ; Make system call
; Exit program elegantly:
ExitProgram ; ExitProgram macro
%%exit:
%endmacro
;-------------------------------------------------------------------------------
; MoveString : Moves string from memory offset A to memory offset B
; Updated : 19/08/2018
; IN : %1 is the destination memory offset; %2 is the source
; memory offset; %3 is the byte count in the string.
; Returns : Nothing
; Modified/Trashed : EDI will point to memory offset immediately after the
; last char in the moved string.
; Calls : Nothing
; Description : The macro is used to invoke the instruction 'rep
; MOVSB', it is useful as it preserves registers and
; reduces necessary key-strokes.
%macro MoveString 3
push rcx
push rsi
lea edi,%1 ; Destination memory address for `MOVSB`
lea esi,%2 ; Source memory address for `MOVSB`
mov ecx,%3 ; The byte count of the string being moved
rep movsb
pop rsi
pop rcx
%endmacro
;-------------------------------------------------------------------------------
;PROCEDURES START HERE
;-------------------------------------------------------------------------------
;-------------------------------------------------------------------------------
; CharToHex : Converts a string of chars in memory, to their underlying
; binary representations, see Description
; Architecture: x86-64
; Updated : 21/08/2018
; IN : EBX is the memory offset of the string of input chars; EDI is
; the memory offset of the string of converted converted
; hexidecimal pairs; ECX is the number of chars to convert.
; Returns : Hexidecimal pairs are stored at memory offset EDI
; Modifies : EDI will point to the memory offset immediately after the last
; hex-pair stored in memory; ESI will contain the delimiter
; character passed to 'CharToHex' as an original argument.
; Calls : Nothing
; Description : CharsToHex excepts a string of ASCII chars, at offset EBX, and
; converts the chars to a string of chars representing their
; underlying binary representations, to memory offset EDI. For
; example, if char at EBX was "A", then [EBX] would contain the
; underlying binary notation 41h. CharsToHex would then generate
; a string at EDI representing the chars "4" and "1" (binary in
; memory 3431h). Consequently, when the input is "A", the output
; is "41"; the output is the underlying hexidecimal notation of
; the input.
CharToHex:
push rax
push rbx
push rcx
push rdx
; During loop `.convertChars`, if the high byte of registers AX and DX are not
; zero then, the use of `[Digits+eax]` could end up accessing data out of
; bounds of memory. This would be in the case, for instance, if the number of
; chars to be converted, EAX, exceeded 255 characters:
xor eax,eax
xor edx,edx
.convertChars:
mov al,byte [ebx] ; Move byte from input buffer to AL
mov dl,al ; Copy char into DL
and al,0Fh ; Bit-mask, AL will now hold lower nibble
shr dl,4 ; DL will now hold upper nibble of hex-pair
;Look up nibble in lookup table 'Digits', return the underlying binary pattern:
mov al,byte [Digits+eax] ; Lookup digit in 'Digits' table
mov dl,byte [Digits+edx] ; Return the underlying binary notation
mov byte [edi],dl ; Move binary pattern to Output string
mov byte [edi+1],al ; Move binary pattern
mov byte [edi+2],20h ; Append 'space' character to output string
lea edi,[edi+3] ; Move output pointer
inc ebx ; Increment input buffer pointer
dec ecx ; Decrement the count of chars
jne .convertChars ; If char count not zero, convert next char
; Restore registers and return:
pop rdx
pop rcx
pop rbx
pop rax
ret
;-------------------------------------------------------------------------------
; ConvertControlChars : Converts a string of chars in memory, replacing
; non-printable chars with the ASCII period character,
; 2Eh; printable characters are left unchanged.
; Architecture : x86-64
; Updated : 22/08/2018
; IN : RCX is the length of the string being scanned, in
; bytes; RBX is the pointer to the offset of the string
; being scanned.
; Returns : Nothing
; Modifies : Nothing, any registers modified during the procedure
; are reserved on the stack, and are restored prior to
; returning to the main program.
; Calls : Nothing
; Description : Scans a string of chars in memory. The high 128
; characters are translated to ASCII period (2Eh).
; The non-printable characters in the low 128
; (00h -1Fh) are also translated to ASCII period, as is
; char 127 (7Fh).
ConvertControlChars:
; Preserve registers:
push rax
push rcx
; Convert string of ECX length, starting at offset EBX:
.nextChar:
mov al, byte [ebx-1+ecx] ; Move first char for conversion to register
cmp al,20h ; Compare char in string to 20h
jb .convertChar ; Chars below ASCII 20h are non-printable
cmp al,7Eh ; Compare char in string to 7Eh
jna .testExit ; chars above 7Eh are non-printable
.convertChar:
mov byte [ebx-1+ecx],2Eh ; Char has tested positive as non-printable
.testExit:
dec ecx ; Decrement count of chas to be converted
jnz .nextChar ; Loop if there are chars remaining
; Restore registers and return:
pop rcx
pop rax
ret
;-------------------------------------------------------------------------------
; MAIN PROGRAM STARTS HERE
;-------------------------------------------------------------------------------
GLOBAL _start ; Linker need this to find an entry point
_start:
nop ; This no-op keeps gdb happy....
; Create a pointer, for the 'InputBuff' memory buffer. The instruction is
; situated here in the source code, as the instruction does not need to be
; repeated each time the program loops:
lea ebx,[InputBuff]
; Read data from stdin, to memory offset 'InputBuff':
ReadFile:
ReadInput InputBuff, INPUTLEN ; Macro 'ReadInput'
ErrorHandler ; Macro 'ErrorHandler'
; EDX will store the aggregate number of bytes read from file:
add edx,eax
; Check return value from sys_read. If no data has been read, and the program
; is on first loop (EDX), then there has been no data read from file, inform
; user and exit program. If there has been data read from file (EDX), however
; there is no data read on this loop (EAX), then EOF reached, 'PrintOutput' and
; exit program:
cmp eax,0 ; Compare sys_read return value to zero
jne InputPadding ; If data has been read, jp to 'InputPadding'
cmp edx,0 ; Compare loop count to one
jne Exit ; If data has previously been read,jp 'Exit'
; Inform user that no data has been read and exit program:
WriteOutput ZeroInput, ZEROLEN ; Macro 'WriteOutput'
ErrorHandler ; Macro 'ErrorHandler'
jmp Exit ; Jump to 'Exit' (program)
; If the number of bytes read from file < 'INPUTLEN', calculate the padding
; required to overwrite the bytes 'left-over' from the previous loop. This step
; is required to prevent the program from writing duplicate data on the
; final line of output in the terminal:
InputPadding:
cmp eax,INPUTLEN ; cmp INPUTLEN to no. of chars read from file
je ConvertChars ; If INPUTLEN == chars from file: no padding
; Prepare implicit registers for use with `STOSB` instruction:
mov ecx,INPUTLEN ; Move maximum number of bytes read from file
sub ecx,eax ; Subtract the actual number of bytes read
lea edi,[ebx+eax] ; Offset in which to store the string
mov eax,0h ; Move character to use as padding
; Execute store string instruction, which will overwrite any 'left-over' bytes,
; from previous `sys_read`:
rep stosb ; Reiterate through string
; Convert each individual char, in 'InputBuff', to a string representing its
; underlying binary notation, and store at memory offset 'OutputHex'. For
; example, if char in memory is "A", the underlying binary notation will be
; 41h. Therefore, 'ConvertChars' will create the word 3431h, in memory
; buffer 'OutputHex'. 3431h printed to stdout will be converted to string
; "41", the binary notation of char "A":
ConvertChars:
lea edi,[OutputHex] ; Create pointer for 'OutputHex' stringFor
mov ecx,INPUTLEN ; The number of chars to convert
call CharToHex ; Convert ASCII chars read from file, to
; their underlying binary notation
; Convert all non-printable chars in 'InputBuff' to period character (2Eh):
call ConvertControlChars
; Move string of chars from 'InputBuff', to relevant place in 'OutputChars'
; string, accounting for the 'opening' vertical bar, with '+1'.
; A row of chars will appear immediately after the row of related hex-pairs in
; the terminal output, 'book-marked' either end by a vertical bar char (7Ch):
MoveString [OutputChars+1], [InputBuff], INPUTLEN
; Print the prepared output string to the terminal, delimited at the offset in
; memory `OutputHex`. The string consists of two `SECTION .data` items,
; 'OutputHex', containing the hexidecimal pairs, and `OutputChars`, containing
; the ASCII chars, with all control chars converted to the period character 2Eh.
; The total output string is of length `OUTPUTLEN`:
PrintOutput:
WriteOutput OutputHex, OUTPUTLEN ; Macro `WriteOutput`
ErrorHandler ; `ErrorHandler` macro
; Fetch next buffer of input from file and repeat the process:
jmp ReadFile
; Exit program elegantly:
Exit:
ExitProgram ; 'ExitProgram' macro
nop ; no-op keeps gdb happy.......
</code></pre>
| [] | [
{
"body": "<p>I see a number of things that may help you improve your program, but first I wanted to say that you've definitely improved the program greatly from the previous version. Nice work!</p>\n\n<h2>Fix the (minor) bug</h2>\n\n<p>The previous version correctly showed blanks at the end of the lines if th... | {
"AcceptedAnswerId": "202331",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T12:20:31.143",
"Id": "202302",
"Score": "4",
"Tags": [
"performance",
"assembly",
"x86"
],
"Title": "Hex Dump Utility in x86-64 Assembly: Version 1.1"
} | 202302 |
<p>I have the following front-end code for a responsive navigation menu which I thought using in my WordPress website.</p>
<p>Clicking the <code>.burger</code> element should cause adjacent <code>.menu</code> element to appear or disappear, in dropdown or dropup respectively, but without a breakpoint conflict such as this, which I suffer from:</p>
<ol>
<li>We open a browser window <code><=959px</code> and open the menu.</li>
<li>We resize the window to <code>>=960px</code> and then we resize back to <code><=959px</code>.</li>
<li>We see that the menu is still open and isn't restarted.</li>
</ol>
<h2>Why I seek review</h2>
<p>Many programmers advised me to take a pure CSS approach (no JavaScript) but in this case I create my markup with a WordPress page builder (<a href="http://elementor.com" rel="nofollow noreferrer">Elementor</a>) hence it feels inefficient to me. I also feel my JavaScript is too long and a bit confusing.</p>
<p>You might know a simpler and shorter (more <a href="https://www.w3schools.com/js/js_object_methods.asp" rel="nofollow noreferrer">methodal</a> and more intuitive) pattern in vanilla JavaScript available in 2018 (ES6/ES7?) or in jQuery 3.x.x.</p>
<h2>Code</h2>
<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>document.addEventListener('DOMContentLoaded', ()=>{
let clicks = 0;
let menu = document.querySelector('#menu-primary');
let burger = document.querySelector('.burger');
let isMenuVisible = false;
burger.addEventListener('click', ()=>{
isMenuVisible = !isMenuVisible;
menu.style.display = isMenuVisible ? 'block' : 'none';
});
let mobileBehavior = ()=>{
menu.style.display = 'none';
};
if (window.innerWidth <= 959) {
mobileBehavior();
}
window.addEventListener('resize', ()=>{
if (window.innerWidth <= 959) {
clicks = 1;
} else if (window.innerWidth >= 960) {
menu.style.display = 'block';
}
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.burger {display: block; text-align: center; color: var(--w); margin-bottom: 0 !important; font-weight: bold}
#menu-primary {display: none}
@media screen and (min-width: 960px) {
.burger {display: none}
#menu-primary {display: block}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="burger">BARS</div>
<ul id="menu-primary">
<li>Homepage</li>
<li>Contact_us</li>
</ul></code></pre>
</div>
</div>
</p>
<h2>Update</h2>
<p>I reported a problem with the code in <a href="https://stackoverflow.com/questions/51990611/javascript-resizing-laptops-browser-window-mobile-desktop-mobile-doe">this StackOverflow session</a>; the problem is that the code can conflict with some page builders and does conflict with Elementor WordPress-Drupal page builder, as described there. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T15:55:14.067",
"Id": "390550",
"Score": "1",
"body": "\"*advised me to take a pure CSS approach but I create my markup with a WordPress page builder and it feels to me inefficient*\" Why is it inefficient to use a combination of CSS... | [
{
"body": "<h2>General feedback</h2>\n<p>Overall it seems somewhat simple and works fine except for the issue I saw you mentioned in a comment on <a href=\"https://stackoverflow.com/a/52119743/3578082\">the accepted answer to the related Stack Overflow post</a>, about having to click the menu button twice after... | {
"AcceptedAnswerId": "202686",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T12:20:55.707",
"Id": "202303",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"wordpress"
],
"Title": "JavaScript responsive menu (dropdown/dropup)"
} | 202303 |
<p>I have a data structure that looks like this:</p>
<pre><code>interface Node {
originalWeight: number;
currentWeight: number;
}
</code></pre>
<p>where both properties are floats between <code>0</code> and <code>1</code>.</p>
<p>To check if a node has been modified, I wrote a simple <code>isNodeModified</code> function:</p>
<pre><code>isNodeModified(node: Node): boolean {
return Math.abs(node.originalWeight- node.currentWeight) > this.EPSILON;
}
</code></pre>
<p>where <code>EPSILON</code> is my tolerance. </p>
<p>However, I also need to do a very similar comparison in a slightly different scenario, which was originally handled like this:</p>
<pre><code>if (Math.abs(event.value - node.originalWeight) > this.EPSILON) {
// do something
}
</code></pre>
<p>where <code>event</code> is another object with a <code>value</code> property.</p>
<p>To avoid duplication, I replaced both methods with something like the following:</p>
<pre><code>isNodeModified(node: Node, event?: Event): boolean {
let original = node.originalWeight;
if (event) {
original = event.value;
}
return Math.abs(original - node.currentWeight) > this.EPSILON;
}
</code></pre>
<p>So that I can call <code>isNodeModified(node)</code> or <code>isNodeModified(node, event)</code> depending on what I need. </p>
<p>Is there a better / cleaner solution to this problem?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T13:18:42.087",
"Id": "389812",
"Score": "0",
"body": "Can you clarify what the purpose of `event` is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T13:28:36.130",
"Id": "389816",
"Score": "0... | [
{
"body": "<p>You could create a more general function which simple compares two values.\nLike:</p>\n\n<pre><code>hasDifference(oldValue: number, newValue: number, offset?: number): boolean {\n const offsetToUse: number = offset === undefined ? this.EPSILON : offset;\n\n return Math.abs(oldValue - newValue) &... | {
"AcceptedAnswerId": "202310",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T12:24:22.623",
"Id": "202304",
"Score": "1",
"Tags": [
"typescript",
"overloading"
],
"Title": "Generic function with same logic but different input structure"
} | 202304 |
<p>The following code is used to show/hide components in an AngularJS app:</p>
<pre><code>var vm = this;
var hideComponents = function()
{
vm.showRegions = false;
vm.showAccounts = false;
vm.showOrders = false;
vm.showInvoices = false;
vm.showWarehouses = false;
}
vm.showComponent = function(componentName)
{
hideComponents();
switch (componentName) {
case "Regions":
vm.showRegions = true;
break;
case "Accounts":
vm.showAccounts = true;
break;
case "Orders":
vm.showOrders = true;
break;
case "Invoices":
vm.showInvoices = true;
break;
case "Warehouses":
vm.showWarehouses = true;
break;
default:
}
}
</code></pre>
<p>Is there a more concise way to achieve this functionality?</p>
<p>I was thinking something along these lines:</p>
<pre><code>var setComponentVisibility = function (componentName = null)
{
var bool = false;
var map = {
'Regions': vm.showRegions = bool,
'Accounts': vm.showAccounts = bool,
'Orders': vm.showOrders = bool,
'Invoices': vm.showInvoices = bool,
'Warehouses': vm.showWarehouses = bool
}
if (componentName != null)
{
// code to set bool to true only for that componentName in map
// is this even possible?
// if so, how?
}
}
</code></pre>
<p>However, being new to AngularJS, I'm not sure the above is possible.</p>
| [] | [
{
"body": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation\" rel=\"nofollow noreferrer\">Bracket Notation</a> to have custom object key by <code>['text'+variable]</code>.</p>\n\n<pre><code>vm.showComponent = function(compon... | {
"AcceptedAnswerId": "202314",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T13:07:38.667",
"Id": "202306",
"Score": "2",
"Tags": [
"javascript",
"angular.js"
],
"Title": "show/hide components"
} | 202306 |
<blockquote>
<h2><a href="https://projecteuler.net/problem=5" rel="nofollow noreferrer">Project Euler #5: Smallest multiple</a></h2>
<p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p>
<p>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"</p>
</blockquote>
<p>And I'm wondering if my code to solve this problem is good and if there are ways to make it better.</p>
<pre><code>#include "stdafx.h"
#include <iostream>
int main(){
int smallestMultiple = 40;
int i = 10;
while (i<20){
if (smallestMultiple%i == 0){
i++;
continue;
}
else{
i = 10;
smallestMultiple += 20;
}
}
std::cout << smallestMultiple;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T13:20:28.327",
"Id": "389813",
"Score": "3",
"body": "There are far more efficient ways to get the result. I would suggest to have a look at existing Q&A's about the same problem, such as https://codereview.stackexchange.com/q/80500... | [
{
"body": "<h1>Code Review</h1>\n<p>Despite its name, <code>"stdafx.h"</code> isn't a standard header. It doesn't seem to be needed, as the code compiles and runs without it.</p>\n<p>Your indentation is off - perhaps that's a result of how you inserted the code into the question?</p>\n<p>The <code>co... | {
"AcceptedAnswerId": "202311",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T13:09:58.337",
"Id": "202307",
"Score": "1",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "Project Euler Problem #5 Solution in C++"
} | 202307 |
<p>In my current game I have the need for values ranging from 0 to 1, or from -1 to 1. The values should never exceed this threshold, so instead of constantly validating the values I made a custom data type which essentially clamps a float to that threshold. I have been researching various ways of making it better, and I feel like what I have now is just about perfect for my uses. I decided against implementing IConvertible since all I'm really doing is wrapping a float with code I need; the value is still a float, and can be extracted and converted in the unlikely event it would need to be. </p>
<p>Is there anything I can improve on? Anything I'm doing wrong? I'd love to know!</p>
<p>P.S. You'll notice there's mention of a "SBloat", that's the same thing as a Bloat, just signed and ranging from -1.0 to 1.0. The code is almost identical.</p>
<pre><code>using System;
using UnityEngine;
namespace ProjectBleak {
/// <summary>
/// Represents an unsigned binary float ranging from 0 to 1.0. If the value exceeds this limit, it will be clamped to stay in range.
/// </summary>
[System.Diagnostics.DebuggerDisplay("{value}")]
public struct Bloat : IEquatable<Single>, IFormattable {
/// <summary> 0 </summary>
public static readonly float MinValue = 0f;
/// <summary> 1.0 </summary>
public static readonly float MaxValue = 1f;
private float value;
/// <summary> Should an error be thrown when the value would be lower than 0 or higher than 1.0? </summary>
public bool ErrorOnExceed { get; set; }
/// <summary>
/// Represents an unsigned binary float ranging from 0 to 1.0. If the value exceeds this limit, it will be clamped to stay in range.
/// </summary>
/// <param name="value">Value ranging from 0 to 1.0</param>
/// <param name="errorOnExceed">Should an error be thrown when the value would be lower than 0 or higher than 1.0?</param>
public Bloat(float value, bool errorOnExceed = false) {
ErrorOnExceed = errorOnExceed;
if (value < MinValue) {
value = MinValue;
if (ErrorOnExceed) {
Debug.LogError($"Bloat:: {value} exceeds minimum allowed value.");
}
}
else if (value > MaxValue) {
value = MaxValue;
if (ErrorOnExceed) {
Debug.LogError($"Bloat:: {value} exceeds maximum allowed value.");
}
}
this.value = value;
}
public override int GetHashCode() {
unchecked {
int hash = 17;
hash = hash * 23 + value.GetHashCode();
if (ErrorOnExceed) {
hash = hash |= 1 << 19;
}
else {
hash = hash |= 1 << 13;
}
return hash;
}
}
public bool Equals(float other) {
return value == other;
}
public override bool Equals(object obj) {
if (obj is SBloat || obj is Bloat || obj is Single) {
return Equals((float)obj);
}
return false;
}
public override String ToString() {
return value.ToString();
}
public String ToString(IFormatProvider provider) {
return value.ToString(provider);
}
public String ToString(String format) {
return value.ToString(format);
}
public String ToString(String format, IFormatProvider provider) {
return value.ToString(format, provider);
}
// Keep the Signed-to-Unsigned conversion explicit since we will be losing any negative number
public static explicit operator Bloat(SBloat s) => new Bloat(s);
public static implicit operator Bloat(Single f) => new Bloat(f);
public static implicit operator float(Bloat b) => b.value;
public static Bloat operator +(Bloat left, Single right) {
return new Bloat(left.value + right, left.ErrorOnExceed);
}
public static Bloat operator -(Bloat left, Single right) {
return new Bloat(left.value - right, left.ErrorOnExceed);
}
public static Bloat operator +(Bloat left, Bloat right) {
return new Bloat(left.value + right.value, left.ErrorOnExceed);
}
public static Bloat operator -(Bloat left, Bloat right) {
return new Bloat(left.value - right.value, left.ErrorOnExceed);
}
public static bool operator ==(Bloat left, Single right) {
return left.value == right;
}
public static bool operator !=(Bloat left, Single right) {
return left.value != right;
}
public static bool operator <(Bloat left, Single right) {
return left.value < right;
}
public static bool operator >(Bloat left, Single right) {
return left.value > right;
}
public static bool operator <=(Bloat left, Single right) {
return left.value <= right;
}
public static bool operator >=(Bloat left, Single right) {
return left.value >= right;
}
public static bool operator ==(Single left, Bloat right) {
return left == right.value;
}
public static bool operator !=(Single left, Bloat right) {
return left != right.value;
}
public static bool operator <(Single left, Bloat right) {
return left < right.value;
}
public static bool operator >(Single left, Bloat right) {
return left > right.value;
}
public static bool operator <=(Single left, Bloat right) {
return left <= right.value;
}
public static bool operator >=(Single left, Bloat right) {
return left >= right.value;
}
public static bool operator ==(Bloat left, Bloat right) {
return left.value == right.value;
}
public static bool operator !=(Bloat left, Bloat right) {
return left.value != right.value;
}
public static bool operator <(Bloat left, Bloat right) {
return left.value < right.value;
}
public static bool operator >(Bloat left, Bloat right) {
return left.value > right.value;
}
public static bool operator <=(Bloat left, Bloat right) {
return left.value <= right.value;
}
public static bool operator >=(Bloat left, Bloat right) {
return left.value >= right.value;
}
public static bool operator ==(Bloat left, SBloat right) {
return left.value == right;
}
public static bool operator !=(Bloat left, SBloat right) {
return left.value != right;
}
public static bool operator <(Bloat left, SBloat right) {
return left.value < right;
}
public static bool operator >(Bloat left, SBloat right) {
return left.value > right;
}
public static bool operator <=(Bloat left, SBloat right) {
return left.value <= right;
}
public static bool operator >=(Bloat left, SBloat right) {
return left.value >= right;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T20:29:09.290",
"Id": "389876",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidat... | [
{
"body": "<p>All in all it seems OK to me. I have these comments:</p>\n\n<p>This test:</p>\n\n<pre><code> Bloat a = new Bloat(0.5f);\n object b = new Bloat(0.3f);\n\n Console.WriteLine(a.Equals(b));\n</code></pre>\n\n<p>Throws an <code>InvalidCastException</code></p>\n\n<p>in:</p>\n\n<blockquote>\n<pre><cod... | {
"AcceptedAnswerId": "202335",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T16:07:01.440",
"Id": "202322",
"Score": "5",
"Tags": [
"c#",
"performance",
"unity3d",
"unit-conversion"
],
"Title": "Custom data type - \"Binary\" Float (0-1.0)"
} | 202322 |
<p>I have a pre-planning file for year-end review that does a lot of index/match formulas and <code>IF</code> statement formulas based on certain parameters when referencing increases in various types of pay/incentive pay.</p>
<pre><code>Sub Update()
'File Paths
Dim Preplan As String: Preplan = "M:\PrePlanning_Template.xlsm"
Dim PS_Export As String: PS_Export = "M:\PS_Export.xlsx"
'Open WB's
Dim PP_WB As Workbook: Set PP_WB = Workbooks.Open(Filename:=Preplan, Password:="")
Dim PS_WB As Workbook: Set PS_WB = Workbooks.Open(Filename:=PS_Export)
Dim PP_WS As Worksheet: Set PP_WS = PP_WB.Sheets("2017 Pre-Planning Emp Detail")
Dim PS_WS As Worksheet: Set PS_WS = PS_WB.Sheets("ps")
Dim lrAR As Long, lrAS As Long, lrAX As Long
LastRow = PP_WS.Range("A" & Rows.Count).End(xlUp).Row
lastrow2 = PS_WS.Range("A" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
PP_WB.Activate
PP_WS.Range("AE2").Formula = "=INDEX([PS_Export.xlsx]ps!$K:$K,MATCH(A2,[PS_Export.xlsx]ps!$A:$A,0))"
PP_WS.Range("AE2").AutoFill Destination:=Range("AE2:AE" & LastRow)
PP_WS.Range("AF2").Formula = "=INDEX([PS_Export.xlsx]ps!$H:H,MATCH(A2,[PS_Export.xlsx]ps!$A:$A,0))"
PP_WS.Range("AF2").AutoFill Destination:=Range("AF2:AF" & LastRow)
PP_WS.Range("AG2").Formula = "=INDEX([PS_Export.xlsx]ps!$AX:AX,MATCH(A2,[PS_Export.xlsx]ps!$A:$A,0))"
PP_WS.Range("AG2").AutoFill Destination:=Range("AG2:AG" & LastRow)
PP_WS.Range("AH2").Formula = "=INDEX([PS_Export.xlsx]ps!$O:O,MATCH(A2,[PS_Export.xlsx]ps!$A:$A,0))"
PP_WS.Range("AH2").AutoFill Destination:=Range("AH2:AH" & LastRow)
PP_WS.Range("AI2").Formula = "=INDEX([PS_Export.xlsx]ps!$P:P,MATCH(A2,[PS_Export.xlsx]ps!$A:$A,0))"
PP_WS.Range("AI2").AutoFill Destination:=Range("AI2:AI" & LastRow)
PP_WS.Range("AE:AI").Copy
PP_WS.Range("AE:AI").PasteSpecial xlPasteValues
With PP_WS.Range("AG:AG")
.Replace What:="Assistant Vice President", Replacement:="AVP", _
LookAt:=xlPart
.Replace What:="Vice President", Replacement:="VP", LookAt:= _
xlPart
.Replace What:="Sr. VP", Replacement:="SVP", LookAt:= _
xlPart
.Replace What:="0", Replacement:="", LookAt:= _
xlPart
End With
PS_WB.Activate
PP_WS.Range("AE:AE").Replace What:="0", Replacement:="", LookAt:=xlWhole
PS_WS.Range("AH:AH").Insert Shift:=xlToRight
'fills to last row in PS report'
PS_WS.Range("AH2").Formula = "=AD2+AG2"
PS_WS.Range("AH2").AutoFill Destination:=Range("AH2:AH" & lastrow2)
PS_WS.Range("AH2").Range("AH1") = "Variable Comp"
PS_WB.Close savechanges:=False
''if there is an "X" in column F (sr. manager), then do a VLOOKUP, if not then do the calc'
PP_WS.Range("AR2").Formula = "=IF(F2=""X"",VLOOKUP(A2,[PS_Export.xlsx]ps!$A:$AH,34,FALSE),(AS2+AU2+AX2))"
PP_WS.Range("AR2").AutoFill Destination:=Range("AR2:AR" & LastRow)
'if there isn't an "X" in column F, then do a VLOOKUP, if not keep the calc'
PP_WS.Range("AS2").Formula = "=IF(F2="""",VLOOKUP(A2,[PS_Export.xlsx]ps!$A:$AD,30,FALSE),(AR2-AX2))"
PP_WS.Range("AS2").AutoFill Destination:=Range("AS2:AS" & LastRow)
PP_WS.Range("AX2").Formula = "=VLOOKUP(A2,[PS_Export.xlsx]ps!$A:$AG,33,FALSE)"
PP_WS.Range("AX2").AutoFill Destination:=Range("AX2:AX" & LastRow)
'PP_WS.Range("AX:AX").Copy
'PP_WS.Range("AX:AX").PasteSpecial xlPasteValues
'Filter section for Sr. Leaders'
PP_WS.Cells.AutoFilter field:=5, Criteria1:="<>"
lrAX = Cells(Rows.Count, 50).End(xlUp).Row
With Range(Cells(2, 50), Cells(lrAX, 50))
.Offset(1).SpecialCells(xlCellTypeVisible).FormulaR1C1 = "=IF(RC[-6]<=300000,RC[-6]*0.3,IF(AND(RC[-6]>300000,RC[-6]<=500000),((RC[-6]-300000)*0.35)+90000,IF(AND(RC[-6]>500000,RC[-6]<=1000000),((RC[-6]-500000)*0.4)+160000,IF(RC[-6]>1000000,((RC[-6]-1000000)*0.45)+360000,))))"
End With
'Second filter section'
'selects cell AS2, designates that as current region, autofilters column F'
PP_WS.Cells.AutoFilter field:=5, Criteria1:="<>"
lrAS = Cells(Rows.Count, 45).End(xlUp).Row
With Range(Cells(2, 45), Cells(lrAS, 45))
.Offset(1).SpecialCells(xlCellTypeVisible).FormulaR1C1 = "=RC[-1]-RC[5]"
End With
PP_WS.Cells.AutoFilter field:=5
PP_WS.Range("AR2").AutoFilter field:=5, Criteria1:=""
' Find last row with data in column 44
lrAR = Cells(Rows.Count, 44).End(xlUp).Row
With Range(Cells(2, 44), Cells(lrAR, 44))
.Offset(1).SpecialCells(xlCellTypeVisible).FormulaR1C1 = "=RC[1]+RC[3]+RC[6]"
End With
PP_WS.Cells.AutoFilter
PP_WS.Range("AS2").AutoFilter field:=6, Criteria1:="<>"
With Range(Cells(2, 45), Cells(lrAS, 45))
.Offset(1).SpecialCells(xlCellTypeVisible).FormulaR1C1 = "=RC[-1]-RC[5]"
End With
Cells.AutoFilter
Cells.AutoFilter
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>What I'm curious about is any tactic that I can deploy in order to condense this script to make it run faster. It works fine, but I'm sure there is repetitive with/end with referencing and subtle things like that that are unnecessary. I would like this to also serve as a learning experience for me to make my code more elegant.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T22:48:37.560",
"Id": "389899",
"Score": "0",
"body": "Do you need the formulas on your final product or just the values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T18:35:46.753",
"Id": "39008... | [
{
"body": "<p>First, your indenting is all weird. Sometimes that's a result of copy/paste into CodeReview - but it's worth pointing out anyway. Make sure <em>everything</em> is indented at least 1 tab and each level is indented one further tab. Then any labels you may have are not indented. <a href=\"https://gi... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T16:48:31.680",
"Id": "202323",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Compensation Year-End Planning VBA Script"
} | 202323 |
<p>I decided to improve my OOP design knowledge and learn python at the same time so I started to write a simple program which will be a fight "simulator".</p>
<p>For now, there are only 2 character types : Orc and Human.
The <code>CharacterFactory</code> class is created so that I'll be able to handle <code>Orc</code> and <code>Human</code> classes in a more abstract way or so.</p>
<p><code>GameState</code> is meant to track the state of the game. Instances will be immediately registered to the <code>GameState</code> as soon as they created. And for example, if a character dies, I want to remove it from the list as well. (<code>self.characters</code>).</p>
<pre><code> #abtract factory or something
class CharacterFactory:
def __init__(self, character=None, game_state=None):
self.character = character
game_state.register_character(self)
def inspect(self):
print(self.character.name)
print(self.character.attack_dmg)
print(self.character.health)
print("\n")
def attack(self, target):
target.character.health = target.character.health - self.character.attack_dmg
#Observable or so
class GameState:
def __init__(self):
self.characters = []
def register_character(self, character):
self.characters.append(character)
def show_characters(self):
list(map(lambda x: x.inspect(), self.characters))
class Orc:
def __init__(self,name):
self.name = name
self.attack_dmg = 50
self.health = 100
class Human:
def __init__(self,name):
self.name = name
self.attack_dmg = 45
self.health = 105
def Main():
game_state = GameState()
orc = CharacterFactory(Orc("Karcsi"),game_state)
#orc.inspect()
#orc.attack()
human = CharacterFactory(Human("Nojbejtoo"),game_state)
#human.inspect()
#human.attack()
print("Game state:\n")
game_state.show_characters()
orc.attack(human)
game_state.show_characters()
Main()
</code></pre>
<p>My question is:</p>
<p>Is this a good design? Or maybe a complete pain in the ... to work with? Is there something that I could improve? </p>
<p>Of course this code is really far from being finished, but I try to find the best approach possible to design things like this so that i can deepen my knowledge in design patterns and stuff like that.</p>
| [] | [
{
"body": "<blockquote>\n <p>The CharacterFactory class is created so that I'll be able to handle Orc and Human classes in a more abstract way or so.</p>\n</blockquote>\n\n<p>You try to stay DRY which is very good, but this idea would be better represented with <a href=\"https://www.python-course.eu/python3_in... | {
"AcceptedAnswerId": "202373",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T17:49:14.887",
"Id": "202326",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"role-playing-game",
"abstract-factory"
],
"Title": "Combat game - character factory"
} | 202326 |
<p>I don't have much experience using either OOP or PHP since this is probably my first thing ever written in this language. I've had some exposure to OOP but I'm not used to writing programs that way. I would greatly appreciate some feedback concerning OOP and PHP best practices, clean code, and overall design. I'm also curious if my code could make use of some design patterns.</p>
<p>It's supposed to be a blueprint for bank simulator app. For now, It has the following capabilities:</p>
<ul>
<li>Client classes - NaturalPerson and Company. Client can have multiple bank accounts as well as open new and delete current ones.</li>
<li>Account class - it stores an instance of Client, amount of money and transactions history. Using an instance of that class, a client can deposit money to an account, withdraw money and make a transfer to another account. Every operation is saved the <strong>history</strong> array.</li>
<li>Log classes - AccountOperationLog and TransferLog. Every instance stores details of a operation made by an account.</li>
</ul>
<p>.</p>
<pre><code>namespace Bank;
abstract class Client
{
protected $numMoney;
protected $accounts = [];
public function __construct($numMoney)
{
$this->numMoney = $numMoney;
}
public function addNumMoney($ammount)
{
$this->numMoney += $ammount;
}
public function substractNumMoney($ammount)
{
$this->numMoney -= $ammount;
}
public function getNumMoney() : float
{
return $this->numMoney;
}
public function openNewAccount($name)
{
$newAccount = new Account($this, $name);
array_push($this->accounts, $newAccount);
}
public function closeAccount($account)
{
if (in_array($account, $this->accounts)) {
$account->withdrawMoney($account->getNumMoney());
$this->deleteFromAccounts($account);
}
}
private function deleteFromAccounts($account)
{
if (in_array($account, $this->accounts)) {
unset($this->accounts[array_search($account, $this->accounts)]);
}
}
public function getAccount($name) : Account
{
foreach ($this->accounts as $account) {
if ($account->getName() === $name) {
return $account;
}
}
return null;
}
}
class Company extends Client
{
private $name;
private $ein;
public function __construct($name, $ein, $numMoney)
{
$this->name = $name;
$this->ein = $ein;
parent::__construct($numMoney);
}
public function getName() : string
{
return $this->name;
}
}
class NaturalPerson extends Client
{
private $firstName;
private $lastName;
private $ssn;
public function __construct($firstName, $lastName, $ssn, $numMoney)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->ssn = $ssn;
parent::__construct($numMoney);
}
public function getName() : string
{
return $this->firstName . ' ' . $this->lastName;
}
}
class Account
{
private $client;
private $name;
private $numMoney = 0;
private $debt;
private $history = [];
public function __construct($client, $name)
{
$this->client = $client;
$this->name = $name;
}
public function getName() : string
{
return $this->name;
}
public function getNumMoney() : float
{
return $this->numMoney;
}
public function getHistory() : array
{
return $this->history;
}
public function addNumMoney($ammount)
{
$this->numMoney += $ammount;
}
public function substractNumMoney($ammount)
{
$this->numMoney -= $ammount;
}
public function depositMoney($ammount)
{
if ($this->client->getNumMoney() < $ammount) {
return;
}
$this->addNumMoney($ammount);
$this->client->substractNumMoney($ammount);
$this->addAccountOperationLogToHistory('Deposition', 'Today', $ammount, $this->numMoney);
}
public function withdrawMoney($ammount)
{
if ($this->numMoney < $ammount) {
return;
}
$this->substractNumMoney($ammount);
$this->client->addNumMoney($ammount);
$this->addAccountOperationLogToHistory('Withdraw', 'Today', $ammount, $this->numMoney);
}
public function addAccountOperationLogToHistory($type, $date, $ammount, $moneyAfter)
{
$operationLog = new AccountOperationLog(...func_get_args());
array_push($this->history, $operationLog);
}
public function addTransferLogToHistory($type, $name, $date, $ammount, $moneyAfter, $sender, $beneficiary)
{
$operationLog = new TransferLog(...func_get_args());
array_push($this->history, $operationLog);
}
public function transferMoney($account, $title, $ammount)
{
if ($this->numMoney < $ammount) {
return;
}
$this->substractNumMoney($ammount);
$account->addNumMoney($ammount);
$this->addTransferLogToHistory('Transfer', $title, 'today', $ammount, $this->numMoney, $account->client->getName(), $this->client->getName());
$account->addTransferLogToHistory('Transfer', $title, 'today', $ammount, $account->getNumMoney(), $this->client->getName(), $account->client->getName());
}
}
class AccountOperationLog
{
private $type;
private $date;
private $ammount;
private $numMoneyAfter;
public function __construct($type, $date, $ammount, $numMoneyAfter)
{
$this->type = $type;
$this->date = $date;
$this->ammount = $ammount;
$this->numMoneyAfter = $numMoneyAfter;
}
private function saveToDB()
{
// Implement later
}
}
class TransferLog extends AccountOperationLog
{
private $title;
private $sender;
private $beneficiary;
public function __construct($type, $title, $date, $ammount, $numMoneyAfter, $sender, $beneficiary)
{
parent::__construct($type, $date, $ammount, $numMoneyAfter);
$this->title = $title;
$this->sender = $sender;
$this->beneficiary = $beneficiary;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T18:17:40.197",
"Id": "389859",
"Score": "0",
"body": "Welcome to Code Review! Can you include the specification? As in, what problem does this code solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T17:58:26.167",
"Id": "202328",
"Score": "2",
"Tags": [
"beginner",
"php",
"object-oriented",
"design-patterns"
],
"Title": "Simple bank OOP structure in PHP"
} | 202328 |
<p>I have written a small PHP script to get a variable from the URL and echo it in the body ID.</p>
<p>An example of the url:</p>
<pre><code>http://www.example.com/?var=123
</code></pre>
<p>I have added this to the head of my HTML page:</p>
<pre><code><?php if (isset($_GET['var'])) {
$var = $_GET['var'];
} else {
$var = NULL;
} ?>
</code></pre>
<p>The body tag of the HTML page looks like this:</p>
<pre><code><body class="whatever" <?php if(isset($var)) {echo "id=\"$var\""; } ?>>
</code></pre>
<p>The result is a body tag like this when the ?var=123 is added to the URL:</p>
<pre><code><body class="whatever" id="123">
</code></pre>
<p>This is working but I am sure there is a better way to go about it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T18:34:52.857",
"Id": "389862",
"Score": "0",
"body": "For retrieving the value of `var` I would suggest using the ternary option which makes it a lot cleaner and easier to understand. `$var = $GET['var'] ?? null;` See [Comparison Op... | [
{
"body": "<p>One technique is to default the value to <code>NULL</code>:</p>\n\n<pre><code>$var = NULL;\nif (isset($_GET['var'])) {\n $var = $_GET['var'];\n} ?>\n</code></pre>\n\n<p>Then when setting the attribute on the tag, <code>isset()</code> doesn't need to be used.</p>\n\n<pre><code><body class=... | {
"AcceptedAnswerId": "202332",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T18:20:55.797",
"Id": "202329",
"Score": "2",
"Tags": [
"php",
"html"
],
"Title": "Adding ID to body tag from variable defined in URL"
} | 202329 |
<p>I have decided to rewrite what I did <a href="https://codereview.stackexchange.com/questions/196409/generic-double-linked-list-follow-up">here</a>, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate.</p>
<p>I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community in their effort in evaluating my code, I really appreciate it and I believe it is slowly but surely taking my coding skills to the next level.</p>
<p>Here is my header file:</p>
<pre><code>#ifndef DOUBLELINKEDLIST_h
#define DOUBLELINKEDLIST_h
template <class T>
class DoubleLinkedList {
private:
struct Node {
T data;
std::unique_ptr<Node> next = nullptr;
Node* previous = nullptr;
template<typename... Args, typename = std::enable_if_t<std::is_constructible<T, Args&&...>::value>>
explicit Node(std::unique_ptr<Node>&& next, Node* previous, Args&&... args) noexcept(std::is_nothrow_constructible<T, Args&&...>::value)
: data{ std::forward<Args>(args)... }, previous{previous}, next{ std::move(next) } {}
// disable if noncopyable<T> for cleaner error msgs
explicit Node(const T& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
// disable if nonmovable<T> for cleaner error msgs
explicit Node(T&& x, std::unique_ptr<Node>&& p = nullptr)
: data(std::move(x))
, next(std::move(p)) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
void do_pop_front() {
head = std::move(head->next);
if (!tail) tail = head.get(); // update tail if list was empty before
}
public:
// Constructors
DoubleLinkedList() = default; // empty constructor
DoubleLinkedList(DoubleLinkedList const &source); // copy constructor
// Rule of 5
DoubleLinkedList(DoubleLinkedList &&move) noexcept; // move constructor
DoubleLinkedList& operator=(DoubleLinkedList &&move) noexcept; // move assignment operator
~DoubleLinkedList() noexcept;
// Overload operators
DoubleLinkedList& operator=(DoubleLinkedList const &rhs);
// Create an iterator class
class iterator;
iterator begin();
iterator end();
iterator before_begin();
// Create const iterator class
class const_iterator;
const_iterator cbegin() const;
const_iterator cend() const;
const_iterator begin() const;
const_iterator end() const;
const_iterator before_begin() const;
const_iterator cbefore_begin() const;
// Reverse iteator
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
reverse_iterator rbegin() noexcept { return { end() }; }
const_reverse_iterator rbegin() const noexcept { return { end() }; }
const_reverse_iterator crbegin() const noexcept { return { end() }; }
reverse_iterator rend() noexcept { return { begin() }; }
const_reverse_iterator rend() const noexcept { return { begin() }; }
const_reverse_iterator crend() const noexcept { return { begin() }; }
// Memeber functions
void swap(DoubleLinkedList &other) noexcept;
bool empty() const { return head.get() == nullptr; }
int size() const;
template<typename... Args>
void emplace_back(Args&&... args);
template<typename... Args>
void emplace_front(Args&&... args);
template<typename... Args>
iterator emplace(const_iterator pos, Args&&... args);
void push_back(const T &theData);
void push_back(T &&theData);
void push_front(const T &theData);
void push_front(T &&theData);
iterator insert(const_iterator pos, const T& theData);
iterator insert(const_iterator pos, T&& theData);
void clear();
void pop_front();
void pop_back();
iterator erase(const_iterator pos);
bool search(const T &x);
};
template <class T>
class DoubleLinkedList<T>::iterator {
Node* node = nullptr;
bool end_reached = true;
public:
friend class DoubleLinkedList<T>;
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T * ;
using reference = T & ;
iterator(Node* node = nullptr, bool end_reached = false) : node{ node }, end_reached{ end_reached } {}
operator const_iterator() const noexcept { return const_iterator{ node }; }
bool operator!=(iterator other) const noexcept;
bool operator==(iterator other) const noexcept;
T& operator*() const { return node->data; }
T* operator->() const { return &node->data; }
iterator& operator++();
iterator operator++(int);
iterator& operator--();
iterator operator--(int);
};
template <class T>
class DoubleLinkedList<T>::const_iterator {
Node* node = nullptr;
bool end_reached = true;
public:
friend class DoubleLinkedList<T>;
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T *;
using reference = const T &;
const_iterator() = default;
const_iterator(Node* node, bool end_reached = false) : node{ node }, end_reached { end_reached } {}
bool operator!=(const_iterator other) const noexcept;
bool operator==(const_iterator other) const noexcept;
const T& operator*() const { return node->data; }
const T* operator->() const { return &node->data; }
const_iterator& operator++();
const_iterator operator++(int);
const_iterator& operator--();
const_iterator operator--(int);
};
template <class T>
DoubleLinkedList<T>::DoubleLinkedList(DoubleLinkedList<T> const &source) {
for (Node* loop = source.head.get(); loop != nullptr; loop = loop->next.get()) {
push_back(loop->data);
}
}
template <class T>
DoubleLinkedList<T>::DoubleLinkedList(DoubleLinkedList<T>&& move) noexcept {
move.swap(*this);
}
template <class T>
DoubleLinkedList<T>& DoubleLinkedList<T>::operator=(DoubleLinkedList<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
DoubleLinkedList<T>::~DoubleLinkedList() {
clear();
}
template <class T>
void DoubleLinkedList<T>::clear() {
while (head) {
do_pop_front();
}
}
template <class T>
DoubleLinkedList<T>& DoubleLinkedList<T>::operator=(DoubleLinkedList const &rhs) {
SingleLinkedList copy{ rhs };
swap(copy);
return *this;
}
template <class T>
void DoubleLinkedList<T>::swap(DoubleLinkedList &other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
int DoubleLinkedList<T>::size() const {
int size = 0;
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
return size;
}
template <class T>
template <typename... Args>
void DoubleLinkedList<T>::emplace_back(Args&&... args) {
if (!head) emplace_front(std::forward<Args>(args)...);
else {
tail->next = std::make_unique<Node>(nullptr, tail, std::forward<Args>(args)...);
tail = tail->next.get();
}
}
template <class T>
template <typename... Args>
void DoubleLinkedList<T>::emplace_front(Args&&... args) {
head = std::make_unique<Node>(std::move(head), nullptr, std::forward<Args>(args)...);
if (!tail) tail = head.get(); // update tail if list was empty before
}
template <class T>
template <typename... Args>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::emplace(const_iterator pos, Args&&... args) {
if (pos.end_reached) {
emplace_back(std::forward<Args>(args)...);
return end();
}
if (!head) {
emplace_front(std::forward<Args>(args)...);
return begin();
}
std::unique_ptr<Node> newNode = std::make_unique<Node>(std::forward<Args>(args)...);
newNode->previous = pos.node->previous;
newNode->next = std::move(pos.node->previous->next);
pos.node->previous = newNode.get();
newNode->previous->next = std::move(newNode);
return {pos.node->previous};
}
template <class T>
void DoubleLinkedList<T>::push_back(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(std::move(theData));
newNode->previous = tail;
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void DoubleLinkedList<T>::push_back(T &&thedata) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(std::move(thedata));
newNode->previous = tail;
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void DoubleLinkedList<T>::push_front(const T &theData) {
head = std::make_unique<Node>(std::move(head), nullptr, theData);
if (!(head->next)) {
tail = head.get();
}
}
template <class T>
void DoubleLinkedList<T>::push_front(T &&theData) {
head = std::make_unique<Node>(std::move(head),nullptr,std::move(theData));
if (!(head->next)) {
tail = head.get();
}
}
template <class T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::insert(const_iterator pos, const T& theData) {
return emplace(pos, theData);
}
template <class T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::insert(const_iterator pos, T&& theData) {
return emplace(pos, std::move(theData));
}
template <class T>
void DoubleLinkedList<T>::pop_front() {
if (empty()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
do_pop_front();
}
template <class T>
void DoubleLinkedList<T>::pop_back() {
if (!head) {
return;
}
if (head) {
auto current = head.get();
Node* prev = nullptr;
while (current->next) {
prev = current;
current = current->next.get();
}
tail = prev;
prev->next = nullptr;
}
else {
throw std::out_of_range("The list is empty, nothing to delete.");
}
}
template <class T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::erase(const_iterator pos) {
if (pos.end_reached) {
pop_back();
return end();
}
if (pos.node && pos.node->next) {
pos.node->next = std::move(pos.node->previous->next);
return { pos.node->previous };
}
return begin();
}
template <class T>
bool DoubleLinkedList<T>::search(const T &x) {
return std::find(begin(), end(), x) != end();
}
template <typename T>
std::ostream& operator<<(std::ostream &str, DoubleLinkedList<T>& list) {
for (auto const& item : list) {
str << item << "\t";
}
return str;
}
// Iterator Implementaion////////////////////////////////////////////////
template <class T>
typename DoubleLinkedList<T>::iterator& DoubleLinkedList<T>::iterator::operator++() {
if (!node) return *this;
if (node->next) {
node = node->next.get();
}
else {
end_reached = true; // keep last node, so we can go backwards if required
}
return *this;
}
template<typename T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::iterator::operator++(int) {
auto copy = *this;
++*this;
return copy;
}
template <class T>
typename DoubleLinkedList<T>::iterator& DoubleLinkedList<T>::iterator::operator--() {
if (!node) return *this;
if (end_reached) {
end_reached = false;
}
else if (node->previous) {
node = node->previous.get();
}
return *this;
}
template<typename T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::iterator::operator--(int) {
auto copy = *this;
--*this;
return copy;
}
template<typename T>
bool DoubleLinkedList<T>::iterator::operator==(iterator other) const noexcept {
if (end_reached) return other.end_reached;
if (other.end_reached) return false;
return node == other.node;
}
template<typename T>
bool DoubleLinkedList<T>::iterator::operator!=(iterator other) const noexcept {
return !(*this == other);
}
template<class T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::begin() {
return head.get();
}
template<class T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::end() {
return {tail, true};
}
template <class T>
typename DoubleLinkedList<T>::iterator DoubleLinkedList<T>::before_begin() {
return { head.get(), false };
}
// Const Iterator Implementaion////////////////////////////////////////////////
template <class T>
typename DoubleLinkedList<T>::const_iterator& DoubleLinkedList<T>::const_iterator::operator++() {
if (!node) return *this;
if (node->next) {
node = node->next.get();
}
else {
end_reached = true; // keep last node, so we can go backwards if required
}
return *this;
}
template<typename T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::const_iterator::operator++(int) {
auto copy = *this;
++*this;
return copy;
}
template <class T>
typename DoubleLinkedList<T>::const_iterator& DoubleLinkedList<T>::const_iterator::operator--() {
if (!node) return *this;
if (end_reached) {
end_reached = false;
}
else if (node->previous) {
node = node->previous.get();
}
return *this;
}
template<class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::const_iterator::operator--(int) {
auto copy = *this;
--*this;
return copy;
}
template<class T>
bool DoubleLinkedList<T>::const_iterator::operator==(const_iterator other) const noexcept {
if (end_reached) return other.end_reached;
if (other.end_reached) return false;
return node == other.node;
}
template<class T >
bool DoubleLinkedList<T>::const_iterator::operator!=(const_iterator other) const noexcept {
return !(*this == other);
}
template <class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::begin() const {
return head.get();
}
template <class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::end() const {
return {tail, true};
}
template <class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::cbegin() const {
return begin();
}
template <class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::cend() const {
return end();
}
template <class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::before_begin() const {
return { head.get(), true };
}
template <class T>
typename DoubleLinkedList<T>::const_iterator DoubleLinkedList<T>::cbefore_begin() const {
return before_begin();
}
#endif
</code></pre>
<p>Here is the main.cpp file:</p>
<pre><code>#include <iostream>
#include <iterator>
#include <memory>
#include <utility>
#include <stdexcept>
#include <iosfwd>
#include <type_traits>
#include <ostream>
#include "SingleLinkedList.h"
#include "DoubleLinkedList.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////
///////////////////////////// Double Linked List //////////////////////
///////////////////////////////////////////////////////////////////////
DoubleLinkedList<int> obj;
obj.push_back(2);
obj.push_back(4);
obj.push_back(6);
obj.push_back(8);
obj.push_back(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------displaying all nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.push_front(1);
std::cout << obj << "\n";
std::cout << "\n--------------------------------------------------\n";
std::cout << "-------------Get current size ---=--------------------";
std::cout << "\n--------------------------------------------------\n";
std::cout << obj.size() << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_front();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at end-----------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_back();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------inserting at particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insert(obj.cend(),60);
std::cout << obj << "\n";
std::cout<<"\n----------------------------------------------------------\n";
std::cout<<"--------------Deleting after particular position--------------";
std::cout<<"\n-----------------------------------------------------------\n";
obj.erase(obj.cend());
std::cout << obj << "\n";
obj.search(8) ? printf("yes"):printf("no");
std::cout << "\n--------------------------------------------------\n";
std::cout << "--------------Testing copy----------------------------";
std::cout << "\n--------------------------------------------------\n";
DoubleLinkedList<int> obj1 = obj;
std::cout << obj1 << "\n";
std::cin.get();
}
</code></pre>
| [] | [
{
"body": "<p>It is great to see you are really taking reviews seriously and are trying to learn something and improve yourself. That really makes us reviewers like what we are doing. I may not be the best here, but I will still try :)</p>\n\n<p>I very much like your approach with smart pointers (<code>unique_p... | {
"AcceptedAnswerId": "202341",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T19:24:26.867",
"Id": "202333",
"Score": "4",
"Tags": [
"c++",
"linked-list",
"pointers"
],
"Title": "Double Linked List Using Smart Pointers"
} | 202333 |
<p>I implemented a custom Sliding Window Spliterator in Java.
Do you have any ideas how this could be improved?</p>
<p>Thinking if replacing the buffer with a plain array could have a positive impact on the performance side of things if done correctly.</p>
<p>I'm not going to use that code in any production system, just exercising.</p>
<pre><code>public class WindowSpliterator<T> implements Spliterator<Stream<T>> {
static <T> Stream<Stream<T>> windowed(Collection<T> stream, int windowSize) {
return StreamSupport.stream(new WindowSpliterator<>(stream, windowSize), false);
}
private final Queue<T> buffer;
private final Iterator<T> sourceIterator;
private final int windowSize;
private WindowSpliterator(Collection<T> collection, int windowSize) {
this.buffer = new ArrayDeque<>(windowSize);
this.sourceIterator = Objects.requireNonNull(collection).iterator();
this.windowSize = windowSize;
}
@Override
public boolean tryAdvance(Consumer<? super Stream<T>> action) {
if (windowSize < 1) {
return false;
}
while (sourceIterator.hasNext()) {
buffer.add(sourceIterator.next());
if (buffer.size() == windowSize) {
action.accept(Arrays.stream((T[]) buffer.toArray(new Object[0])));
buffer.poll();
return sourceIterator.hasNext();
}
}
if (!buffer.isEmpty()) {
action.accept(buffer.stream());
}
return false;
}
@Override
public Spliterator<Stream<T>> trySplit() {
return null;
}
@Override
public long estimateSize() {
return Long.MAX_VALUE;
}
@Override
public int characteristics() {
return ORDERED | NONNULL;
}
}
</code></pre>
| [] | [
{
"body": "<p>I'm curious why you are using:</p>\n\n<pre><code>action.accept(Arrays.stream((T[]) buffer.toArray(new Object[0])));\n</code></pre>\n\n<p>It seems to me that <code>action.accept(buffer.stream())</code> would work here, as long as the <code>action.accept()</code> fully processes the produced stream ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T20:25:27.230",
"Id": "202339",
"Score": "1",
"Tags": [
"java",
"stream"
],
"Title": "Sliding Window Spliterator in Java"
} | 202339 |
<p>A simple concept yet I seem to have written it in a complicated way.</p>
<p>I have written some C++ source code that should:</p>
<ul>
<li>read in a file</li>
<li>parse it</li>
<li>save the data to a class</li>
<li>print out all the saved class data</li>
</ul>
<p>I am absolutely new to C++ and OOP and Programming and English.</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
class Person {
private:
int age;
std::string name;
public:
void setAge(int age) {
this->age = age;
}
int getAge() {
return age;
}
void setName(std::string name) {
this->name = name;
}
std::string getName() {
return name;
}
void printInfo() {
std::cout
<< "Name: " << getName() << '\n'
<< "Age: " << getAge() << '\n';
}
};
std::istream& operator>> (std::istream& is, Person& person) {
int age;
is >> age;
std::string name;
is >> name;
person.setAge(age);
person.setName(name);
return is;
}
int main() {
auto myfilename = "unknown-people.txt";
std::ofstream myfile(myfilename, std::ios::binary | std::ios::trunc);
myfile << "3 Baby\n";
myfile << "48 Linus Torvalds\n";
myfile << "62 Bill Gates\n";
myfile << "115 Kane Tanaka\n";
myfile.close();
std::ifstream mysamefile(myfilename, std::ios::binary);
std::string details;
std::vector<Person> people;
while (std::getline(mysamefile, details)) {
Person person;
std::istringstream personDetails(details);
personDetails >> person;
people.push_back(person);
}
mysamefile.close();
for (std::vector<Person>::iterator it = people.begin(); it != people.end(); ++it) {
it->printInfo();
if (!(it != people.end() && it == --people.end())) {
std::cout << "\n\n";
}
}
}
</code></pre>
| [] | [
{
"body": "<p>You seem to have a good grasp of the concepts - this is looking pretty good for a first effort!</p>\n<p>Those accessors (<code>setAge()</code> + <code>getAge()</code>, and <code>setName()</code> + <code>getName()</code>) are exactly equivalent to making the members <code>age()</code> and <code>nam... | {
"AcceptedAnswerId": "202374",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T21:47:59.297",
"Id": "202344",
"Score": "5",
"Tags": [
"c++",
"beginner"
],
"Title": "Read a Person object from file stream"
} | 202344 |
<h2>INTRO</h2>
<p>I am using an Excel worksheet as my "database." No headers so <code>[F1]</code> is assigned to column one by default. I filled the entire column, all 1,048,576 cells with <code>RANDBETWEEN(1,20)</code>. I then hard set these values by copy/pasting as value.</p>
<p>It is very slow. Much slower than using Excel functions would be to generate same data. I realize that I could use 1,048,576 as a constant denominator but I wanted to practice with SQL query language, and keep model more dynamic.</p>
<p>EDIT: it should not say % in results not many times. I am getting the % of times each var occurred in my data set. I am basically seeing what the distribution is of randbetween(1-20) outputs are over X calls. In this instance x is 1,048,576.</p>
<p>My SQL Query</p>
<pre><code>"SELECT Round(SUM(IIF([F1]=" & searchKey & ",1,0))*100.0/SUM(IIF([F1]<> Null,1,0)),10) From [Sheet1$];"
</code></pre>
<p>Is returning the total number of records in column F1 that are equal to searchKey and dividing that number by the total number of records in column F1.</p>
<h2>CODE</h2>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long
Sub SqlQueryOnWorkSheet()
Dim started As Long
Dim cn As ADODB.Connection
Dim filePath As String
Dim counter As Long
Dim outCome As Double
Dim ended As Long
started = timeGetTime
filePath = "Z:\Test\Test1.xlsx"
Set cn = EstablishConnection(filePath)
If cn.State <> 1 Then GoTo CleanFail:
For counter = 1 To 20
outCome = FindCount(cn, counter)
PrintOutcome counter, outCome
Next counter
cn.Close
Set cn = Nothing
ended = timeGetTime
Debug.Print "QUERIES RAN IN " & (ended - started) / 1000 & " SECONDS"
Exit Sub
CleanFail:
Debug.Print "CONNECTION COULD NOT BE MADE"
End Sub
Function EstablishConnection(ByVal filePath As String) As ADODB.Connection
Set EstablishConnection = New ADODB.Connection
EstablishConnection.Open _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & filePath & "';" & _
"Extended Properties=""Excel 12.0 Macro;HDR=No;IMEX=1;"";"
End Function
Function FindCount(ByRef cn As ADODB.Connection, ByVal searchKey As Long) As Double
Dim strSql As String
Dim rs As ADODB.Recordset
On Error GoTo CleanFail:
Set rs = New ADODB.Recordset
strSql = "SELECT Round(SUM(IIF([F1]=" & searchKey & ",1,0))*100.0/SUM(IIF([F1]<> Null,1,0)),10) From [Sheet1$];"
rs.Open strSql, cn
FindCount = rs.GetString
rs.Close
Set rs = Nothing
Exit Function
CleanFail:
Debug.Print "QUERY FAILED"
End Function
Sub PrintOutcome(ByVal counter As Long, ByVal outCome As Double)
Debug.Print "Variable " & counter & " Occured " & outCome & " Many Times"
End Sub
</code></pre>
<h2>Results</h2>
<p>EDIT: THIS SHOULD BE % NOT MANY -- FIXED</p>
<pre class="lang-none prettyprint-override"><code>Variable 1 Occured 4.9837112427 % Of Time
Variable 2 Occured 5.0171852112 % Of Time
Variable 3 Occured 4.9752235413 % Of Time
Variable 4 Occured 4.9716949463 % Of Time
Variable 5 Occured 5.0051689148 % Of Time
Variable 6 Occured 4.9989700317 % Of Time
Variable 7 Occured 4.9901008606 % Of Time
Variable 8 Occured 5.0283432007 % Of Time
Variable 9 Occured 5.0018310547 % Of Time
Variable 10 Occured 5.0164222717 % Of Time
Variable 11 Occured 4.9933433533 % Of Time
Variable 12 Occured 5.0059318542 % Of Time
Variable 13 Occured 5.0333976746 % Of Time
Variable 14 Occured 4.9952507019 % Of Time
Variable 15 Occured 5.0163269043 % Of Time
Variable 16 Occured 4.9654006958 % Of Time
Variable 17 Occured 4.9822807312 % Of Time
Variable 18 Occured 5.0310134888 % Of Time
Variable 19 Occured 5.0113677979 % Of Time
Variable 20 Occured 4.9770355225 % Of Time
QUERIES RAN IN 38.754 SECONDS
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T22:13:11.393",
"Id": "389892",
"Score": "1",
"body": "Guessing that since `RANDBETWEEN` is volatile, it's updating every single one of the 1,048,576 results every time the cursor moves for a read..."
},
{
"ContentLicense": "... | [
{
"body": "<p>The reason for the poor performance is that you are taking a non database approach to compiling the data. A query's speed is dependent on its ability to group, filter and index records. </p>\n\n<blockquote>\n<pre><code>SELECT \nRound(SUM(IIF([F1]=\" & searchKey & \",1,0))\n*100.0\n/SUM(I... | {
"AcceptedAnswerId": "202392",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T21:53:21.300",
"Id": "202345",
"Score": "3",
"Tags": [
"performance",
"sql",
"vba",
"excel",
"error-handling"
],
"Title": "Running SQL Queries On A Worksheet (With Set Of Random Numbers Between 1-20 Filling Column A) Handled As An ADO"
} | 202345 |
<p>Just made a simple <code>Vec</code> class, nothing fancy but I am open to suggestions for improvements. Of course, this is not suppose to replace or used for the same tasks as <code>std::vector</code>. This is more like opencv's <code>Vec</code> and eventually I want to include this in a bigger project of mine.</p>
<pre><code>#include <cmath>
#include <vector>
#include <initializer_list>
#include <cassert>
#define VEC_ASSERT(x) assert(x)
template<typename T, unsigned int C>
class Vec {
public:
typedef T dataType;
typedef T& dataType_ref;
typedef const T& dataType_cref;
// Empty Constructor
Vec();
// Single-Arg Constructor
explicit Vec(T v);
// From std::vector Constructor
Vec(const std::vector<T>& v);
// From std::initializer_list Constructor
Vec(const std::initializer_list<T>& l);
// Main Constructor
template<typename ... Args>
explicit Vec(T v, Args&& ... args);
// Get vector dimensions
unsigned int dim() const;
// Get vector length
double length() const;
// Get vectors dist
double dist(const Vec<T, C>& v) const;
// Get the cross product (3D Vectors only)
Vec<T, C> cross(const Vec<T, C>& v) const;
// Get the dot product
double dot(const Vec<T, C>& v) const;
// Get ortho vector (2D vectors only)
Vec<T, C> ortho() const;
// Normalize vector values
Vec<T, C> norm() const;
// Rotate (2D Vectors only)
Vec<T, C> rotate(double angle) const;
// Rotate on x-axis (3D Vectors only)
Vec<T, C> rotateX(double angle) const;
// Rotate on y-axis (3D Vectors only)
Vec<T, C> rotateY(double angle) const;
// Rotate on z-axis (3D Vectors only)
Vec<T, C> rotateZ(double angle) const;
// Convert to std::vector
std::vector<dataType> to_std_vector() const;
// Cast
template<typename TT, unsigned int CC = C>
Vec<TT, CC> to() const;
// Access vector values
dataType_ref operator[](int index);
dataType_ref operator()(int index);
dataType_cref operator[](int index) const;
dataType_cref operator()(int index) const;
// Vector Operations with Scalars
Vec<T, C> operator+(T v);
Vec<T, C> operator-(T v);
Vec<T, C> operator*(T v);
Vec<T, C> operator/(T v);
Vec<T, C>& operator+=(T v);
Vec<T, C>& operator-=(T v);
Vec<T, C>& operator*=(T v);
Vec<T, C>& operator/=(T v);
// Vector Operations with Vectors
Vec<T, C> operator+(const Vec<T, C>& v);
Vec<T, C> operator-(const Vec<T, C>& v);
Vec<T, C> operator*(const Vec<T, C>& v);
Vec<T, C> operator/(const Vec<T, C>& v);
private:
// Recursive pusher (used by constructor)
template<typename ... Args>
void push(T v, Args&& ... args);
// Base pusher
void push(T v);
// Vector values
dataType values[C];
// Index for Vector pusher
unsigned int idx;
};
template<typename T, unsigned int C>
Vec<T, C>::Vec() {
for ( unsigned int i = 0; i < C; ++i )
this->values[i] = 0;
}
template<typename T, unsigned int C>
Vec<T, C>::Vec(T v) {
for ( unsigned int i = 0; i < C; ++i )
this->values[i] = v;
}
template<typename T, unsigned int C>
Vec<T, C>::Vec(const std::vector<T>& v) {
VEC_ASSERT(v.size() <= C);
for ( unsigned i = 0; i < v.size(); ++i )
this->values[i] = v[i];
}
template<typename T, unsigned int C>
Vec<T, C>::Vec(const std::initializer_list<T>& l) {
VEC_ASSERT(l.size() <= C);
unsigned i = 0;
for ( auto it : l )
this->values[i++] = it;
}
template<typename T, unsigned int C>
template<typename ... Args>
Vec<T, C>::Vec(T v, Args&& ... args) {
this->idx = 0;
this->values[idx] = v;
this->push(args ...);
}
template<typename T, unsigned int C>
template<typename ... Args>
void Vec<T, C>::push(T v, Args&& ... args) {
this->values[++(this->idx)] = v;
this->push(args ...);
}
template<typename T, unsigned int C>
void Vec<T, C>::push(T v) {
VEC_ASSERT(this->idx + 1 < C);
this->values[++(this->idx)] = v;
}
template<typename T, unsigned int C>
unsigned int Vec<T, C>::dim() const {
return C;
}
template<typename T, unsigned int C>
double Vec<T, C>::length() const {
double result = 0;
for ( unsigned int i = 0; i < C; ++i )
result += this->values[i] * this->values[i];
return std::sqrt(result);
}
template<typename T, unsigned int C>
double Vec<T, C>::dist(const Vec<T, C>& v) const {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] - v[i];
return result.length();
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::cross(const Vec<T, C>& v) const {
VEC_ASSERT(C == 3);
Vec<T, C> result;
result[0] = this->values[1] * v[2] - this->values[2] * v[1];
result[1] = this->values[0] * v[2] - this->values[2] * v[0];
result[2] = this->values[0] * v[0] - this->values[1] * v[0];
return result;
}
template<typename T, unsigned int C>
double Vec<T, C>::dot(const Vec<T, C>& v) const {
double result = 0.0;
for ( unsigned int i = 0; i < C; ++i )
result += this->values[i] * v[i];
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::ortho() const {
VEC_ASSERT(C == 2);
return Vec<T, C>(this->values[1], -(this->values[0]));
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::norm() const {
VEC_ASSERT(this->length() != 0);
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] * (1.0 / this->length());
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::rotate(double angle) const {
VEC_ASSERT(C == 2);
double theta = angle / 180.0 * M_PI;
double c = std::cos(theta);
double s = std::sin(theta);
double x = this->values[0] * c - this->values[1] * s;
double y = this->values[0] * s + this->values[1] * c;
return Vec<T, C>(x, y);
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::rotateX(double angle) const {
VEC_ASSERT(C == 3);
double theta = angle / 180.0 * M_PI;
double c = std::cos(theta);
double s = std::sin(theta);
double x = this->values[0];
double y = this->values[1] * c - this->values[2] * s;
double z = this->values[1] * s + this->values[2] * c;
return Vec<T, C>(x, y, z);
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::rotateY(double angle) const {
VEC_ASSERT(C == 3);
double theta = angle / 180.0 * M_PI;
double c = std::cos(theta);
double s = std::sin(theta);
double x = this->values[0] * c + this->values[2] * s;
double y = this->values[1];
double z = -(this->values[0]) * s + this->values[2] * c;
return Vec<T, C>(x, y, z);
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::rotateZ(double angle) const {
VEC_ASSERT(C == 3);
double theta = angle / 180.0 * M_PI;
double c = std::cos(theta);
double s = std::sin(theta);
double x = this->values[0] * c - this->values[1] * s;
double y = this->values[0] * s + this->values[1] * c;
double z = this->values[2];
return Vec<T, C>(x, y, z);
}
template<typename T, unsigned int C>
auto Vec<T, C>::to_std_vector() const -> std::vector<dataType> {
return std::vector<dataType>(&this->values[0], &this->values[0] + C);
}
template<typename T, unsigned int C>
template<typename TT, unsigned int CC>
Vec<TT, CC> Vec<T, C>::to() const {
Vec<TT, CC> result;
for ( unsigned int i = 0; i < std::min(C, CC); ++i )
result[i] = static_cast<TT>(this->values[i]);
return result;
}
template<typename T, unsigned int C>
auto Vec<T, C>::operator[](int index) -> dataType_ref {
VEC_ASSERT(index < C);
return this->values[index];
}
template<typename T, unsigned int C>
auto Vec<T, C>::operator()(int index) -> dataType_ref {
VEC_ASSERT(index < C);
return this->values[index];
}
template<typename T, unsigned int C>
auto Vec<T, C>::operator[](int index) const -> dataType_cref {
VEC_ASSERT(index < C);
return this->values[index];
}
template<typename T, unsigned int C>
auto Vec<T, C>::operator()(int index) const -> dataType_cref {
VEC_ASSERT(index < C);
return this->values[index];
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator+(T v) {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] + v;
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator-(T v) {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] - v;
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator*(T v) {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] * v;
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator/(T v) {
VEC_ASSERT(v != 0);
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] / v;
return result;
}
template<typename T, unsigned int C>
Vec<T, C>& Vec<T, C>::operator+=(T v) {
for ( unsigned int i = 0; i < C; ++i )
this->values[i] += v;
return *this;
}
template<typename T, unsigned int C>
Vec<T, C>& Vec<T, C>::operator-=(T v) {
for ( unsigned int i = 0; i < C; ++i )
this->values[i] -= v;
return *this;
}
template<typename T, unsigned int C>
Vec<T, C>& Vec<T, C>::operator*=(T v) {
for ( unsigned int i = 0; i < C; ++i )
this->values[i] *= v;
return *this;
}
template<typename T, unsigned int C>
Vec<T, C>& Vec<T, C>::operator/=(T v) {
VEC_ASSERT(v != 0);
for ( unsigned int i = 0; i < C; ++i )
this->values[i] /= v;
return *this;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator+(const Vec<T, C>& v) {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] + v[i];
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator-(const Vec<T, C>& v) {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] - v[i];
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator*(const Vec<T, C>& v) {
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] * v[i];
return result;
}
template<typename T, unsigned int C>
Vec<T, C> Vec<T, C>::operator/(const Vec<T, C>& v) {
for ( unsigned int i = 0; i < C; ++i )
VEC_ASSERT(v[i] != 0);
Vec<T, C> result;
for ( unsigned int i = 0; i < C; ++i )
result[i] = this->values[i] / v[i];
return result;
}
typedef Vec<int, 2> Vec2i;
typedef Vec<int, 3> Vec3i;
typedef Vec<int, 4> Vec4i;
typedef Vec<unsigned int, 2> Vec2u;
typedef Vec<unsigned int, 3> Vec3u;
typedef Vec<unsigned int, 4> Vec4u;
typedef Vec<float, 2> Vec2f;
typedef Vec<float, 3> Vec3f;
typedef Vec<float, 4> Vec4f;
typedef Vec<double, 2> Vec2d;
typedef Vec<double, 3> Vec3d;
typedef Vec<double, 4> Vec4d;
typedef Vec<char, 2> Vec2c;
typedef Vec<char, 3> Vec3c;
typedef Vec<char, 4> Vec4c;
typedef Vec<unsigned char, 2> Vec2uc;
typedef Vec<unsigned char, 3> Vec3uc;
typedef Vec<unsigned char, 4> Vec4uc;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T19:49:21.493",
"Id": "390095",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your edits. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated a... | [
{
"body": "<pre><code>template<typename T, unsigned int C>\nclass Vec;\n</code></pre>\n\n<p>The template generates redundant codes if <code>C</code> varies for the same <code>T</code>.<br>\nYou can look through <code><<Effective C++>> Item 44</code> and refactor like this:</p>\n\n<pre><code>te... | {
"AcceptedAnswerId": "202462",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T21:58:24.300",
"Id": "202346",
"Score": "4",
"Tags": [
"c++",
"vectors"
],
"Title": "A simple Vector implementation"
} | 202346 |
<p>I'd like to improve how ownership is handled within a simple interpreter written in Rust. The interpreter takes simple calculator like expressions and returns either a string of the AST or a number of the evaluation:</p>
<pre><code>// Simple expression for working on numbers
enum Exp {
Add { e1 : Box <Exp>, e2 : Box <Exp> },
Mul { e1 : Box <Exp>, e2 : Box <Exp> },
Int { i : i32}
}
// Evaluate an expression to a number
fn exp_to_num(e : Exp) -> i32 {
match e {
Exp::Add {e1,e2} => return exp_to_num(*e1) + exp_to_num(*e2),
Exp::Mul {e1,e2} => return exp_to_num(*e1) * exp_to_num(*e2),
Exp::Int {i} => return i
}
}
// Evaluate an expression to a string
fn exp_to_str(e : Exp) -> String {
match e {
Exp::Add {e1,e2} =>
return format!("({}) + ({})",exp_to_str(*e1),exp_to_str(*e2)),
Exp::Mul {e1,e2} =>
return format!("({}) * ({})",exp_to_str(*e1),exp_to_str(*e2)),
Exp::Int {i} =>
return format!("{}",i)
}
}
fn main() {
// Create an expression
let e1 = Exp::Add {
e1 : Box::new(Exp::Mul {
e1 : Box::new(Exp::Int { i : 2 }),
e2 : Box::new(Exp::Int { i : 3 })}),
e2 : Box::new(Exp::Int {i : 4})};
// Evaluate the expression
println!("e1 : {}", exp_to_num(e1));
//println!("e1 : {}", exp_to_str(e1));
}
</code></pre>
<p>The last command can not be uncommented since it appears as though <code>exp_to_num</code> takes ownership of <code>e1</code>. I'd like to fix this.</p>
<p>In C++, I'd just make the arguments <code>const &</code>. In Rust, my best attempt at this is the following code:</p>
<pre><code>// Simple expression for working on numbers
enum Exp {
Add { e1 : Box <Exp>, e2 : Box <Exp> },
Mul { e1 : Box <Exp>, e2 : Box <Exp> },
Int { i : i32}
}
// Evaluate an expression to a number
fn exp_to_num(e : & Exp) -> i32 {
match *e {
Exp::Add {ref e1,ref e2} => return exp_to_num(&*e1) + exp_to_num(&*e2),
Exp::Mul {ref e1,ref e2} => return exp_to_num(&*e1) * exp_to_num(&*e2),
Exp::Int {i} => return i
}
}
// Evaluate an expression to a string
fn exp_to_str(e : & Exp) -> String {
match *e {
Exp::Add {ref e1,ref e2} =>
return format!("({}) + ({})",exp_to_str(&*e1),exp_to_str(&*e2)),
Exp::Mul {ref e1,ref e2} =>
return format!("({}) * ({})",exp_to_str(&*e1),exp_to_str(&*e2)),
Exp::Int {i} =>
return format!("{}",i)
}
}
fn main() {
// Create an expression
let e1 = Exp::Add {
e1 : Box::new(Exp::Mul {
e1 : Box::new(Exp::Int { i : 2 }),
e2 : Box::new(Exp::Int { i : 3 })}),
e2 : Box::new(Exp::Int {i : 4})};
// Evaluate the expression
println!("e1 : {}", exp_to_num(&e1));
println!("e1 : {}", exp_to_str(&e1));
}
</code></pre>
<p>Though this works, it feels verbose. Specifically, it feels verbose to match references, <code>Exp::Add {ref e1,ref e2}</code>, and verbose to find a reference to an unboxed expression, <code>exp_to_num(&*e1)</code>. Can passing a constant reference be made more concise and compact?</p>
<p>Alternatively, we could just clone the memory, which gives</p>
<pre><code>// Simple expression for working on numbers
#[derive(Clone)]
enum Exp {
Add { e1 : Box <Exp>, e2 : Box <Exp> },
Mul { e1 : Box <Exp>, e2 : Box <Exp> },
Int { i : i32}
}
// Evaluate an expression to a number
fn exp_to_num(e : Exp) -> i32 {
match e {
Exp::Add {e1,e2} => return exp_to_num(*e1) + exp_to_num(*e2),
Exp::Mul {e1,e2} => return exp_to_num(*e1) * exp_to_num(*e2),
Exp::Int {i} => return i
}
}
// Evaluate an expression to a string
fn exp_to_str(e : Exp) -> String {
match e {
Exp::Add {e1,e2} =>
return format!("({}) + ({})",exp_to_str(*e1),exp_to_str(*e2)),
Exp::Mul {e1,e2} =>
return format!("({}) * ({})",exp_to_str(*e1),exp_to_str(*e2)),
Exp::Int {i} =>
return format!("{}",i)
}
}
fn main() {
// Create an expression
let e1 = Exp::Add {
e1 : Box::new(Exp::Mul {
e1 : Box::new(Exp::Int { i : 2 }),
e2 : Box::new(Exp::Int { i : 3 })}),
e2 : Box::new(Exp::Int {i : 4})};
// Evaluate the expression
println!("e1 : {}", exp_to_num(e1.clone()));
println!("e1 : {}", exp_to_str(e1.clone()));
}
</code></pre>
<p>This also feels somewhat verbose because we have to call clone rather than just allowing an implicit copy. Is a clone required due to <code>Box</code>? Can this be made more concise?</p>
| [] | [
{
"body": "<ol>\n<li><p>Learn to love <a href=\"https://github.com/rust-lang-nursery/rustfmt\" rel=\"noreferrer\">rustfmt</a>. It will correct your code to the idiomatic Rust style.</p></li>\n<li><p>Learn to love <a href=\"https://github.com/rust-lang-nursery/rust-clippy\" rel=\"noreferrer\">clippy</a>. It will... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T22:17:36.413",
"Id": "202347",
"Score": "5",
"Tags": [
"rust",
"interpreter"
],
"Title": "Simple interpreter written in Rust"
} | 202347 |
<p>I am creating a simple bot that collects coins in-game. The code runs under a game-loop so there are 60 ticks p/s</p>
<p>Here is the function that I use to check for the nearest coin (Game object) to be collected:</p>
<pre><code>public GameObject getNearest(ID objectID) {
LinkedList<GameObject> object = new LinkedList<GameObject>();
for (int i = 0; i < handler.object.size(); i++) {
GameObject temp = handler.object.get(i);
if (temp.getId() == objectID) {
object.add(temp);
}
}
if (object.size() == 0)
return null;
else {
GameObject nearest = object.get(0);
for (int i = 0; i < object.size(); i++) {
if (getDistance(this, object.get(i)) < getDistance(this, nearest)) {
nearest = object.get(i);
}
object.remove(i);
}
return nearest;
}
}
</code></pre>
<p>What this function would do is check for all the game objects, and add all the once that match the parameter in a list. It then will loop through the list and check for the nearest coin to the bot.</p>
<p>Is my function efficient regarding performance, speed, and memory usage? By calling the object.remove after every check, does it help? (If not, please mention why)</p>
<p>Is it okay that it calls the method 60 times p/s or I should limit it to execute once every 20 frames maybe? The thing is that I want it to be collecting the coins safely in the shortest time possible. Is there anything that I should take into consideration or something to improve in my code??</p>
| [] | [
{
"body": "<p><code>object</code> should be plural, and should more clearly indicate what it contains. <code>gameObjects</code> would be preferable.</p>\n\n<p>It's a good idea to always include curly braces, even when they're not required. It removes a possible source of later bugs.</p>\n\n<p>It’s easier to rea... | {
"AcceptedAnswerId": "202354",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T23:03:21.653",
"Id": "202351",
"Score": "2",
"Tags": [
"java",
"performance",
"memory-optimization"
],
"Title": "Find the nearest coin to be collected in a game"
} | 202351 |
<p>For a new project, I've started learning Golang. This is one of my very first steps in Go.</p>
<p>The objective that I've given myself is to convert int to a String representing the roman numeral of that int. The supported range shall start with 0, negative numbers can be ignored, and it's okay for now that for negative numbers, an empty String is returned.</p>
<h2>File <code>roman_test.go</code></h2>
<pre><code>package main
import "testing"
func TestRoman(t *testing.T) {
testcases := []struct {
number int
roman string
}{
{ 0, "" },
{ 1, "I" },
{ 2, "II" },
{ 4, "IV" },
{ 5, "V" },
{ 1993, "MCMXCIII" },
{ 2018, "MMXVIII" },
{ 1111, "MCXI" },
{ 2222, "MMCCXXII" },
{ 444, "CDXLIV" },
{ 555, "DLV" },
{ 666, "DCLXVI" },
{ 999, "CMXCIX" },
}
for _, testcase := range testcases {
roman := Roman(testcase.number)
if roman != testcase.roman {
t.Errorf("%d expected to convert to %s, got: %s.", testcase.number, testcase.roman, roman)
}
}
}
</code></pre>
<h2>File <code>roman.go</code></h2>
<pre><code>package main
func Roman(number int) string {
conversions := []struct{
value int
digit string
}{
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
}
roman := ""
for _, conversion := range conversions {
for number >= conversion.value {
roman += conversion.digit
number -= conversion.value
}
}
return roman
}
</code></pre>
<p>I'm mainly interested in feedback on the following aspects:</p>
<ul>
<li>Go code style</li>
<li>Idiomatic go</li>
<li>Better structure</li>
</ul>
| [] | [
{
"body": "<p>Your code is well formatted and structured.</p>\n\n<p>Nice usage of anonymous struct at Roman function, but don't overuse them: your test cases may be written as a map and it's <em>preferable way</em>.</p>\n\n<pre><code>testcases := map[int]string{\n 0: \"\",\n 1: \"I\",\n 2: \"I... | {
"AcceptedAnswerId": "202394",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T23:10:40.187",
"Id": "202352",
"Score": "3",
"Tags": [
"beginner",
"go",
"roman-numerals"
],
"Title": "int to Roman numerals in Go / Golang"
} | 202352 |
<p>I have been trying to learn Python and just solved <a href="https://projecteuler.net/problem=3" rel="nofollow noreferrer">Euler Problem 3</a>:</p>
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p>
</blockquote>
<p>I am looking for any feedback on improving efficiency and the code itself.</p>
<p>My code:</p>
<pre><code>from itertools import count, islice
def is_prime(number):
for n in islice(count(2), int(number**0.5 -1)):
if number % n == 0:
return False
return True
def find_factors(number):
lst = []
for n in islice(count(2), int(number/2-1)):
if number % n == 0:
if is_prime(n):
lst.append(n)
return lst
print(find_factors(13195).pop())
</code></pre>
<p>I used <code>islice</code> instead of <code>xrange</code> because of <code>int</code> limits, which I learned about from another question at StackOverflow.com</p>
<p>In code above, I have created two separate functions, one to find a prime and the other to find factors.</p>
<p>The program works this way,</p>
<ul>
<li>It takes an input number</li>
<li>Find all the factors of that number from <code>2->number/2</code></li>
<li>If it finds a factor, it checks if its a prime, and append it to a list.</li>
<li>Eventually I print the last element of list since list in python are ordered.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T02:03:40.120",
"Id": "389914",
"Score": "0",
"body": "There are far more efficient methods to get the result. I suggest to have a look at [other Q&A's about the same problem](https://codereview.stackexchange.com/search?q=%5Bpython%5... | [
{
"body": "<p>When I look at your solution, the first impression I get is that it's too complicated. To solve the problem you don't need any fancy algorithms for prime numbers, or <code>islice</code> and <code>count</code>. It's a simple task of trying to divide by possible factors. </p>\n\n<p>One important thi... | {
"AcceptedAnswerId": "202370",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T01:13:16.507",
"Id": "202355",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"primes"
],
"Title": "Euler problem 3: largest prime factor of the number"
} | 202355 |
<p>I'm pretty new to working with databases, and I would like to know if I've made some common, major design flaws in my implementation. For context, the whole project is intended to be used by a single user.</p>
<p>The code I want reviewed:</p>
<pre><code>class DatabaseConnection
{
//properties
private MySqlConnection _connection;
public MySqlConnection Connection { get { return _connection; } }
public AccountLogin AccountCredentials { get; }
public DatabaseLogin DatabaseCredentials { get; }
//constructor
public DatabaseConnection(AccountLogin _AccCred,
DatabaseLogin _DBCred)
{
AccountCredentials = _AccCred;
DatabaseCredentials = _DBCred;
}
public void Connect()
{
if (Connection != null)
{
return;
}
string[] UserInputs =
{
DatabaseCredentials?.DatabaseName,
DatabaseCredentials?.Server,
DatabaseCredentials?.Port,
AccountCredentials?.Password,
AccountCredentials?.Username
};
bool ChkInpts = Validators.NullStringValidator(UserInputs);
if (!ChkInpts)
{
string ConnInfo = "server=" + DatabaseCredentials.Server + ";" +
"user=" + AccountCredentials.Username + ";" +
"database=" + DatabaseCredentials.DatabaseName +
"port=" + DatabaseCredentials.Port +
"password=" + AccountCredentials.Password;
_connection = new MySqlConnection(ConnInfo);
try
{
Console.WriteLine("Connecting to " + DatabaseCredentials.DatabaseName + "...");
_connection.Open();
Console.WriteLine("Connection to " + DatabaseCredentials.DatabaseName + " successful.");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
public void Close()
{
_connection.Close();
}
}
</code></pre>
<p>Relevant code:</p>
<pre><code>class AccountLogin
{
public string Username { get; }
public string Password { get; }
public AccountLogin(string _username, string _password)
{
Username = _username;
Password = _password;
}
}
class DatabaseLogin
{
public string DatabaseName { get; }
public string Server { get; }
public string Port { get; }
public DatabaseLogin(string _server, string _DatabaseName, string _port)
{
DatabaseName = _DatabaseName;
Server = _server;
Port = _port;
}
}
static class Validators
{
public static bool NullStringValidator(string[] _inputs)
{
bool _result = false;
for (int i = 0; i < _inputs.Length; i++)
{
if (string.IsNullOrEmpty(_inputs[i]))
{
return _result = true;
}
}
return _result;
}
}
</code></pre>
| [] | [
{
"body": "<p>The conventional naming for arguments in C# is camelCase:</p>\n\n<blockquote>\n <p><code>AccountLogin _AccCred</code></p>\n</blockquote>\n\n<p>looks better as</p>\n\n<pre><code>AccountLogin accountLogin\n</code></pre>\n\n<hr>\n\n<p>I wonder if this: <code>DatabaseCredentials?.DatabaseName</code> ... | {
"AcceptedAnswerId": "202396",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T02:36:32.080",
"Id": "202359",
"Score": "1",
"Tags": [
"c#",
"mysql"
],
"Title": "MySQLConnection Conn.Connect()"
} | 202359 |
<p>I was very bored over one of my breaks this year, so I built a Hardy-Weinberg equilibrium simulator for two unrelated alleles of the same gene. Hardy-Weinberg equilibrium is when there is no evolution, random mating, and a constant population size. The idea behind the simulation is to show the effects of genetic drift over time on small or large populations for a particular gene.</p>
<p>The goal of the project is to teach me how to use C (this is my first non-trivial program) and how to heavily optimize programs. The current best benchmark I have on my computer is 380µs per generation of 65536 ~= 170m matings per second on my 2.5 GHz Intel Core i5. In the core logic of the program, I don't believe there are any memory accesses, so it should be totally CPU bound. The project is built to run on computers with SSE4.2. It will probably run on computers without it, but I imagine it will be much slower. GCC is not required, but heavily recommended as the code becomes ~25% faster with GCC as opposed to clang. The project as a whole is on <a href="https://github.com/williamwisdom/biology/tree/411f1db79335008d8aca6eab968840d23f58e1c1" rel="nofollow noreferrer">Github</a>.</p>
<p>The idea behind my implementation is that for each mating, because there are only three attributes possible, (aa, ab or ba, and bb) we don't have to actually pick out each organism, we can just count how many there are of a certain type. Additionally, there are only two possibilities in a mating: both alleles from one parent or one allele from each parent. The number of times each occur is represented in the <code>both_one_parent</code> variable, which should be approximately normal. The current maximum number of organisms is 65536, so we can used an unsigned short to find one of the organisms and get its' allele. If there's only one parent, then we're done. If there are two parents, then we have to mix their genes, which is in the second for loop.</p>
<p>One of the keys to fast simulation is a fast random function, and the fastest I could find is the <a href="http://www.dimkovic.com/node/22" rel="nofollow noreferrer"><code>FastRand</code> algorithm by Ivan Dimkovic</a>. I benchmarked <code>FastRand</code>, the system <code>random</code> function and Intel's <code>rdrand</code> instruction at respectively 4300 bytes/µs, 790 bytes/µs, and 190 bytes/µs (on generating 1GB. If anyone knows of a better one I would appreciate it. FastRand works in C by initializing a <code>FastRand</code> struct using <code>InitFastRand</code> and then calling <code>FastRand</code> on it, which refills the <code>FastRand.res</code> buffer, which is theoretically an int[4] array but is actually a 128 bit register.</p>
<p>I am fairly new to C and to optimizing programs like this in general. I would appreciate any advice. Below is the core loop of the program logic, which probably consumes >99% of runtime. I slightly changed the <code>FastRand</code> from Ivan Dimkovic and my version is <a href="https://github.com/williamwisdom/biology/blob/e271bb545a6d623b4f0a7b6ca36d8f249fc91119/fast_rand.h" rel="nofollow noreferrer">here</a>.</p>
<pre><code>#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <x86intrin.h>
#include "fast_rand.h"
void progress_generation(int thresh_aa, int thresh_ab, int thresh_bb, int next_members, int* result) {
// 0 | thresh_aa | thresh_ab | end = thresh_bb
int counts[5] = { 0,0,0,0,0 };
if (next_members != 65536) {
double offset = 65536 / next_members;
thresh_aa *= offset;
thresh_ab *= offset;
thresh_bb *= offset;
printf("next_members != 65536");
}
fastrand rand_index = InitFastRand();
fastrand rand_choice = InitFastRand();
/*
* This is a little bit complicated. In the old way, the choice over whether to have both bits
* come from one parent or not was made more or less on the fly, which costs a shr and most
* importantly, an evil evil branch on every iteration. This branch was so awful because if the
* random number generator is good, it is unpredictable, which means you have a branch miss half
* of the time. Instead, we can refactor the decision making so it happens up here. What that means
* is that we decide ahead of time how many have both bits come from one parent and how many
* have one bit from each parent. This means that we don't have a branch in a loop here - there's
* only the loop branch, which should have >99% prediction. This should make the code much faster.
*/
int both_one_parent = 0;
for (int i = 0; i < (next_members >> 7); i += 1) { // FastRand is 128 bits = 2^7 members per fastrand
FastRand(&rand_choice);
both_one_parent += __builtin_popcountll(*(rand_choice.res)) +
__builtin_popcountll(*(rand_choice.res + 2)); // hopefully the compiler gets it
}
unsigned short *short_res = (unsigned short *)rand_index.res;
// normally rand_index.res would be typed as an int *, though really it's a 128 bit register
// location. Unsigned shorts cover the 0-65536 range. I could handle ints also, but it would be
// something like half as fast.
// For ones where both bits come from one parent
for (int i = 0; i < (both_one_parent >> 3); i++) {
FastRand(&rand_index);
for (int k = 0; k < 8; k++) {
unsigned short firstIndex = short_res[k];
counts[(firstIndex < thresh_aa) + (firstIndex < thresh_ab)] += 1;
// 0 = bb, 1 = ab, 2 = aa
}
}
counts[3] = counts[0];
counts[0] = counts[2];
counts[2] = 0;
// Counts output: 0: aa 1: ab 2: ab 3: bb 4: bb , so we have to fiddle around a bit
for (int i = 0; i < ((next_members - both_one_parent) >> 2); i++) {
// >> 2 and not 3 because the cycle only gives 4 results, not 8, because it needs 32 bits
FastRand(&rand_index);
for (int k = 0; k < 8; k++) {
unsigned short firstIndex = short_res[k];
k += 1;
unsigned short secondIndex = short_res[k];
char allele = 0;
// Three tests for first bit: firstIndex > thresh_ab in which case it's 1. firstIndex < thresh_aa in which case it's 1. threst_aa < firstIndex < thresh_ab 50% chance
if (firstIndex > thresh_ab) { // if it's a bb, then both alleles are b so result is b
allele = 1;
}
else if (firstIndex > thresh_aa) {
allele = secondIndex & 1; // subtle small error. change to secondIndex?
}
if (secondIndex > thresh_ab) { // We know second one is BB
counts[allele + 2] += 1;
}
else if (secondIndex > thresh_aa) { // Second one is AB
counts[allele + (firstIndex & 2)] += 1; // This used to be firstIndex. This caused an insidious bug where aa and bb were relatively favored 10:12:10 when they should be 8:16:8
// This used to be allele+secondIndex&2 and the &2 operated after the + so it was always 0 or 2
}
else { // second one is AA
counts[allele] += 1;
}
}
}
// 0: aa 1: ab 2: ab 3: bb 4: bb
result[0] = counts[0]; // aa
result[1] = counts[1] + counts[2]; // ab
result[2] = counts[3] + counts[4]; // bb
}
void initialize_generation(int number, int* gen) { // 14 milliseconds faster on generating 1.6 million organisms lol. 224 organisms / microsecond is good
// AA consistently has ~17.5k while BB consistently has ~15k.
// This is equivalent to a normal distribution. There's probably some normal distribution function I could use that's faster.
int num_aa = 0;
int num_ab = 0;
int num_bb = 0;
for (int i = 0; i < number / 8; i++) { // 8 instead of 16 because the upper bit is always 0.
// It would be more efficient to make this 15 or something but who cares
int n = random();
#pragma clang loop unroll(full)
for (int j = 0; j < 8; j++) { // This needs to be unrolled
char organism = n & 3;
if (organism == 0) {
num_aa += 1;
}
else if (organism == 3) {
num_bb += 1;
}
else {
num_ab += 1;
}
n >>= 2;
}
}
gen[0] = num_aa;
gen[1] = num_ab;
gen[2] = num_bb;
}
int main(int argc, char **argv) {
int num_organisms = 0;
int num_generations = 0;
if (argc < 3) {
num_organisms = 65536;
num_generations = 1000;
}
else {
num_organisms = atoi(argv[1]);
num_generations = atoi(argv[2]);
if (__builtin_popcount(num_organisms) != 1) {
printf("num_organisms must be a multiple of 2");
exit(1);
}
}
printf("Simulating %d organisms for %d generations
",num_organisms,num_generations);
srandomdev(); // Seeds random() using information from /dev/random
int initial_values[3];
initialize_generation(num_organisms, initial_values);
int thresh_aa = initial_values[0];
int thresh_ab = thresh_aa + initial_values[1];
int thresh_bb = thresh_ab + initial_values[2];
int **results = (int **)malloc(num_generations * 3 * sizeof(int));
int result[3] = { 0,0,0 };
int time_takens[20];
int average = 0;
for (int i = 0; i < 20; i++) {
struct timeval start;
struct timeval end;
gettimeofday(&start, NULL);
for (int j = 0; j < 1000; j++) {
progress_generation(thresh_aa, thresh_ab, thresh_bb, num_organisms, result);
thresh_aa = result[0];
thresh_ab = thresh_aa + result[1];
thresh_bb = thresh_ab + result[2];
}
gettimeofday(&end, NULL);
int time_taken = (1000000 * end.tv_sec + end.tv_usec) - (1000000 * start.tv_sec + start.tv_usec);
printf("%d microseconds ", time_taken);
printf("aa: %d ab:%d bb:%d
",result[0],result[1],result[2]);
time_takens[i] = time_taken;
average += time_taken;
initialize_generation(num_organisms, initial_values);
thresh_aa = initial_values[0];
thresh_ab = thresh_aa + initial_values[1];
thresh_bb = thresh_ab + initial_values[2];
}
printf("Took on average %d microseconds per 1000 generationss or %d microseconds per generation
",average/20,average/20000);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T10:43:03.063",
"Id": "389976",
"Score": "0",
"body": "You seem to have lost your `#include` lines and function declaration(s), perhaps while copying from your editor - any chance you could reinstate those, to give us a complete runn... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T04:37:30.457",
"Id": "202364",
"Score": "4",
"Tags": [
"performance",
"algorithm",
"c",
"simulation",
"sse"
],
"Title": "Fast Hardy-Weinberg equilibrium simulation"
} | 202364 |
<p>I have two view controllers which have same tableview. One is for Post and one is for Profile, which also contains a post by a user. I have decided to reuse the code, so I have created the class <code>PostTableView</code>.</p>
<pre><code>class PostTableView: UITableView {
var arrayPosts:[PostTableViewCompitible] = [] {
didSet {
self.reloadData()
}
}
var btnCommentTapped:((ArrayInspireListCell) -> ())?
var heightOfRows = Dictionary<IndexPath, CGFloat>()
var indexOfCellBeforeDragging = 0
override func awakeFromNib() {
super.awakeFromNib()
setupTableView()
}
private func setupTableView() {
self.register(UINib.init(nibName: StoryBoard.Cells.ArrayInspireListCell, bundle: nil), forCellReuseIdentifier: StoryBoard.Cells.ArrayInspireListCell)
self.dataSource = self
self.delegate = self
self.estimatedRowHeight = 470
// self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.rowHeight = UITableViewAutomaticDimension
self.separatorStyle = .none
}
}
</code></pre>
<p>With Delegate / Data source:</p>
<pre><code>extension PostTableView:UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayPosts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = self.arrayPosts[indexPath.row]
let cell = post.cellForTableView(tableview: tableView, atIndexPath: indexPath)
cell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
cell.btnCommentTapped = self.btnCommentTapped
cell.layoutIfNeeded()
return cell
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = self.heightOfRows[indexPath] {
return height
}
return 470
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let height = cell.frame.size.height
self.heightOfRows[indexPath] = height + 30
}
}
</code></pre>
<p>Is it good practice to do so?</p>
| [] | [
{
"body": "<p>Personally I don't like the way <code>UITableView</code>s work with a <code>delegate</code> and <code>dataSource</code> yet there's no real way to say \"Here's the data\". You are kind of forced to either send around copies of your data or put everything into one class. There's tons of mixing of t... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T07:34:01.460",
"Id": "202372",
"Score": "3",
"Tags": [
"swift",
"ios",
"swift3"
],
"Title": "Tableview Subclass implementing delegate datasource"
} | 202372 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.