body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I created this program which runs with no error, but I'd like to have some comments if it is possible to optimize it, since I need to run the program with <code>N = 3200</code>. In this case it takes a lot of time to end. I left it running during the night to get the answer.</p>
<p>The math notation of the program:</p>
<p><span class="math-container">\$
A = (a_{ij}) \space \text{is an} \space N \times N \space \text{matrix} \\
B = \text{max_prod(A)} \space \text{is an} \space N \times N \space \text{matrix where} \\
\space \space \space \space \space b_{ij} = \min\{\max(a_{ik}, b_{kj}); k = 1, \dots,N\}
\$</span></p>
<pre><code>import numpy as np
def min_max(mat1, mat2, i, j):
''' this function takes 2 matrices and 2 indexes
and return the minimum of the element wise maximum
between row i of mat1 and col j of mat2 '''
return min(np.maximum(mat1[i,:], mat2[:,j]))
def max_prod(mat1,mat2):
''' this function takes 2 matrices and return a new matrix
where position (i,j) is min_max(mat1, mat2, i, j) '''
n = len(mat1)
my_prod = np.zeros((n,n), dtype=float)
for i in range(n):
for j in range(i,n):
my_prod[i,j] = min_max(mat1,mat2,i,j)
my_prod[j,i] = min_max(mat2,mat1,j,i)
return my_prod
N = 5
A = np.random.randint(1,20, size=(N,N))
print max_prod(A,A)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T20:30:51.877",
"Id": "206608",
"Score": "2",
"Tags": [
"python",
"python-2.x",
"matrix"
],
"Title": "MinMax product for large matrices"
} | 206608 |
<p><a href="https://projecteuler.net/problem=37" rel="nofollow noreferrer">Project Euler Problem 37</a> asks:</p>
<blockquote>
<p>The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.</p>
<p>Find the sum of the only eleven primes that are both truncatable from left to right and right to left.</p>
<p>NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.</p>
</blockquote>
<p>My approach can generate first 8 numbers "fairly" quickly and it relies on pregenerated list of primes created using sieve of eratosthenes. I've tried with active prime generation but it was slower, any way to optimize this code ?</p>
<pre><code>from algorithms import *
primes = [i for i in gen_primes(10000000)]
def is_truncatable_right(n):
a = True
if n > 10:
for x in range(len(str(n))):
if int(n) not in primes:
a = False
n = str(n)[:-1]
return a
else:
return False
def is_truncatable_left(n):
a = True
if n > 10:
for x in range(len(str(n))):
if int(n) not in primes:
a = False
n = str(n)[1:]
return a
else:
return False
def main():
n = []
a = 11
while len(n) != 11:
if is_truncatable_left(a) and is_truncatable_right(a):
n.append(a)
a += 1
return n, sum(n)
print(main())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T23:56:09.473",
"Id": "398562",
"Score": "4",
"body": "Strictly speaking, you don't need a program to solve the challenge. It is easy to observe that there are 8 truncatable primes below 100, and the challenge itself gives up the oth... | [
{
"body": "<p>One thing you could do to increase the speed of your algorithm would be to use the numbers in <code>primes</code> rather than incrementing <code>a</code> and then checking if <code>a</code> is in <code>primes</code>.</p>\n\n<p>Ex.</p>\n\n<p>Since we know that <code>11</code> is the <code>5th</code... | {
"AcceptedAnswerId": "206636",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T21:23:13.590",
"Id": "206610",
"Score": "2",
"Tags": [
"python",
"performance",
"programming-challenge",
"primes"
],
"Title": "Project Euler Problem 37 in Python"
} | 206610 |
<blockquote>
<p>A beginner level "Student Library Program" in Java, which interacts
the Students and the Books. This Library Program can do following
functions:</p>
<ol>
<li><p>Adding a Book to Library.</p></li>
<li><p>Update Book Quantity.</p></li>
<li><p>Search a Book with its Serial number.</p></li>
<li><p>Search Books With Author Name.</p></li>
<li><p>Show all Books and their related Information.</p></li>
<li><p>Registering a Student.</p></li>
<li><p>Show All Registered Students.</p></li>
<li><p>Student can Check Out Book From Library (if registered).</p>
<ul>
<li><p>Student can not Check Out max than 3 Books</p></li>
<li><p>You can only borrow a Book If it is Available in Library</p></li>
</ul></li>
<li><p>Student can Check In Book to Library.</p></li>
<li><p>You can also see the Books which a Student has Checked Out(only while checking in)</p></li>
</ol>
<p>Note: At the time it can store only 50 books for simplicity in
program.</p>
</blockquote>
<p>I have created this program to the best of my ability. I'm a beginner, so I couldn't do more.</p>
<pre><code>package library;
import java.util.Scanner;
public class book {
public int sNo;
public String bookName;
public String authorName;
public int bookQty;
public int bookQtyCopy;
Scanner input = new Scanner(System.in);
public book(){
System.out.println("Enter Serial No of Book:");
this.sNo = input.nextInt();
input.nextLine();
System.out.println("Enter Book Name:");
this.bookName = input.nextLine();
System.out.println("Enter Author Name:");
this.authorName = input.nextLine();
System.out.println("Enter Quantity of Books:");
this.bookQty = input.nextInt();
bookQtyCopy = this.bookQty;
}
}
</code></pre>
<hr>
<pre><code>package library;
import java.util.Scanner;
public class books {
book theBooks[] = new book[50]; // Array that stores 'book' Objects.
public static int count; // Counter for No of book objects Added in Array.
Scanner input = new Scanner(System.in);
public int compareBookObjects(book b1, book b2){
if (b1.bookName.equalsIgnoreCase(b2.bookName)){
System.out.println("Book of this Name Already Exists.");
return 0;
}
if (b1.sNo==b2.sNo){
System.out.println("Book of this Serial No Already Exists.");
return 0;
}
return 1;
}
public void addBook(book b){
for (int i=0; i<count; i++){
if (this.compareBookObjects(b, this.theBooks[i]) == 0)
return;
}
if (count<50){
theBooks[count] = b;
count++;
}
else{
System.out.println("No Space to Add More Books.");
}
}
public void searchBySno(){
System.out.println("\t\t\t\tSEARCH BY SERIAL NUMBER\n");
int sNo;
System.out.println("Enter Serial No of Book:");
sNo = input.nextInt();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
return;
}
}
if (flag == 0)
System.out.println("No Book for Serial No " + sNo + " Found.");
}
public void searchByAuthorName(){
System.out.println("\t\t\t\tSEARCH BY AUTHOR'S NAME");
input.nextLine();
System.out.println("Enter Author Name:");
String authorName = input.nextLine();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (authorName.equalsIgnoreCase(theBooks[i].authorName)){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
}
}
if (flag == 0)
System.out.println("No Books of " + authorName + " Found.");
}
public void showAllBooks(){
System.out.println("\t\t\t\tSHOWING ALL BOOKS\n");
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
}
}
public void upgradeBookQty(){
System.out.println("\t\t\t\tUPGRADE QUANTITY OF A BOOK\n");
System.out.println("Enter Serial No of Book");
int sNo = input.nextInt();
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println("Enter No of Books to be Added:");
int addingQty = input.nextInt();
theBooks[i].bookQty += addingQty;
theBooks[i].bookQtyCopy += addingQty;
return;
}
}
}
public void dispMenu(){
System.out.println("----------------------------------------------------------------------------------------------------------");
System.out.println("Enter 0 to Exit Application.");
System.out.println("Enter 1 to Add new Book.");
System.out.println("Enter 2 to Upgrade Quantity of a Book.");
System.out.println("Enter 3 to Search a Book.");
System.out.println("Enter 4 to Show All Books.");
System.out.println("Enter 5 to Register Student.");
System.out.println("Enter 6 to Show All Registered Students.");
System.out.println("Enter 7 to Check Out Book. ");
System.out.println("Enter 8 to Check In Book");
System.out.println("-------------------------------------------------------------
---------------------------------------------");
}
public int isAvailable(int sNo){
//returns the index number if available
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
if(theBooks[i].bookQtyCopy > 0){
System.out.println("Book is Available.");
return i;
}
System.out.println("Book is Unavailable");
return -1;
}
}
System.out.println("No Book of Serial Number " + " Available in Library.");
return -1;
}
public book checkOutBook(){
System.out.println("Enter Serial No of Book to be Checked Out.");
int sNo = input.nextInt();
int bookIndex =isAvailable(sNo);
if (bookIndex!=-1){
//int bookIndex = isAvailable(sNo);
theBooks[bookIndex].bookQtyCopy--;
return theBooks[bookIndex];
}
return null;
}
public void checkInBook(book b){
for (int i=0; i<count; i++){
if (b.equals(theBooks[i]) ){
theBooks[i].bookQtyCopy++;
return;
}
}
}
}
</code></pre>
<hr>
<pre><code>package library;
import java.util.Scanner;
public class student {
String studentName;
String regNum;
book borrowedBooks[] = new book[3];
public int booksCount = 0;
Scanner input = new Scanner(System.in);
public student(){
System.out.println("Enter Student Name:");
this.studentName = input.nextLine();
System.out.println("Enter Reg Number:");
this.regNum = input.nextLine();
}
}
</code></pre>
<hr>
<pre><code>package library;
import java.util.Scanner;
public class students {
Scanner input = new Scanner(System.in);
student theStudents[] = new student[50];
//books book;
public static int count = 0;
public void addStudent(student s){
for (int i=0; i<count; i++){
if(s.regNum.equalsIgnoreCase(theStudents[i].regNum)){
System.out.println("Student of Reg Num " + s.regNum + " is Already Registered.");
return;
}
}
if (count<=50){
theStudents[count] = s;
count++;
}
}
public void showAllStudents(){
System.out.println("Student Name\t\tReg Number");
for (int i=0; i<count; i++){
System.out.println(theStudents[i].studentName + "\t\t" + theStudents[i].regNum);
}
}
public int isStudent(){
//return index number of student if available
//System.out.println("Enter Student Name:");
//String studentName = input.nextLine();
System.out.println("Enter Reg Number:");
String regNum = input.nextLine();
for (int i=0; i<count; i++){
if (theStudents[i].regNum.equalsIgnoreCase(regNum)){
return i;
}
}
System.out.println("Student is not Registered.");
System.out.println("Get Registered First.");
return -1;
}
public void checkOutBook(books book){
int studentIndex =this.isStudent();
if (studentIndex!=-1){
System.out.println("checking out");
book.showAllBooks();//jjjjjjjjjjjj
book b = book.checkOutBook();
System.out.println("checking out");
if (b!= null){
if (theStudents[studentIndex].booksCount<=3){
System.out.println("adding book");
theStudents[studentIndex].borrowedBooks[theStudents[studentIndex].booksCount] = b;
theStudents[studentIndex].booksCount++;
return;
}
else {
System.out.println("Student Can not Borrow more than 3 Books.");
return;
}
}
System.out.println("Book is not Available.");
}
}
public void checkInBook(books book){
int studentIndex = this.isStudent();
if (studentIndex != -1){
System.out.println("S.No\t\t\tBook Name\t\t\tAuthor Name");
student s = theStudents[studentIndex];
for (int i=0; i<s.booksCount; i++){
System.out.println(s.borrowedBooks[i].sNo+ "\t\t\t" + s.borrowedBooks[i].bookName + "\t\t\t"+
s.borrowedBooks[i].authorName);
}
System.out.println("Enter Serial Number of Book to be Checked In:");
int sNo = input.nextInt();
for (int i=0; i<s.booksCount; i++){
if (sNo == s.borrowedBooks[i].sNo){
book.checkInBook(s.borrowedBooks[i]);
s.borrowedBooks[i]=null;
return;
}
}
System.out.println("Book of Serial No "+sNo+"not Found");
}
}
}
</code></pre>
<hr>
<pre><code>package library;
import java.util.Scanner;
public class Library {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("********************Welcome to the Student Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
books ob = new books();
students obStudent = new students();
int choice;
int searchChoice;
do{
ob.dispMenu();
choice = input.nextInt();
switch(choice){
case 1:
book b = new book();
ob.addBook(b);
break;
case 2:
ob.upgradeBookQty();
break;
case 3:
System.out.println("Enter 1 to Search with Serial No.");
System.out.println("Enter 2 to Search with Author Name(Full Name).");
searchChoice = input.nextInt();
switch(searchChoice){
case 1:
ob.searchBySno();
break;
case 2:
ob.searchByAuthorName();
}
break;
case 4:
ob.showAllBooks();
break;
case 5:
student s = new student();
obStudent.addStudent(s);
break;
case 6:
obStudent.showAllStudents();
break;
case 7:
obStudent.checkOutBook(ob);
break;
case 8:
obStudent.checkInBook(ob);
break;
default:
System.out.println("CHOICE SHOULD BE BETWEEN 0 TO 8.");
}
}
while (choice!=0);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T21:57:10.720",
"Id": "475487",
"Score": "0",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)"
}
] | [
{
"body": "<p>In Java, class names should begin with a capital letter. So you should have</p>\n\n<pre><code>class Book { ... }\nclass Books { ... }\nclass Student { ... }\nclass Students { ... }\n</code></pre>\n\n<hr>\n\n<p>Each <code>book</code> has its own <code>Scanner</code>, as does <code>books</code>, ev... | {
"AcceptedAnswerId": "206632",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T21:58:19.063",
"Id": "206615",
"Score": "5",
"Tags": [
"java",
"beginner"
],
"Title": "A student library program in Java"
} | 206615 |
<p>I am trying to implement an open source desktop application with python. I want to provide both a gui and an API. I know there is no private methods in python but i am trying to find the most elegant way to keep some methods private. I do not want my users to see all list of methods while using API. After some research, I come up with the implementation below and wondering if there is any problem with my implementation of this concept and if there is any room for improvement. Please provide me a review and do not hesitate to ask any questions you have. Here is my try:</p>
<pre><code>from pprint import pprint
# CamelCase because it "acts" like a class
def CounterController():
class CounterControllerPrivate(object):
def __init__(self):
self.counter = 0
def add_one(self):
self.counter += 1
def reset(self):
self.counter = 0
def get_counter(self):
return self.counter
counter_controller = CounterControllerPrivate()
class CounterControllerPublic(object):
def add_one_endpoint(self):
counter_controller.add_one()
return counter_controller.get_counter()
def reset_endpoint(self):
counter_controller.reset()
return counter_controller.get_counter()
return CounterControllerPublic()
# counter attribute is not accessible from out here
controller = CounterController()
print(controller.add_one_endpoint())
print(controller.add_one_endpoint())
print(controller.reset_endpoint())
pprint(dir(controller))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T22:24:12.860",
"Id": "398549",
"Score": "0",
"body": "When I run your code, I get: `Traceback (most recent call last): File \"cr105997.py\", line 33, in <module>: controller.add_one_endpoint(): TypeError: add_one_endpoint() missing ... | [
{
"body": "<p>The private objects and attributes are easily accessed using <a href=\"https://docs.python.org/3/library/inspect.html#inspect.getclosurevars\" rel=\"noreferrer\"><code>inspect.getclosurevars</code></a>:</p>\n\n<pre><code>>>> c = CounterController()\n>>> import inspect\n>>&g... | {
"AcceptedAnswerId": "206620",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T22:00:39.927",
"Id": "206616",
"Score": "1",
"Tags": [
"python",
"object-oriented"
],
"Title": "Counter object in Python with public and private methods"
} | 206616 |
<p>I wrote a solution to <a href="https://leetcode.com/problems/first-unique-character-in-a-string/" rel="nofollow noreferrer">first-unique-character-in-a-string</a>:</p>
<blockquote>
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p>
</blockquote>
<p>If there is better way for me to build the dictionary <code>seems</code>? and find the first key when <code>value</code> is 1 and <code>index</code> is lowest?</p>
<pre><code>def firstUniqChar(string) -> int:
seems = dict()
index = len(string)
c = ''
for i, char in string:
if char not in seems:
seems.setdefault(char, (i,1))
else:
seems[char] = (seems[char][0], seems[char][1] + 1)
for k, value in seems.items():
if value[1] == 1 and value[0] < index:
index = value[0]
c = k
return index if c else -1
</code></pre>
| [] | [
{
"body": "<p>The code is too convoluted and unreadable for such a simple task</p>\n\n<ul>\n<li><code>seems</code> is a dictionary where the values are (first index, occurrences) pairs. That's an unconventional data structure. You'd be better off with two separate dictionaries.</li>\n<li><code>seems</code> is... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T00:34:14.717",
"Id": "206624",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"strings",
"programming-challenge"
],
"Title": "Find the first non-recurring character in string"
} | 206624 |
<p>First time using React. </p>
<p>Here is a demo: <a href="https://ostralyan.github.io/flood-fill/" rel="nofollow noreferrer">https://ostralyan.github.io/flood-fill/</a></p>
<p><strong>Game Component</strong> </p>
<pre><code>import React from 'react';
import Board from './Board';
import Options from './Options';
export default class Game extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.state.widthOfSquare = 10;
this.state.squaresPerRow = 50;
this.state.numberOfColors = 3;
this.state.includeDiagonals = false;
this.state.colors = this.generateColors(this.state.numberOfColors);
this.state.squares = this.generateSquares(
this.state.colors,
this.state.squaresPerRow,
this.state.numberOfColors
);
this.resetBoard = this.resetBoard.bind(this);
}
resetBoard(widthOfSquare, squaresPerRow, numberOfColors, includeDiagonals) {
const colors = this.generateColors(numberOfColors);
const state = {
widthOfSquare,
squaresPerRow,
numberOfColors,
includeDiagonals,
colors: colors,
squares: this.generateSquares(colors, squaresPerRow, numberOfColors)
}
this.setState(state);
}
generateColors(numberOfColors) {
const colors = [];
for (let i = 0; i < numberOfColors; i++) {
colors[i] = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
return colors;
}
generateSquares(colors, squaresPerRow, numberOfColors) {
const squares = []
for(let i = 0; i < squaresPerRow; i++) {
squares[i] = [];
for(let j = 0; j < squaresPerRow; j++) {
squares[i][j] = {
color: this.getColor(colors, numberOfColors),
visited: false
}
}
}
return squares;
}
getColor(colors, numberOfColors) {
const numberBetweenZeroAndFour = Math.floor((Math.random() * numberOfColors));
return colors[numberBetweenZeroAndFour];
}
render() {
return (
<div className="game">
<div className="game-board">
<Options
onReset={this.resetBoard}
widthOfSquare={this.state.widthOfSquare}
squaresPerRow={this.state.squaresPerRow}
numberOfColors={this.state.numberOfColors}
includeDiagonals={this.state.includeDiagonals}
/>
<Board
widthOfSquare={this.state.widthOfSquare}
squaresPerRow={this.state.squaresPerRow}
numberOfColors={this.state.numberOfColors}
includeDiagonals={this.state.includeDiagonals}
squares={this.state.squares}
colors={this.state.colors}
/>
</div>
</div>
);
}
}
</code></pre>
<p><strong>Board Component</strong></p>
<pre><code>import React from 'react';
import Square from './Square';
export default class Board extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
floodFillRecursive(i, j) {
const oldColor = this.props.squares[i][j].color;
const newColor = this.getUniqueRandomColor(oldColor);
const squares = this.props.squares.slice();
this.floodFillHelper(squares, i, j, oldColor, newColor);
this.clearVisisted(squares);
this.setState({ squares: squares });
}
floodFillRecursiveHelper(squares, i, j, oldColor, newColor) {
// check out of bounds
if (i < 0 || i > this.props.squaresPerRow - 1) return;
if (j < 0 || j > this.props.squaresPerRow - 1) return;
// check if it's visited
if (squares[i][j].visited) return;
// Indicate node has been visited
squares[i][j].visited = true;
// check if it's same color
if (squares[i][j].color !== oldColor) return;
// set the current color to the new color and mark node as visited.
squares[i][j].color = newColor;
// recurse through up, down, left, right boxes.
this.floodFillRecursiveHelper(squares, i + 1, j, oldColor, newColor);
this.floodFillRecursiveHelper(squares, i - 1, j, oldColor, newColor);
this.floodFillRecursiveHelper(squares, i, j + 1, oldColor, newColor);
this.floodFillRecursiveHelper(squares, i, j - 1, oldColor, newColor);
if (this.props.includeDiagonals) {
this.floodFillRecursiveHelper(squares, i + 1, j + 1, oldColor, newColor);
this.floodFillRecursiveHelper(squares, i - 1, j + 1, oldColor, newColor);
this.floodFillRecursiveHelper(squares, i + 1, j + 1, oldColor, newColor);
this.floodFillRecursiveHelper(squares, i - 1, j - 1, oldColor, newColor);
}
}
floodFillIterative(i, j) {
const oldColor = this.props.squares[i][j].color;
const newColor = this.getUniqueRandomColor(oldColor);
const squares = this.props.squares.slice();
const stack = [
[i, j]
];
while (stack.length) {
const squareCoordinates = stack.pop();
let newI = squareCoordinates[0];
let newJ = squareCoordinates[1];
if (newI < 0 || newI >= this.props.squaresPerRow) continue;
if (newJ < 0 || newJ >= this.props.squaresPerRow) continue;
let nextSquare = squares[newI][newJ];
if (nextSquare.color !== oldColor) continue;
if (nextSquare.visited) continue;
Array.prototype.push.apply(stack, [
[newI - 1, newJ],
[newI + 1, newJ],
[newI, newJ - 1],
[newI, newJ + 1],
]);
if (this.props.includeDiagonals) {
Array.prototype.push.apply(stack, [
[newI - 1, newJ - 1],
[newI + 1, newJ - 1],
[newI - 1, newJ + 1],
[newI + 1, newJ + 1],
]);
}
nextSquare.visited = true;
nextSquare.color = newColor;
}
this.setState({ squares });
this.clearVisisted(squares);
}
getUniqueRandomColor(color) {
const numberBetweenZeroAndFour = Math.floor((Math.random() * this.props.numberOfColors));
if (color === this.props.colors[numberBetweenZeroAndFour]) {
return this.getUniqueRandomColor(color);
} else {
return this.props.colors[numberBetweenZeroAndFour];
}
}
clearVisisted(squares) {
for (let i = 0; i < squares.length; i++) {
for (let j = 0; j < squares[i].length; j++) {
squares[i][j].visited = false;
}
}
}
renderSquare(i, j) {
return <Square
color={this.props.squares[i][j].color}
onClick={() => this.floodFillIterative(i, j)}
widthOfSquare={this.props.widthOfSquare}
key={i + "," + j}
/>;
}
createTable() {
let table = []
for (let i = 0; i < this.props.squaresPerRow; i++) {
let children = []
// Inner loop to create children
for (let j = 0; j < this.props.squaresPerRow; j++) {
children.push(this.renderSquare(i, j))
}
// Create the parent and add the children
table.push(<div className="board-row" key={i}>{children}</div>)
}
return table
}
render() {
return (
<div>
{this.createTable()}
</div>
);
}
}
</code></pre>
<p><strong>Options Component</strong></p>
<pre><code>import React from 'react';
export default class Options extends React.Component {
constructor(props) {
super(props)
this.state = {};
this.state.widthOfSquare = this.props.widthOfSquare
this.state.squaresPerRow = this.props.squaresPerRow
this.state.numberOfColors = this.props.numberOfColors
this.state.includeDiagonals = this.props.includeDiagonals
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
this.props.onReset(
this.state.widthOfSquare,
this.state.squaresPerRow,
this.state.numberOfColors,
this.state.includeDiagonals,
);
event.preventDefault();
}
render() {
return (
<div>
<p>
Instructions: Click on any square.<br></br>
<a href="https://github.com/ostralyan/flood-fill" target="_blank" rel="noopener noreferrer">Written by Luke Xu.</a>
</p>
<form onSubmit={this.handleSubmit}>
<label>
Width of square:
<input type="number" name="widthOfSquare" value={this.state.widthOfSquare} onChange={this.handleChange} />
</label>
<br></br>
<label>
Squares per row:
<input type="number" name="squaresPerRow" value={this.state.squaresPerRow} onChange={this.handleChange} />
</label>
<br></br>
<label>
Number of colors:
<input type="number" name="numberOfColors" value={this.state.numberOfColors} onChange={this.handleChange} />
</label>
<br></br>
<label>
Include diagonals:
<input
name="includeDiagonals"
type="checkbox"
checked={this.state.includeDiagonals}
onChange={this.handleChange} />
</label>
<br></br>
<input type="submit" value="Reset" />
</form>
<br></br>
</div>
);
}
}
</code></pre>
<p><strong>Square Component</strong> </p>
<pre><code>import React from 'react';
export default class Square extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
shouldComponentUpdate(nextProps) {
if (nextProps.color !== this.props.color) {
return true;
}
return false;
}
render() {
const divStyle = {
backgroundColor: this.props.color,
height: this.props.widthOfSquare + "px",
width: this.props.widthOfSquare + "px",
lineHeight: this.props.widthOfSquare + "px",
}
return (
<button
className="square"
style={divStyle}
onClick={() => this.props.onClick()}>
</button>
);
}
}
</code></pre>
<p>Would love to hear any feedback. Things I'm not sure about. How far up should I lift the state? Pretty much all my state lives at the highest component which kind of doesn't make sense to me. Imagine if this was a super large app then literally all my state would just sit in the Game Component. I guess that might be where redux comes in?</p>
| [] | [
{
"body": "<h1>FloodFill memory hog</h1>\n<p>Using a library should reduce your source code size and create a higher performance app. If this is not the case then you should not be using the library.</p>\n<p>Using react to hold the pixel state is beyond ludicrous. Just for a 50 by 50 square you create 2500 elem... | {
"AcceptedAnswerId": "206634",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T02:54:29.910",
"Id": "206629",
"Score": "2",
"Tags": [
"react.js",
"jsx"
],
"Title": "Wrote a floodfill visualizer in React"
} | 206629 |
<p>I have a function that simply counts the number of files in a directory. To test this function I am using temporary files which are great in the respect that they are deleted upon creating. However, when I want to test my function to count multiple file it can become quite tedious. The below code works but you can probably guess there will be many lines in my test case if i wanted to count say 100 files. </p>
<pre><code>#myfunction
class FileHandler:
def count_files(output_file_dir):
return len([f for f in listdir(output_file_dir) if isfile(join(output_file_dir, f))])
#test_myfunction
class FileHandlerTests(unittest.TestCase):
def test_if_files_exist_return_count_of_those_files(self):
f= FileHandler
#test with 1 file
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory\n', tmpdirname)
with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file:
print('created temporary file\n', test_file.name)
self.assertEqual(1,f.count_files(tmpdirname))
#test with 2 file
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory\n', tmpdirname)
with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file1:
print('created temporary file\n', test_file1.name)
with tempfile.NamedTemporaryFile(dir=tmpdirname) as test_file2:
print('created temporary file\n', test_file2.name)
self.assertEqual(2,f.count_files(tmpdirname))
#test with 34 file
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory\n', tmpdirname)
#loop to create 34 temp files?
</code></pre>
| [] | [
{
"body": "<p>Why do you create named temporary files within your named temporary directory? The whole directory (<a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory\" rel=\"nofollow noreferrer\">including its contents</a>) will be deleted as soon as the context ends.</p>\n\n<p... | {
"AcceptedAnswerId": "206654",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T08:53:47.887",
"Id": "206639",
"Score": "2",
"Tags": [
"python",
"unit-testing",
"file",
"file-system"
],
"Title": "Unit tests for directory-entry counter"
} | 206639 |
<p>I'm a newbie getting into web scrapers. I've made something that works, but it takes hours and hours to get everything I need. I read something about using parallel processes to process the URLs but I have no clue how to go about it and incorporate it in what I already have. Help is much appreciated! </p>
<p>Here is my, still extremely messy, code. I'm still learning :) </p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
from selenium.common.exceptions import NoSuchElementException
import time
import random
import pprint
import itertools
import csv
import pandas as pd
start_url = "https://www.nationalevacaturebank.nl/vacature/zoeken?query=&location=&distance=city&limit=100&sort=relevance&filters%5BcareerLevel%5D%5B%5D=Starter&filters%5BeducationLevel%5D%5B%5D=MBO"
driver = webdriver.Firefox()
driver.set_page_load_timeout(20)
driver.get(start_url)
driver.find_element_by_xpath('//*[@id="form_save"]').click() #accepts cookies
wait = WebDriverWait(driver, random.randint(1500,3200)/1000.0)
j = random.randint(1500,3200)/1000.0
time.sleep(j)
num_jobs = int(driver.find_element_by_xpath('/html/body/div[3]/div/main/div[2]/div[3]/div/header/h2/span').text)
num_pages = int(num_jobs/102)
urls = []
list_of_links = []
for i in range(num_pages+1):
try:
elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="search-results-container"]//article/job/a')))
for i in elements:
list_of_links.append(i.get_attribute('href'))
j = random.randint(1500,3200)/1000.0
time.sleep(j)
if 'page=3' not in driver.current_url:
driver.find_element_by_xpath('//html/body/div[3]/div/main/div[2]/div[3]/div/paginator/div/nav[1]/ul/li[6]/a').click()
else:
driver.find_element_by_xpath('//html/body/div[3]/div/main/div[2]/div[3]/div/paginator/div/nav[1]/ul/li[5]/a').click()
url = driver.current_url
if url not in urls:
print(url)
urls.append(url)
else:
break
except:
continue
set_list_of_links = list(set(list_of_links))
print(len(set_list_of_links), "results")
driver.close()
def grouper(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
def remove_empty_lists(l):
keep_going = True
prev_l = l
while keep_going:
new_l = remover(prev_l)
#are they identical objects?
if new_l == prev_l:
keep_going = False
#set prev to new
prev_l = new_l
#return the result
return new_l
def remover(l):
newlist = []
for i in l:
if isinstance(i, list) and len(i) != 0:
newlist.append(remover(i))
if not isinstance(i, list):
newlist.append(i)
return newlist
vacatures = []
chunks = grouper(100, set_list_of_links)
chunk_count = 0
for chunk in chunks:
chunk_count +=1
print(chunk_count)
j = random.randint(1500,3200)/1000.0
time.sleep(j)
for url in chunk:
driver = webdriver.Firefox()
driver.set_page_load_timeout(20)
try:
driver.get(url)
driver.find_element_by_xpath('//*[@id="form_save"]').click() #accepts cookies
vacature = []
vacature.append(url)
j = random.randint(1500,3200)/1000.0
time.sleep(j)
elements = driver.find_elements_by_tag_name('dl')
p_elements = driver.find_elements_by_tag_name('p')
li_elements = driver.find_elements_by_tag_name('li')
for i in elements:
if "Salaris:" not in i.text:
vacature.append(i.text)
running_text = list()
for p in p_elements:
running_text.append(p.text)
text= [''.join(running_text)]
remove_ls = ['vacatures', 'carrièretips', 'help', 'inloggen', 'inschrijven', 'Bezoek website', 'YouTube',
'Over Nationale Vacaturebank', 'Werken bij de Persgroep', 'Persberichten', 'Autotrack', 'Tweakers',
'Tweakers Elect', 'ITBanen', 'Contact', 'Carrière Mentors', 'Veelgestelde vragen',
'Vacatures, stages en bijbanen', 'Bruto Netto Calculator', 'Salariswijzer', 'Direct vacature plaatsen',
'Kandidaten zoeken', 'Bekijk de webshop', 'Intermediair', 'Volg ons op Facebook']
for li in li_elements:
if li.text not in remove_ls:
text.append(li.text)
text = ''. join(text)
vacature.append(text)
vacatures.append(vacature)
driver.close()
except TimeoutException as ex:
isrunning = 0
print("Exception has been thrown. " + str(ex))
driver.close()
except NoSuchElementException:
continue
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T11:09:01.530",
"Id": "398612",
"Score": "1",
"body": "Please note reviewers will not comment about code not yet written (How to parallel process), but the rest of the question seems fine. Welcome to Code Review"
},
{
"Conten... | [
{
"body": "<p>Bearing in mind that this is a small point and won't likely lead to much of a performance gain, it may simplify the complexity of finding elements.</p>\n\n<p>Instead of finding elements by <em>id</em> attribute using xpath, the function <a href=\"https://selenium-python.readthedocs.io/api.html#sel... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T09:58:24.693",
"Id": "206644",
"Score": "4",
"Tags": [
"python",
"performance",
"web-scraping",
"selenium"
],
"Title": "Python Selenium webscraper for job listing website"
} | 206644 |
<p>I created the below comparer to allow me to use a generic dictionary as a key to another generic dictionary.</p>
<p>My <code>GetHashCode</code> implementation creates a hash based on all keys and their values; but I suspect its distribution could be improved?</p>
<p>Also my <code>Equals</code> method returns true only if the two arguments have exactly the same keys, with each key having exactly the same values. However, potentially there's a more efficient approach to this comparison which I've neglected?</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
namespace MyCompany.Collections.Generic
{
public class DictionaryEqualityComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>
{
readonly IEqualityComparer<TKey> keyComparer;
readonly IEqualityComparer<TValue> valueComparer;
public DictionaryEqualityComparer(): this(null, null){}
public DictionaryEqualityComparer(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
this.keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;
this.valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
}
public bool Equals(IDictionary<TKey, TValue> a, IDictionary<TKey, TValue> b)
{
if (a == null || b == null) return (a == null && b == null); //if either value is null return false, or true if both are null
return a.Count == b.Count //unless they have the same number of items, the dictionaries do not match
&& a.Keys.Intersect(b.Keys, keyComparer).Count() == a.Count //unless they have the same keys, the dictionaries do not match
&& a.Keys.Where(key => ValueEquals(a[key], b[key])).Count() == a.Count; //unless each keys' value is the same in both, the dictionaries do not match
}
public int GetHashCode(IDictionary<TKey, TValue> obj)
{
//I suspect there's a more efficient formula for even distribution, but this does the job for now
long hashCode = obj.Count;
foreach (var key in obj.Keys)
{
hashCode += (key?.GetHashCode() ?? 1000) + (obj[key]?.GetHashCode() ?? 0);
hashCode %= int.MaxValue; //ensure we don't go outside the bounds of MinValue-MaxValue
}
return (int)hashCode; //safe conversion thanks to the above %
}
private bool ValueEquals(TValue x, TValue y)
{
return valueComparer.Equals(x, y);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T10:52:34.420",
"Id": "398606",
"Score": "0",
"body": "NB: After posting realised that my `GetHashCode` method doesn't handle nulls; so have since amended the first line to `if (obj == null) return 0; long hashCode = obj.Count + 1;`;... | [
{
"body": "<p>You said you built this specifically so you can use dictionaries as keys in other dictionaries?</p>\n\n<p>In that case, you've got a problem. Consider the following demonstration:</p>\n\n<pre><code>var keyA = new Dictionary<string, int> { [\"a\"] = 4 };\nvar keyB = new Dictionary<string, ... | {
"AcceptedAnswerId": "206660",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T10:03:14.763",
"Id": "206645",
"Score": "7",
"Tags": [
"c#",
".net",
"generics",
"hash-map"
],
"Title": "Generic Dictionary Equality Comparer"
} | 206645 |
<h1>Intro</h1>
<p>I am building a rogue like RPG, currently it is still a work in progress, but I would like to get an intermediate review of my Procedural map generation code.</p>
<p>I've chosen to use the Binary Space Partitioning algo, because it would make my life easier in the future when I will add corridors to the rooms.</p>
<p>There are some TODO's left, </p>
<ul>
<li>Creating random rooms within the leaves</li>
<li>Adding corridors to connect the (random-sized) rooms</li>
</ul>
<p>but they are not up for review.</p>
<h1>Code</h1>
<pre><code>from queue import Queue
from random import choice, randint
from collections import namedtuple
from enum import Enum
Position = namedtuple("Position", ["y", "x"])
class Tile(Enum):
WALL = '#'
EMPTY = ' '
ROCK = '.'
class Split(Enum):
HORIZONTAL = 0
VERTICAL = 1
class Room():
def __init__(self, lu, rd):
self.lu = lu
self.rd = rd
@property
def position_map(self):
return self._get_positions()
@property
def border_map(self):
return self._get_border()
@property
def width(self):
return self.rd.x - self.lu.x
@property
def height(self):
return self.rd.y - self.lu.y
def _get_positions(self):
return [
Position(row, col)
for col in range(self.lu.x + 1, self.rd.x)
for row in range(self.lu.y + 1, self.rd.y)
]
def _get_border(self):
return [Position(y, self.lu.x) for y in range(self.lu.y, self.rd.y)] + \
[Position(y, self.rd.x) for y in range(self.lu.y, self.rd.y)] + \
[Position(self.lu.y, x) for x in range(self.lu.x, self.rd.x)] + \
[Position(self.rd.y, x) for x in range(self.lu.x, self.rd.x + 1)]
class Leaf():
def __init__(self, lu, rd, parent, min_room_space):
self.lu = lu
self.rd = rd
self.parent = parent
self.min_room_space = min_room_space
self._children = None
self._sibling = None
self._room = None
@property
def children(self):
return self._children
@children.setter
def children(self, value):
self._children = value
@property
def sibling(self):
return self._sibling
@sibling.setter
def sibling(self, value):
self._sibling = value
@property
def room(self):
return self._room or self._generate_room()
@property
def width(self):
return self.rd.x - self.lu.x
@property
def height(self):
return self.rd.y - self.lu.y
def _generate_room(self):
#TODO create random sized room in the leaf
room = Room(self.lu, self.rd)
self._room = room
return room
class Map():
def __init__(self, width, height, min_room_space=10, split_threshold=1.25):
self.width = width
self.height = height
self.lu = Position(0, 0)
self.rd = Position(height-1, width-1)
self.min_room_space = min_room_space
self.split_threshold = split_threshold
self._leaves = None
self.board = [[Tile.ROCK.value] * (self.width) for _ in range(self.height)]
@property
def leaves(self):
return self._leaves
def generate(self):
# Reset the board
self.board = [[Tile.ROCK.value] * (self.width) for _ in range(self.height)]
self._generate_leaves()
for leaf in self.leaves:
for pos in leaf.room.position_map:
self.board[pos.y][pos.x] = Tile.EMPTY.value
for pos in leaf.room.border_map:
self.board[pos.y][pos.x] = Tile.WALL.value
#TODO Create corridors by adding corridors from the children up to the highest in the tree
def _generate_leaves(self):
splitable = Queue()
splitable.put(Leaf(self.lu, self.rd, None, self.min_room_space))
leaves = Queue()
while splitable.qsize() > 0:
leaf = splitable.get()
leaf_a, leaf_b = self._split(leaf)
if leaf_a is None and leaf_b is None:
leaves.put(leaf)
else:
leaf.children = (leaf_a, leaf_b)
leaf_a.sibling = leaf_b
leaf_b.sibling = leaf_a
splitable.put(leaf_a)
splitable.put(leaf_b)
self._leaves = list(leaves.queue)
def _split(self, leaf):
if leaf.width / leaf.height >= self.split_threshold:
return self._split_room(leaf, Split.HORIZONTAL)
elif leaf.height / leaf.width >= self.split_threshold:
return self._split_room(leaf, Split.VERTICAL)
else:
return self._split_room(leaf, choice([Split.VERTICAL, Split.HORIZONTAL]))
def _split_room(self, leaf, direction):
leaf_a = leaf_b = None
if direction == Split.VERTICAL:
if not leaf.height < self.min_room_space * 2:
random_split = randint(leaf.lu.y + self.min_room_space, leaf.rd.y - self.min_room_space)
leaf_a = Leaf(leaf.lu,
Position(random_split, leaf.rd.x),
leaf,
self.min_room_space)
leaf_b = Leaf(Position(random_split + 1, leaf.lu.x),
leaf.rd,
leaf,
self.min_room_space)
elif direction == Split.HORIZONTAL:
if not leaf.width < self.min_room_space * 2:
random_split = randint(leaf.lu.x + self.min_room_space, leaf.rd.x - self.min_room_space)
leaf_a = Leaf(leaf.lu,
Position(leaf.rd.y, random_split),
leaf,
self.min_room_space)
leaf_b = Leaf(Position(leaf.lu.y, random_split + 1),
leaf.rd,
leaf,
self.min_room_space)
return leaf_a, leaf_b
def __str__(self):
return "\n".join("".join(b) for b in self.board)
if __name__ == "__main__":
m = Map(50, 50, 10)
m.generate()
print(m)
</code></pre>
<h1>Example Output</h1>
<pre><code>##################################################
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ############
# ## ## ############
# ## ## ## #
# ## ## ## #
######################################## #
######################################## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ############
# ## ## ############
# ## ## ## #
# ## ## ## #
######################################## #
######################################## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
##################################################
</code></pre>
<p>Please critique <em>any and all</em> </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T10:57:44.630",
"Id": "398608",
"Score": "0",
"body": "Would it be desirable to have rooms of different width within the same \"column\"? It looks a bit computer-generated with the equal width columns going down."
},
{
"Conte... | [
{
"body": "<p>This is already nice-looking code. Some minor remarks</p>\n\n<h1>upper and lower</h1>\n\n<p>on both <code>Leaf</code> and <code>Room</code>, things would become more clear if you defined a <code>left</code>, <code>right</code>, <code>up</code> and <code>down</code></p>\n\n<pre><code>@property\ndef... | {
"AcceptedAnswerId": "207319",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T10:44:01.790",
"Id": "206646",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"game",
"role-playing-game"
],
"Title": "creating procedural generated RPG Dungeon maps"
} | 206646 |
<p>i am pretty new to powershell and im not great at coding, but i have managed to cobble together code from around the net to help save time when removing old students accounts in AD.</p>
<p>Code currently does the following;</p>
<ul>
<li>Takes leavers from .csv file moves the leavers to leavers OU,</li>
<li>Disables Account, and removes from all groups Moves their home folder
to the Leavers Archive share</li>
<li>Deletes their profiles .v5 and .v6 folders </li>
</ul>
<p>What I'm hoping is that someone more experienced can take a look at the code
and possibly explain how it could be tidied and cleaned up and condensed if possible, We have 4 different shares split A-D,E-J,K-R,S-Z</p>
<p>In order to do what i needed for each share i just duplicated the code for each share. I am sure that this could be better formatted with while loops, and IF statements but i don't fully understand how they work to be honest.</p>
<p>Here's the code.</p>
<pre><code> #################################################################################
#Disables Student accounts for leavers and moves them to the leavers OU
#Disables Parent Accounts, Strips groups, Moves to Parent Leavers OU
#################################################################################
#Import users to be disabled
##############################################################################################################################################################################################
Import-Module ActiveDirectory
#Create working directory
#New-Item -ItemType directory "C:\LeaversExports"
Import-Csv "C:\Leavers.csv" | ForEach-Object {
$samAccountName = $_."samAccountName"
Get-ADUser -Identity $samAccountName | Disable-ADAccount
Write-host -ForegroundColor Green "$samAccountName Disabled"
}
##############################################################################################################################################################################################
#Move users from SD1 to Leavers SD1
$SD1 = "OU=SD1,OU=Students,DC=Contoso,DC=ac,DC=uk"
$SD1Leavers = "OU=Leavers SD1,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk"
Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD1 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD1_Leavers.csv -nti
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD1 | Move-ADObject –TargetPath $SD1Leavers
Write-Host -ForegroundColor Green "SD1 - Disabled users Moved"
# Remove User from All Group Memberships
$Users = Get-ADUser -SearchBase $SD1Leavers -Filter *
Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False
$users = Get-ADUser -SearchBase $SD1Leavers -Filter *
foreach($user in $users){
$groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'}
foreach($group in $groups){
Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue
}
}
Write-Host -ForegroundColor Green "SD1 Leavers removed from all Groups"
#Move SD1 Leavers Home Area to Archive
$CSVPath = 'C:\LeaversExports\SD1_Leavers.csv'
$NewHomeRoot = '\\FS1\A-D Leavers$\Leavers 18-19$'
#$NewHomeLocal = 'D:\Data\Users'
$Users = Import-Csv $CSVPath
foreach( $User in $Users ){
$NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName
Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE
}
Write-Host -ForegroundColor Green "All SD1 Leavers Home Folders Moved to Archive"
#Delete Profile Folders
$CSVPath = 'C:\LeaversExports\SD1_Leavers.csv'
$Users = Import-Csv $CSVPath
$samAccountName = $Users.SamAccountName
$profilepathv6 = $Users.ProfilePath + ".V6"
$profilepathv5 = $Users.ProfilePath + ".V5"
foreach( $User in $Users ){
if (Test-Path $profilepathv6){
Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found"
Remove-Item ($profilepathv6)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped"
}
if (Test-Path $profilepathv5){
Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found"
Remove-Item ($profilepathv5)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped"
}
}
Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted"
#Clean up working files
#Remove-Item "C:\LeaversExports" -Force -recurse
##############################################################################################################################################################################################
##############################################################################################################################################################################################
#Move users from SD2 to Leavers SD2
$SD2 = "OU=SD2,OU=Students,DC=Contoso,DC=ac,DC=uk"
$SD2Leavers = "OU=Leavers SD2,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk"
Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD2 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD2_Leavers.csv -nti
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD2 | Move-ADObject –TargetPath $SD2Leavers
Write-Host -ForegroundColor Green "SD2 - Disabled users Moved"
# Remove User from All Group Memberships
$Users = Get-ADUser -SearchBase $SD2Leavers -Filter *
Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False
$users = Get-ADUser -SearchBase $SD2Leavers -Filter *
foreach($user in $users){
$groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'}
foreach($group in $groups){
Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue
}
}
Write-Host -ForegroundColor Green "SD2 Leavers removed from all Groups"
#Move SD2 Leavers Home Area to Archive
$CSVPath = 'C:\LeaversExports\SD2_Leavers.csv'
$NewHomeRoot = '\\FS1\E-J Leavers$\Leavers 18-19'
#$NewHomeLocal = 'D:\Data\Users'
$Users = Import-Csv $CSVPath
foreach( $User in $Users ){
$NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName
Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE
}
Write-Host -ForegroundColor Green "All SD2 Leavers Home Folders Moved to Archive"
#Delete Profile Folders
$CSVPath = 'C:\LeaversExports\SD2_Leavers.csv'
$Users = Import-Csv $CSVPath
$samAccountName = $Users.SamAccountName
$profilepathv6 = $Users.ProfilePath + ".V6"
$profilepathv5 = $Users.ProfilePath + ".V5"
foreach( $User in $Users ){
if (Test-Path $profilepathv6){
Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found"
Remove-Item ($profilepathv6)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped"
}
if (Test-Path $profilepathv5){
Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found"
Remove-Item ($profilepathv5)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped"
}
}
Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted"
#Clean up working files
#Remove-Item "C:\LeaversExports" -Force -recurse
##############################################################################################################################################################################################
##############################################################################################################################################################################################
#Move users from SD3 to Leavers SD3
$SD3 = "OU=SD3,OU=Students,DC=Contoso,DC=ac,DC=uk"
$SD3Leavers = "OU=Leavers SD3,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk"
Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD3 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD3_Leavers.csv -nti
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD3 | Move-ADObject –TargetPath $SD3Leavers
Write-Host -ForegroundColor Green "SD3 - Disabled users Moved"
# Remove User from All Group Memberships
$Users = Get-ADUser -SearchBase $SD3Leavers -Filter *
Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False
$users = Get-ADUser -SearchBase $SD3Leavers -Filter *
foreach($user in $users){
$groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'}
foreach($group in $groups){
Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue
}
}
Write-Host -ForegroundColor Green "SD3 Leavers removed from all Groups"
#Move SD3 Leavers Home Area to Archive
$CSVPath = 'C:\LeaversExports\SD3_Leavers.csv'
$NewHomeRoot = '\\FS2\K-R Leavers$\Leavers 18-19'
#$NewHomeLocal = 'D:\Data\Users'
$Users = Import-Csv $CSVPath
foreach( $User in $Users ){
$NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName
Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE
}
Write-Host -ForegroundColor Green "All SD3 Leavers Home Folders Moved to Archive"
#Delete Profile Folders
$CSVPath = 'C:\LeaversExports\SD3_Leavers.csv'
$Users = Import-Csv $CSVPath
$samAccountName = $Users.SamAccountName
$profilepathv6 = $Users.ProfilePath + ".V6"
$profilepathv5 = $Users.ProfilePath + ".V5"
foreach( $User in $Users ){
if (Test-Path $profilepathv6){
Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found"
Remove-Item ($profilepathv6)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped"
}
if (Test-Path $profilepathv5){
Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found"
Remove-Item ($profilepathv5)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped"
}
}
Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted"
#Clean up working files
#Remove-Item "C:\LeaversExports" -Force -recurse
##############################################################################################################################################################################################
##############################################################################################################################################################################################
#Move users from SD4 to Leavers SD4
$SD4 = "OU=SD4,OU=Students,DC=Contoso,DC=ac,DC=uk"
$SD4Leavers = "OU=Leavers SD4,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk"
Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD4 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD4_Leavers.csv -nti
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD4 | Move-ADObject –TargetPath $SD4Leavers
Write-Host -ForegroundColor Green "SD4 - Disabled users Moved"
# Remove User from All Group Memberships
$Users = Get-ADUser -SearchBase $SD4Leavers -Filter *
Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False
$users = Get-ADUser -SearchBase $SD4Leavers -Filter *
foreach($user in $users){
$groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'}
foreach($group in $groups){
Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue
}
}
Write-Host -ForegroundColor Green "SD4 Leavers removed from all Groups"
#Move SD4 Leavers Home Area to Archive
$CSVPath = 'C:\LeaversExports\SD4_Leavers.csv'
$NewHomeRoot = '\\FS2\S-Z Leavers$\Leavers 18-19'
#$NewHomeLocal = 'D:\Data\Users'
$Users = Import-Csv $CSVPath
foreach( $User in $Users ){
$NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName
Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE
}
Write-Host -ForegroundColor Green "All SD4 Leavers Home Folders Moved to Archive"
#Delete Profile Folders
$CSVPath = 'C:\LeaversExports\SD4_Leavers.csv'
$Users = Import-Csv $CSVPath
$samAccountName = $Users.SamAccountName
$profilepathv6 = $Users.ProfilePath + ".V6"
$profilepathv5 = $Users.ProfilePath + ".V5"
foreach( $User in $Users ){
if (Test-Path $profilepathv6){
Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found"
Remove-Item ($profilepathv6)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped"
}
if (Test-Path $profilepathv5){
Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found"
Remove-Item ($profilepathv5)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped"
}
}
Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted"
#Clean up working files
#Remove-Item "C:\LeaversExports" -Force -recurse
#################################################################################
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T14:24:03.983",
"Id": "398649",
"Score": "0",
"body": "hopefully the name change to the title is better now, sorry was recommended to post here from stackoverflow. Wasn't sure of the best way to post."
},
{
"ContentLicense": ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T12:51:07.853",
"Id": "206658",
"Score": "1",
"Tags": [
"csv",
"powershell",
"active-directory"
],
"Title": "Leavers Script to disable users in AD, Remove Groups, delete profile and move home folders"
} | 206658 |
<p>I wrote an implementation of quicksort that I think is pythonic. I based it off of <a href="http://learnyouahaskell.com/recursion#quick-sort" rel="nofollow noreferrer">this common Haskell implementation</a>:</p>
<blockquote>
<pre class="lang-haskell prettyprint-override"><code>quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted
</code></pre>
</blockquote>
<p>I understand this is not an in-place sort. I also understand that it is optimized for Haskell, which handles recursion very well.</p>
<p>Here's my Python adaptation:</p>
<pre><code>def quicksort(li):
if li == []:
return li
p = li[0]
lo = [ i for i in li[1:] if i <= p ]
hi = [ i for i in li[1:] if i > p ]
return quicksort(lo) + [p] + quicksort(hi)
</code></pre>
<p>I think it has the following upsides:</p>
<ul>
<li>clean looking, pythonic </li>
<li>fast C implementation of linear partitioning</li>
</ul>
<p>and the following downsides:</p>
<ul>
<li>does not sort in place</li>
<li>possibly memory inefficient</li>
</ul>
<p>What are some issues I should be aware of besides the above? Can the algorithm be improved in terms of memory complexity without sacrificing the simplicity and pythonic structure? Should I avoid recursion altogether? Does anyone see bugs or have proposed changes?</p>
| [] | [
{
"body": "<p>IMHO you can't really compare in-place quicksort to not-in-place quicksort. While the basic algorithm is the same, the implementation is vastly different, one being in-place (d'uh) and the other being much, much simpler.</p>\n\n<p>Having said that, you could make your code a bit faster and (IMHO) ... | {
"AcceptedAnswerId": "206671",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T14:01:36.970",
"Id": "206663",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"functional-programming",
"quick-sort"
],
"Title": "Python implementation of Quicksort using list comprehensions"
} | 206663 |
<p>I was curious about image manipulation and I was wondering how it was working, so I made some little functions wich are modifying the pictures passed in parameter.<br>
The graphics results are not too bad, and the execution time is quite correct (even if I think it can clearly be improved).<br>
So (because I'm not an expert) I was wondering if I did terrible things that should be avoided, is there enough/too much comment, are my comments understandable ...<br>
I have also made some unit tests, but the post is quite long so I didn't post them.</p>
<hr>
<p>Note :
each file begins with (I don't put it each time to save space)</p>
<pre><code>#! /usr/bin/env python3
#-*- conding utf-8 -*-
from PIL import Image
import os
</code></pre>
<h2>Black and white / greyscale :</h2>
<p>At the begining I was using the mean function from the module statistics to get the average but was very slow (around 5s more than now). Also I don't get the exact same result for the 2 functions but it's not visible to the human eye, any idea why ?</p>
<pre><code>"""
This module contain the function:
-black_and_white :
Transform the image passed as parameter in a black and white Image,
also called greyscale
"""
def black_and_white(img):
"""
for each pixel of the img the average of it's RGB component is applied to
each RGB component wich result in a darker or brighter grey
"""
px = img.load()
size_x, size_y = img.size
for y in range (size_y):
for x in range (size_x):
ppx = px[x,y]
average = int((ppx[0] + ppx[1] + ppx[2]) / 3)
px[x,y] = (average, average, average)
def GreyScale(img):
""" Same result but faster and not mine :/ """
img.paste(img.convert("L"))
if __name__ == "__main__":
img = Image.open("../image/spidey.jpg")
print ("Black and White : \n")
black_and_white(img)
img.show()
os.system("pause")
</code></pre>
<h2>Luminosity modification:</h2>
<p>Just a question about why Python does:</p>
<pre><code>>>>50 * 5.1
254.99999999999997
</code></pre>
<p>Well... I didn't know that.</p>
<pre><code>"""
This module contain the functions:
luminosity_variation:
Change the luminosity of the image by the variation specified,
the value stick between -255 and 255, or if percentage is true, between
-100% and 100%
luminosity_percentage:
Change the percentage luminosity of luminosity of the image :
50 % = no change
100 % = 100% luminosity
0 % = 0% luminosity
Note: the variation are rights would be better if were curves
"""
def luminosity_variation(img, value, percentage=False):
"""
The function for each pixel attribute the correct luminosity_variation.
"""
if not percentage:
mask = img.point(lambda i : i + value)
img.paste(mask)
else:
mask = img.point(lambda i : i + round(value * 2.55))
img.paste(mask)
def luminosity_percentage(img, percentage):
"""
The function for each pixel attribute the correct luminosity_variation
in percent.
"""
if percentage < 0:
percentage = 0
if percentage > 100:
percentage = 100
mask = img.point(lambda i : i + round((percentage - 50) * 5.1))
img.paste(mask)
if __name__ == "__main__":
img = Image.open("../image/spidey.jpg")
i = int(input("luminosity variation :"))
luminosity_variation(img, i, 1)
img.show()
img = Image.open("../image/spidey.jpg")
i = int(input("luminosity percentage :"))
luminosity_percentage(img, i)
img.show()
os.system("pause")
</code></pre>
<h2>Thresholding</h2>
<p>My question here, because I'm using <code>threshold</code> function only inside <code>thresholding</code> function is it better to define <code>threshold</code> inside the <code>thresholding</code> function?</p>
<pre><code>"""
This module contain the function:
-threshold : used to attribute 0 or 255
-thresholding : used to affect a threshold effect
"""
def threshold(value, i):
"""
dependig to the value of i and value assigne or 0 or 255 can take a single
value or a tuple of two element
"""
if (isinstance(value, tuple)):
if i > value[0] and i <= value [1]:
return 255
else:
return 0
if value < i:
return 255
else:
return 0
def thresholding(img, value, choosed=""):
"""
A function that affect a threshold effect on the image, can do it
on the rgb componant individualy or on all of them is same time
"""
if choosed: choosed = choosed.capitalize()
try:
if choosed in ("R", "G", "B"): R,G,B = img.split()
except ValueError:
R,G,B,A = img.split()
if choosed == "R":
R = R.point(lambda i : threshold(value, i))
img.paste(R)
elif choosed == "G":
G = G.point(lambda i : threshold(value, i))
img.paste(G)
elif choosed == "B":
B = B.point(lambda i : threshold(value, i))
img.paste(B)
else:
mask = img.point(lambda i : threshold(value, i))
img.paste(mask)
if __name__ == "__main__":
img = Image.open("../image/spidey.jpg")
i = int(input("threshold : "))
a = input("choose : ")
thresholding(img, i, a)
img.show()
os.system("pause")
</code></pre>
<h2>Pixelisation :</h2>
<p>I used lambda but I'm not sure that it's the best use of this ...</p>
<pre><code>"""
from random import sample
This module contain the function:
-pixelisation :
pixelise the picture with pixel of size you want
"""
class ImgPixelisation:
"""
A class containing all the element necessary to do a pixelisation effect
"""
def __init__(self, img, px_size):
#actual pos on the pic
self.x = 0
self.y = 0
#size of pic and zone
self.px_size = px_size
self.size_x, self.size_y = img.size
#each pixel value (rgb)
self.px = img.load()
self.end = False
self.avg = tuple
#lambda to avoid gooing too far on the line/column
self.max_x = lambda x : self.x + self.px_size if self.x + self.px_size <= self.size_x else self.size_x
self.max_y = lambda y : self.y + self.px_size if self.y + self.px_size <= self.size_y else self.size_y
def get_average(self):
""" get the average of each RGB component of each pixel of the zone """
sum = [0,0,0]
nb = self.px_size * self.px_size
for j in range(self.y, self.max_y(self.y)):
for i in range(self.x, self.max_x(self.x)):
sum[0] += self.px[i,j][0]
sum[1] += self.px[i,j][1]
sum[2] += self.px[i,j][2]
self.avg = (round(sum[0] / nb), round(sum[1] / nb), round(sum[2] / nb))
def fill(self):
""" fill the zone"""
for j in range(self.y, self.max_y(self.y)):
for i in range(self.x, self.max_x(self.x)):
self.px[i,j] = self.avg
def next_line(self):
self.x = 0
self.y += self.px_size
if self.x >= self.size_x and self.y >= self.size_y:
self.end = True
def next_column(self):
self.x += self.px_size
if self.x >= self.size_x and self.y >= self.size_y:
self.end = True
def end_line(self):
return self.x >= self.size_x
def pixelisation(img, px_size):
"""
The function for each zone of size px_size attribute the average color of
each pixel of the zone
"""
pixy = ImgPixelisation(img, px_size)
while (not pixy.end):
while(not pixy.end_line()):
pixy.get_average()
pixy.fill()
pixy.next_column()
pixy.next_line()
if __name__ == "__main__":
img = Image.open("../image/spidey.jpg")
i = int(input("pixelisation size : "))
pixelisation(img, i)
img.show()
print ("pixelisation: \n")
os.system("pause")
</code></pre>
<h2>Shuffling :</h2>
<p>Same way of proceeding as pixelisation.</p>
<pre><code>"""
This module contain the function:
-shuffling : shuffle the picture with zone of size you want
"""
class ImgShuffling:
"""
A class containing all the element necessary to do a shuffle effect
"""
def __init__(self, img, crop_size):
#actual pos on the pic
self.x = 0
self.y = 0
#size of pic and zone
self.crop_size = crop_size
self.size_x, self.size_y = img.size
self.end = False
self.all_croped = []
#lambda to avoid gooing too far on the line/column
self.max_x = lambda x : self.x + self.crop_size if self.x + self.crop_size <= self.size_x else self.size_x
self.max_y = lambda y : self.y + self.crop_size if self.y + self.crop_size <= self.size_y else self.size_y
def add_crop(self, img):
self.all_croped.append(img.crop((self.x, self.y, self.max_x(self.x), self.max_y(self.y))))
def shuffle(self):
self.all_croped = sample(self.all_croped, len(self.all_croped))
def past_it(self, img):
img.paste(self.all_croped[0], (self.x, self.y))
del self.all_croped[0]
def reset(self):
self.x = 0
self.y = 0
self.end = False
def next_line(self):
self.x = 0
self.y += self.crop_size
if self.x >= self.size_x and self.y >= self.size_y:
self.end = True
def next_column(self):
self.x += self.crop_size
if self.x >= self.size_x and self.y >= self.size_y:
self.end = True
def end_line(self):
return self.x >= self.size_x
def shuffling(img, crop_size):
"""
The function for each zone of size crop_size attribute randomly
another zone of crop_size
"""
shuffly = ImgShuffling(img, crop_size)
first_line = True
nb = 0
while (not shuffly.end):
while(not shuffly.end_line()):
nb = nb + 1 if first_line else nb
shuffly.add_crop(img)
shuffly.next_column()
shuffly.next_line()
first_line = False
new_size_x = nb * crop_size
new_size_y = int(len(shuffly.all_croped) / nb) * crop_size
shuffled_img = Image.new("RGB", (new_size_x, new_size_y))
shuffly.shuffle()
shuffly.reset()
while (not shuffly.end):
while(not shuffly.end_line()):
shuffly.past_it(shuffled_img)
shuffly.next_column()
shuffly.next_line()
img.paste(shuffled_img)
if __name__ == "__main__":
img = Image.open("../image/spidey.jpg")
i = int(input("pixelisation size : "))
shuffling(img, i)
img.show()
print ("shuffling: \n")
os.system("pause")
</code></pre>
<p>I have other functions, but I didn't post them because they are less interesting, you can check them here (the full project, with gui and unit tests) : <a href="https://github.com/NoobyBoy/Image-Manipulation-Training/tree/83cf04033f8133ca6b31344deb2ae7996cc2ce8f" rel="nofollow noreferrer">https://github.com/NoobyBoy/Image-Manipulation-Training</a></p>
<p>I'm also interrested if you have any idea about how to find a picture inside another one, I have tried some things but it was not very effective ^^', personally I was thinking about matrix but, but I'm not very good with them.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T16:29:40.910",
"Id": "398680",
"Score": "2",
"body": "The reason why 50 × 5.1 is not exactly 255 is that Python's floats are really [double-precision binary floating-point numbers](https://en.wikipedia.org/wiki/Floating-point_arithm... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T14:23:20.620",
"Id": "206665",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"image"
],
"Title": "Image Manipulation with PIL/Pillow - Picture effect/filter"
} | 206665 |
<p>I'd want to refactor that if ladder but I'm not sure how to do that or whether it is even possible</p>
<pre><code>public async List<ComplexObject> Generate(DateTime? data1, DateTime? data2, string FirstName, string SecondName)
{
var ListOfPredicates = new List<Func<ComplexObject, bool>>();
if (data1.HasValue)
{
ListOfPredicates.Add(new Func<ComplexObject, bool>(x => data1.Value <= x.data1));
}
if (data2.HasValue)
{
ListOfPredicates.Add(new Func<ComplexObject, bool>(x => data2.Value >= x.data2));
}
if (!string.IsNullOrEmpty(FirstName))
{
ListOfPredicates.Add(new Func<ComplexObject, bool>(x => x.FirstName.ToLower() == FirstName.ToLower()));
}
if (!string.IsNullOrEmpty(SecondName))
{
ListOfPredicates.Add(new Func<ComplexObject, bool>(x => x.SecondName.ToLower() == SecondName.ToLower()));
}
(...)
}
</code></pre>
<p>I thought about something like this:</p>
<pre><code>switch(true)
{
case expression (e.g x > 5):
}
</code></pre>
| [] | [
{
"body": "<p>One simple refactoring you could do is to use an extension method to simplify your code. </p>\n\n<pre><code>public static void AddIf(this List<Func<ComplexObject, bool>> list, bool condition, Func<ComplexObject, bool> item)\n{\n if (condition)\n list.Add(item);\n}\n\n... | {
"AcceptedAnswerId": "206670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T14:59:13.710",
"Id": "206666",
"Score": "-2",
"Tags": [
"c#",
"null"
],
"Title": "Refactoring null check before adding to Func collection with different predicates"
} | 206666 |
<p><em>Please, if you find a better title, tell me because I really didn't know what to put in here!</em></p>
<p>I like to guess how I could implement a game, and to be sure that my perception is working, I plan to develop small games. For instance, I plan to build a FFTA-like game, a FTL-like game, a tower-defense game, and so on. As a base, I created a bunch of rpg-classes (Warrior, Wizard, ...), and I want to use all of them in each of my futur game.</p>
<p>The only sure thing I know about what should be in common for every game is the stat system: </p>
<blockquote>
<ul>
<li>Strength </li>
<li>Constitution </li>
<li>Agility </li>
<li>Accuracy </li>
<li>Intelligence </li>
<li>Charisma </li>
<li>Luck </li>
</ul>
</blockquote>
<p>I will continue with what I plan to do, but I am not really sure about my choices:</p>
<pre><code>namespace General
{
public interface IStatsOwner
{
int Strength { get; }
int Constitution { get; }
int Agility { get; }
int Accuracy { get; }
int Intelligence { get; }
int Charisma { get; }
int Luck { get; }
}
public abstract class WarriorBase : IStatsOwner
{
public int Strength { get { return 5; } }
public int Constitution { get { return 4; } }
public int Agility { get { return 3; } }
public int Accuracy { get { return 3; } }
public int Intelligence { get { return 2; } }
public int Charisma { get { return 3; } }
public int Luck { get { return 1; } }
}
public abstract class WizardBase : IStatsOwner
{
public int Strength { get { return 2; } }
public int Constitution { get { return 3; } }
public int Agility { get { return 3; } }
public int Accuracy { get { return 3; } }
public int Intelligence { get { return 5; } }
public int Charisma { get { return 4; } }
public int Luck { get { return 1; } }
}
public interface IGame
{
Type WarriorType { get; }
Type WizardType { get; }
}
}
</code></pre>
<hr>
<pre><code>namespace FFTALike
{
public interface IDamageable
{
void TakeDamages();
}
public class Warrior : General.WarriorBase, IDamageable
{
public void TakeDamages() { Console.WriteLine($"Taking damages with CON={Constitution}"); }
}
public class Wizard : General.WizardBase, IDamageable
{
public void TakeDamages() { Console.WriteLine($"Taking damages with CON={Constitution}"); }
}
public Game : IGame
{
public Type WarriorType { get { return typeof(Warrior); } }
public Type WizardType { get { return typeof(Wizard); } }
}
}
</code></pre>
<hr>
<pre><code>namespace TowerDefense
{
public interface ILocatable
{
Location Location { get; set; } // Location(int X, int Y)
}
public interface IShooter
{
void Shoot();
}
public class Warrior : WarriorBase, ILocatable, IShooter
{
public Location Location { get; set; }
public void Shoot() { Console.WriteLine($"Shooting with STR={Strength}"); }
}
public class Wizard : WizardBase, ILocatable, IShooter
{
public Location Location { get; set; }
public void Shoot() { Console.WriteLine($"Shooting with STR={Strength}"); }
}
public Game : IGame
{
public Type WarriorType { get { return typeof(Warrior); } }
public Type WizardType { get { return typeof(Wizard); } }
}
}
</code></pre>
<hr>
<p>What I feel uncomfortable with is: </p>
<blockquote>
<ul>
<li>I don't enforce the fact that <code>IGame.WarriorType</code> inherits <code>WarriorBase</code> </li>
<li>I duplicate <code>TakeDamages()</code>, <code>Location { get; set; }</code> and <code>Shoot()</code> (I actually have 20 rpg-classes, so I <em>isocuplate</em> these implementations) </li>
</ul>
</blockquote>
<p>Please note that I want the final implementation to fit with <code>SOLID</code> principles, because I want these projects to be training projects.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T16:16:10.620",
"Id": "398676",
"Score": "1",
"body": "This doesn't look like working code to me, and I don't see concrete game-specific requirements, so I'm afraid this is off-topic here. Either way, I think you're trying to general... | [
{
"body": "<p>I'm having trouble visualizing what your intention here is.</p>\n\n<p>Let's talk about your code itself, then I'll move on to a slight redesign:</p>\n\n<p>C# has a nice-new language feature called \"Expression-Bodied members\", basically, this:</p>\n\n<pre><code>public int Strength => 5;\n</cod... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T15:21:05.533",
"Id": "206669",
"Score": "4",
"Tags": [
"c#",
"inheritance"
],
"Title": "Multiple games with same rpg-classes base"
} | 206669 |
<p>I'm using Node/Express/Mongoose to accept a JSON file containing a list of product details. These products are looped through, the images are uploaded to AWS S3, and the product is either accepted or rejected depending on validation. In the end the accepted products are uploaded to Mongo via Mongoose and all are returned to provide info to the uploader. This is my first time with any of these frameworks so I'm looking to improve best practices and find potential points of failure.</p>
<p><strong>ProductRoutes.js</strong></p>
<pre><code>const keys = require("../config/keys.js");
const mongoose = require("mongoose");
const requireLogin = require("../middlewares/requireLogin");
var validator = require("validator");
const fileUpload = require("express-fileupload");
var fs = require("fs");
const aws = require("aws-sdk");
const S3_BUCKET = keys.awsBucket;
var path = require("path");
var request = require("request");
aws.config.update({
region: "us-east-2",
accessKeyId: keys.awsAccessKey,
secretAccessKey: keys.awsSecretKey
});
require("../models/Product");
const Product = mongoose.model("product");
function validate(value, type) {
switch (type) {
case "string":
return value && !validator.isEmpty(value, { ignore_whitespace: true });
case "url":
return (
value &&
!validator.isURL(value, {
protocols: ["https, http"],
require_protocol: true
})
);
default:
return value && validator.isEmpty(value, { ignore_whitespace: true });
}
return value == null || value.length === 0;
}
function saveImage(url, key) {
let ext = path.extname(url);
let params = {
Key: key + ext,
Bucket: S3_BUCKET,
ACL: "public-read"
};
return new Promise(function(resolve, reject) {
request.get(url).on("response", function(response) {
if (response.statusCode === 200) {
params.ContentType = response.headers["content-type"];
var s3 = new aws.S3({ params })
.upload({ Body: response })
.send(function(err, data) {
resolve(data);
});
} else {
// return false;
reject(false);
}
});
});
}
module.exports = app => {
app.use(fileUpload());
app.post("/product/addProduct", requireLogin, async (req, res) => {
let products = req.files.file.data;
try {
products = JSON.parse(products);
} catch (e) {
return res
.status(400)
.json({ success: false, message: "Invalid JSON product feed" });
}
let accepted = [];
let rejected = [];
for (const product of products) {
if (!validate(product.sku, "string")) {
rejected.push(product);
return;
}
if (!validate(product.image_url, "url")) {
rejected.push(product);
return;
}
try {
let result = await saveImage(product.image_url, `${product.owner}/${product.sku}`);
product.image_url = result.Location;
} catch (err) {
// catches errors both in fetch and response.json
return res.status(400).json({
success: false,
message: "Could not upload image",
error: err
});
}
let upsertProduct = {
updateOne: {
filter: { sku: product.sku },
update: product,
upsert: true
}
};
accepted.push(upsertProduct);
}
// now bulkWrite (note the use of 'Model.collection')
Product.collection.bulkWrite(accepted, function(err, docs) {
if (err) {
return res.status(400).json({
success: false,
message: "Something went wrong, please try again"
});
} else {
return res.status(200).json({
success: true,
message: "Company successfully created",
accepted: { count: accepted.length, list: accepted },
rejected: { count: rejected.length, rejected: rejected },
affiliate: docs
});
}
});
});
app.get("/product/fetchAffiliateProducts", requireLogin, (req, res) => {
var affiliateId = req.query.affiliateId;
Product.find({ owner: affiliateId }, function(err, products) {
if (err) {
return res.status(400).json({
success: false,
message: "Could not find the requested company's products"
});
} else {
return res.status(200).json({
success: true,
message: "Products successfully found",
products: products
});
}
});
});
};
</code></pre>
<p><strong>Product.js (model):</strong></p>
<pre><code>const mongoose = require('mongoose');
const {Schema} = mongoose;
const productSchema = new Schema({
sku: {type: String, unique: true, required: true},
name: {type: String, required: true},
owner: {type: String, required: true},
image_url: {type: String, required: true}
});
mongoose.model('product', productSchema);
</code></pre>
<p><strong>Sample input</strong></p>
<pre><code>[
{
"sku": "123",
"name": "Test Product 1",
"owner": "Test Company 1",
"image_url": "https://exmaple.com/src/assets/product1.png"
},
{
"sku": "456",
"name": "Test Product 3",
"owner": "Test Company 2",
"image_url": "https://exmaple.com/src/assets/product2.png"
},
{
"sku": "789",
"name": "Test Product 3",
"owner": "Test Company 3",
"image_url": "https://exmaple.com/src/assets/product3.png"
}
]
</code></pre>
<p>If there are other contextual files/code needed let me know; this is all that seemed relevant.</p>
| [] | [
{
"body": "<p>There's nothing outstandingly wrong, there are some minor points that can be improved.</p>\n\n<p>The main concern that I have is the amount of logic happening inside the <code>ProductRoutes</code> file. Your invocation of the AWS library and the <code>validate</code> & <code>saveImage</code> f... | {
"AcceptedAnswerId": "207004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T16:33:55.683",
"Id": "206680",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"express.js",
"mongoose",
"amazon-web-services"
],
"Title": "Upload .JSON product list to MongoDB and upload image to AWS S3"
} | 206680 |
<p>From a sorted vector of indices (<code>toRemove</code>), I would like to remove from another vector (<code>v</code>) the elements at these indices. Note that I need to preserve the order of the remaining elements in <code>v</code>. <code>toRemove</code> can be modified at will however.</p>
<p>An easy way to do it would be to start with the last element of <code>toRemove</code> and remove them sequentially. However, that would require copying elements at the end of the vector several times which is slow when the vector is large.</p>
<p>Here is an alternative using the erase-remove idiom:</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
template <typename INT, typename T> // INT could be int, unsigned int, char, size_t, etc...
void removeIndicesFromVector(std::vector<T>& v, std::vector<INT>& rm )
{
// For speed, I am assuming that 'rm' is sorted
size_t rm_index = 0;
v.erase(
std::remove_if(std::begin(v), std::end(v), [&](T& elem)
{
if (rm.size() != rm_index && &elem - &v[0] == rm[rm_index])
{
rm_index++;
return true;
}
return false;
}),
std::end(v)
);
}
template <typename T>
void print(std::vector<T> v)
{
for (size_t i = 0 ; i < v.size();i++)
{
std::cout << v[i] << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<std::string> v = {"Alice", "Smith", "is", "very", "clever", "and", "is", "very", "nice"};
print(v);
std::vector<int> toRemove = {1,6};
removeIndicesFromVector(v,toRemove);
print(v);
return 0;
}
</code></pre>
<p>The code outputs as expected:</p>
<pre class="lang-none prettyprint-override"><code>Alice Smith is very clever and is very nice
Alice is very clever and very nice
</code></pre>
<p><strong>Is there a "better" alternative to my function <code>removeIndicesFromVector</code>?</strong></p>
<p>By "better", I mean faster / better names / cleaner / more standard / one that is as fast but does not assume 'rm' is sorted. If it matters, note that the object that will need to be removed will rarely be any bigger than the <code>std::string</code>s considered here but the vector will be much longer.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T11:49:10.267",
"Id": "398780",
"Score": "2",
"body": "Just to be clear, do we need to preserve the order of the remaining elements in `v`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-06T18:37:15.400"... | [
{
"body": "<p>That's a worthwhile problem to solve, and a good solution.</p>\n\n<p>Trivial fix: <code>std::size_t</code> is misspelt in a couple of places.</p>\n\n<p>One easy change I'd make is that <code>rm</code> can be <code>const std::vector<INT>&</code>, since we won't be modifying it. That's he... | {
"AcceptedAnswerId": "206708",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T19:23:54.540",
"Id": "206686",
"Score": "9",
"Tags": [
"c++",
"algorithm",
"vectors"
],
"Title": "Removing by indices several elements from a vector"
} | 206686 |
<p>Please, correct me with anything that I say in here (The actual question is below the code).</p>
<p>I've been quickly prototyping a project (ASP.NET Core 2.1) and haven't found the need to structure it with Webpack/Parcel/Rollup/Browserify as it's done with simple JavaScript validations per views (I do minify the files with Gulp).</p>
<p>Since I'm not enclosing my files into modules, they're all open to the global scope (bad idea, right?). Therefore, I've decided to "namespace" them by running everything inside a JavaScript variable. </p>
<p>The code that I have looks like this:</p>
<pre><code>const formValidation = {
submitBtn : null as unknown as HTMLButtonElement,
errors: null as unknown as string[],
errorsDiv: null as unknown as HTMLDivElement,
gradeSections: null as unknown as HTMLDivElement,
form: null as unknown as HTMLFormElement,
mapDOM() {
this.submitBtn = document.getElementById('js-btn-submit') as HTMLButtonElement;
this.errorsDiv = document.getElementById('js-errors') as HTMLDivElement;
this.gradeSections = document.getElementById('js-grade-sections') as HTMLDivElement;
this.form = document.getElementById('js-submit-form') as HTMLFormElement;
this.mapEventListenersFormValidation();
},
mapEventListenersFormValidation() {
this.submitBtn.addEventListener('click', this.submit.bind(this));
},
submit(evt: Event) {
console.log(evt);
evt.preventDefault();
this.resetForms();
if (!this.checkIfSubmitIsValid()) {
this.showErrors();
return;
}
this.form.submit();
},
checkIfSubmitIsValid() {
this.errors = [];
const subjectSelected = this.isSubjectSelected();
const sectionsSelected = this.areSectionsSelected();
if (!subjectSelected) {
selectSubjectDropdown.classList.add('is-invalid');
this.errors.push('Debe de seleccionar por lo menos una materia');
}
if (!sectionsSelected) {
this.gradeSections.classList.add('form-error');
this.errors.push('Debe de seleccionar al menos una sección');
}
return subjectSelected && sectionsSelected;
},
isSubjectSelected() {
return selectSubjectDropdown.selectedIndex !== 0;
},
areSectionsSelected() {
return selectedSectionCounter > 0;
},
showErrors() {
if (!this.errorsDiv || !this.errorsDiv.parentElement) {
return;
}
this.errorsDiv.parentElement.removeAttribute('hidden');
this.errorsDiv.innerHTML = '';
this.errors.forEach((error) => {
const li = document.createElement('li');
li.innerHTML = error;
this.errorsDiv.appendChild(li);
});
},
resetForms() {
selectSubjectDropdown.classList.remove('is-invalid');
this.gradeSections.classList.remove('form-error');
},
};
DOMReady(formValidation.mapDOM.bind(formValidation));
</code></pre>
<p>Check the submitBtn, errors, and errorsDiv properties. AFAIK, JavaScript doesn't have a way to declare an "empty" property. Therefore something sane would be to assign it either <code>undefined</code> or <code>null</code>. </p>
<p>As I want to have it statically defined (through TypeScript), I want to assign a type to those properties. The problem is that I just can't assign a non-nullable type to a null. </p>
<p>As I'm trying to avoid non-implicit any's in the scripts, the compiler suggested me to use <code>unknown</code>. </p>
<p>The question is, whether it's ok for me to use the <code>unknown</code> type from TypeScript to cast a null to an unknown so it can let me cast it to the type that I'm going after.</p>
<p><strong>Edit</strong> Ended up adding the whole document into it. I was working with that function, so it's different now.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:14:27.983",
"Id": "398801",
"Score": "0",
"body": "The code to be reviewed looks sketchy or incomplete: where are `checkIfSubmitIsValid()` and `showErrors()` defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationD... | [
{
"body": "<p>The compiler can't know beforehand if <code>document.getElementById('js-btn-submit')</code> wil return anything. That is why you cannot assign the result directly to a type.</p>\n\n<p>One solution is to tell the compiler that you are certain that the HTML element exists, using <code>!</code></p>\n... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T20:20:47.937",
"Id": "206689",
"Score": "2",
"Tags": [
"validation",
"dom",
"typescript",
"null",
"type-safety"
],
"Title": "TypeScript 3 form validation object"
} | 206689 |
<p>I am building an e-commerce website. I have an application layer service called <code>SearchService</code>. <code>SearchService</code> receives a search request from the view through <code>HomeSearchRequestViewModel</code> (home page search request view model). Then it maps the request to Elasticsearch request entity and sends the search request to the search engine.</p>
<p>Elasticsearch performs the search and returns the result. The result from ES is a flattened (denormalized object). I use a factory to instantiate my Ad Summary View Model from ES result.</p>
<pre><code>public class SearchService : ISearchService
{
private ISearchClient _searchClient;
public SearchService(ISearchClient searchClient)
{
_searchClient = searchClient;
}
public HomeListViewModel Search(HomeSearchRequestViewModel searchRequest)
{
// map search request View Model to Elasticsearch request entity
HomeESRequestMapper esRequestBuilder = new HomeESRequestMapper(searchRequest);
var elasticsearchRequest = esRequestBuilder.GetESRequest();
// do the search
ESResultContainer esResultContainer = _searchClient.SearchDocuments(elasticsearchRequest);
// map ES result to view model
List<IAdSummary> adSummaries = AdSummaryFactory.CreateAdSummaryInstance(esResultContainer.AdResults);
// put the summary View Models in HomeListViewModel container
HomeListViewModel homeList = new HomeListViewModel(searchRequest.MainQuery)
{
SearchResult =
{
AdSummaries = adSummaries,
ServerError = esResultContainer.ServerError
},
HomeSearchRequest = searchRequest
};
return homeList;
}
}
</code></pre>
<p>This is <code>ESResultContainer</code>, which is a container for ES Result:</p>
<pre><code>public class ESResultContainer
{
public ESResultContainer(string serverError = "")
{
AdResults = new List<AdResult>();
ServerError = serverError;
}
public List<AdResult> AdResults { get; set; }
public string ServerError { get; set; }
}
</code></pre>
<p><code>AdResult</code> is the denormalized model which is returned from ES:</p>
<pre><code>[ElasticsearchType(Name = "ad")]
public class AdResult
{
public AdResult()
{
Distance = -1;
}
[Text(Index = false)]
public int Distance { get; set; }
public long Id { get; set; }
public long AdChangeTrackerId { get; set; }
public bool IsActive { get; set; }
[Text(Analyzer = "english")]
public string Title { get; set; }
public short AdDurationInDays { get; set; }
public DateTime AdStartTime { get; set; }
[Text(Analyzer = "english")]
public string Description { get; set; }
public string MainPhotoUrl { get; set; }
public int ChildCategoryId { get; set; }
[Text(Analyzer = "english")]
public string ChildCategoryName { get; set; }
public string Controller { get; set; }
public int ParentCategoryId { get; set; }
[Text(Analyzer = "english")]
public string ParentCategoryName { get; set; }
public GeoLocation GeoLocation { get; set; }
public string Locality { get; set; }
public string Area { get; set; }
public decimal Price { get; set; }
public decimal Rent { get; set; }
public DateTime AvailableFrom { get; set; }
public short NoOfBedrooms { get; set; }
public short NoOfBathrooms { get; set; }
public bool PetFriendly { get; set; }
public bool Furnished { get; set; }
public string Make { get; set; }
}
</code></pre>
<p>This is the static factory, for instantiating my Ad Summery View Models. Each Search Result object has a <code>Controller</code> property. The controller determines the type of View Model that this object belongs to. For Example if <code>Controller = "Car"</code> then I would have to instantiate a <code>CarAdSummaryViewModel</code> (which implements <code>IAdSummary</code>).</p>
<pre><code> // I am using static because I want to maintain the list of AdSummary types in memory, so I won't have to reload it from the disk everytime
public static class AdSummaryFactory
{
private static readonly Dictionary<string, Type> AdSummaryTypes;
// when factory initializes, I load all the types (ad summary view models) which implement IAdSummary and keep it in memory
static AdSummaryFactory()
{
// load ad summary types
AdSummaryTypes = new Dictionary<string, Type>();
IEnumerable<Type> typesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();
foreach (Type type in typesInThisAssembly)
{
if (type.GetInterface(typeof(IAdSummary).ToString()) != null)
{
AdSummaryTypes.Add(type.Name.ToLower(), type);
}
}
}
public static List<IAdSummary> CreateAdSummaryInstance(List<AdResult> esResults)
{
List<IAdSummary> adSummaries = new List<IAdSummary>();
foreach (var esResult in esResults)
{
// choose type of Ad Summery based on controller name
type = GetTypeToCreate(esResult.Controller);
// use AutoMapper to map ES result to the correct AdSummay View Model Type
var adSummary = Mapper.Map(esResult, typeof(AdResult), type);
adSummaries.Add((IAdSummary)adSummary);
}
return adSummaries;
}
private static Type GetTypeToCreate(string controller)
{
string adSummaryTypeName = controller.ToLower() + "summaryviewmodel";
if (AdSummaryTypes.TryGetValue(adSummaryTypeName, out Type type))
{
return type;
}
throw new Exception($"{adSummaryTypeName} type was not found, or it does not implement IAdSummary.");
}
}
</code></pre>
<p>This is how my <code>AdSummery</code> interface look like:</p>
<pre><code>public interface IAdSummary
{
string GetMainPhoto();
string GetTitle();
string GetLocation();
string GetMonetaryValue();
string GetLink();
string GetHighlight();
}
</code></pre>
<p>My View Models implement this interface... they have a hierarchical structure. They all inherit from: <code>AdBaseSummaryViewModel</code></p>
<pre><code>public abstract class AdBaseSummaryViewModel : IAdSummary
{
public AdBaseSummaryViewModel()
{
Distance = -1;
}
public long AdBaseId { get; set; }
public string Title { protected get; set; }
public int ChildCategoryId { protected get; set; }
public string ChildCategoryName { protected get; set; }
public int ParentCategoryId { protected get; set; }
public string ParentCategoryName { protected get; set; }
public string Controller { protected get; set; }
public string MainPhotoUrl { protected get; set; }
public string Locality { protected get; set; }
public string Area { protected get; set; }
public int Distance { protected get; set; } // distance from searched location, if any
public string GetMainPhoto()
{
return MainPhotoUrl;
}
public string GetTitle()
{
return Title;
}
public string GetLocation()
{
if (Distance == 0)
{
Distance = 1;
}
if (Distance > 0 && Distance < 100)
{
return "< " + Convert.ToString(Distance) + " km"; // < 5 km
}
if (!string.IsNullOrEmpty(Locality))
{
return Locality;
}
return Area;
}
public abstract string GetMonetaryValue();
public string GetLink()
{
return $"{Controller}/Display/{AdBaseId}";
}
public virtual string GetHighlight()
{
return string.Empty;
}
}
</code></pre>
<p>Now each concrete Advertisement type, e.g. Car, RealEstate, etc inherit from the above base call (which implements <code>IAdSummery</code>), as an example this is <code>CarSummaryViewModel</code>:</p>
<pre><code>public class CarSummaryViewModel : AdBaseSummaryViewModel
{
public CarSummaryViewModel()
: base()
{
}
public decimal Price { protected get; set; }
public string Make { protected get; set; }
public override string GetMonetaryValue()
{
return Price.ToString("N"); // 1590.99 => 1,590.99
}
}
</code></pre>
<p>I would appreciate any feedback on the above logic... one thing that I am unsure of, is the usage of static factory (I am using a static factory as it can keep object types in memory, to avoid disk IO every time)... I did think about replacing this static factory with a DI container, but could not think of any solution better that the existing factory.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T21:42:14.097",
"Id": "398738",
"Score": "2",
"body": "Why do you think that this factory is better the a DI container? Could you explain what `Mapper` and `AdResult` are? These types seem to be missing."
},
{
"ContentLicense... | [
{
"body": "<p>That class can still be abstracted </p>\n\n<pre><code>public interface IAdSummaryMapper {\n List<IAdSummary> MapAdSummaries(List<AdResult> esResults);\n}\n</code></pre>\n\n<p>The search service can then explicitly depend on the abstraction and not be tightly couple to static implem... | {
"AcceptedAnswerId": "206695",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T21:15:36.517",
"Id": "206692",
"Score": "3",
"Tags": [
"c#",
"asp.net-mvc",
"dependency-injection",
"factory-method"
],
"Title": "Instantiating View Models using a static factory"
} | 206692 |
<p>I'm learning Java and I've started writing some tasks. Could you give me feedback for it?</p>
<blockquote>
<p>Write a static method <code>andThen</code> that takes as parameters two Runnable instances
and returns a Runnable that runs the first, then the second. In the main method,
pass two lambda expressions into a call to <code>andThen</code> , and run the returned
instance.</p>
</blockquote>
<pre><code>public class Exercise7 {
public static class Thread1 implements Runnable {
@Override
public void run() {
System.out.println("Echo from thread1");
}
}
public static class Thread2 implements Runnable {
@Override
public void run() {
System.out.println("Echo from thread2");
}
}
public static Runnable andThen(Runnable thread1, Runnable thread2) {
return () -> {
thread1.run();
thread2.run();
};
}
public static void main(String[] args) {
Runnable thread1 = new Thread1();
Runnable thread2 = new Thread2();
andThen(thread1,thread2).run();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T23:32:05.600",
"Id": "399012",
"Score": "1",
"body": "You should be aware that `thread1` and `thread2` are \"threads\" in name only. There is no multithreading going on: all of your code is running on the main thread."
}
] | [
{
"body": "<p>Your code is fine, but neither the question nor your answer have anything to do with threads. In order to run two separate threads, you need to create a <code>Thread</code> object with your runnable, rather than just calling <code>myRunnable.run()</code>. The first runnable returns to the scope of... | {
"AcceptedAnswerId": "206846",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T21:41:36.560",
"Id": "206694",
"Score": "0",
"Tags": [
"java",
"lambda"
],
"Title": "Threads with lambdas and runnable in Java"
} | 206694 |
<p>I'm currently working on creating a mask for an image. I have initialized a two-dimensional numpy zeros array. I now want to replace the values of the mask corresponding to pixels following some conditions such as x1< x < x2 and y1 < y < y2 (where x and y are the coordinates of the pixels) to 1.</p>
<p>Is there an easier way to do it (maybe through slicing) without looping through the mask like below</p>
<pre><code>clusterMask = np.zeros((h, w))
for x in range(h):
for y in range(w):
if x <= clusterH + 2 * S and x >= clusterH - 2*S and y <= clusterW + 2*S and y >= clusterW - 2*S:
clusterMask[x][y] = 1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T08:23:21.650",
"Id": "398766",
"Score": "0",
"body": "Just got the solution. It turns out you can change values in Numpy using slicing. All I had to do was: `clusterMask[clusterH - 2*S:clusterH + 2*S, clusterW - 2*S : clusterW + 2*S... | [
{
"body": "<p>It turns out that Numpy has various nifty ways of indexing. I found that my question can be solved by</p>\n\n<pre><code>clusterMask[clusterH - 2*S : clusterH + 2*S, clusterW - 2*S : clusterW + 2*S] = 1\n</code></pre>\n\n<p>As given in one of the comments, this link contains all information regardi... | {
"AcceptedAnswerId": "206721",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T07:43:40.230",
"Id": "206704",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Marking a rectangular region in a NumPy array as an image mask"
} | 206704 |
<p>I have two time intervals <code>i1</code> and <code>i2</code>, each defined by two values, <code>begin</code> and <code>end</code> (epoch time). I need to write a function returning a boolean value indicating whether the intervals overlap. </p>
<p>According to my understanding, an overlap can occur in four following cases:</p>
<p><a href="https://i.stack.imgur.com/nTBIi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nTBIi.png" alt="enter image description here"></a></p>
<p>while the last case (where the <code>i2</code> is fully included within <code>i1</code> is already covered by first two cases so can be dismissed.</p>
<p>The remaining three cases lead me to the following logic:</p>
<pre><code>private static boolean isThereOverlap(Interval t1, Interval t2) {
return t1.begin.isAfter(t2.begin) && t1.begin.isBefore(t2.end) ||
t1.end.isAfter(t2.begin) && t1.end.isBefore(t2.end) ||
t1.begin.isBefore(t2.begin) && t1.end.isAfter(t2.end);
}
</code></pre>
<p>where:</p>
<p><code>t1</code> and <code>t2</code> represent <code>i1</code> and <code>i2</code> accordingly.</p>
<p>I wonder whether there's a more concise way to identify the overlap or a
way to simplify the code?</p>
<p><strong>EDIT1</strong>:</p>
<p>Including the <code>Interval</code> class which is utilizing <code>java.time</code>:</p>
<pre><code>import java.time.Instant;
private class Interval {
private Instant begin;
private Instant end;
private Interval(long begin, long end) {
this.begin = Instant.ofEpochMilli(begin);
this.end = Instant.ofEpochMilli(end);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T13:32:41.327",
"Id": "398795",
"Score": "1",
"body": "Is that `Interval` constructor really `private`? How then are you creating new instances of it? Please show your real actual code."
},
{
"ContentLicense": "CC BY-SA 4.0",... | [
{
"body": "<p>Your code uses an algorithm that directly tests for an overlap of time spans, but a simpler algorithm is to check for a non-overlap - to check for whether the time-spans are completely distinct. The spans are distinct if the first span starts after the other ends, or ends before the other one star... | {
"AcceptedAnswerId": "206733",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T09:47:39.210",
"Id": "206710",
"Score": "15",
"Tags": [
"java",
"datetime",
"interval"
],
"Title": "Checking if two time intervals overlap"
} | 206710 |
<blockquote>
<p>Take an integer representing a day of the year and translate it to a string consisting of the month followed by day of the month. For example, Day 32 would be February 1.</p>
</blockquote>
<p>This is what I came up with. I'm sure that there's something more streamlined than else if statements.</p>
<pre><code>vector<string>DayOfYear::months = { "January","February","March","April",
"May","June","July","August",
"September","October","November","December"};
string DayOfYear::convertDayOfYear(int num){
if (num <= 31)
return months[0] + " " + to_string(num);
else if (num > 31 && num <= 59)
return months[1] + " " + to_string(num - 31);
else if (num > 59 && num <= 90)
return months[2] + " " + to_string(num - 59);
else if (num > 90 && num <= 120)
return months[3] + " " + to_string(num - 90);
else if (num > 120 && num <= 151)
return months[4] + " " + to_string(num - 120);
else if (num > 151 && num <= 181)
return months[5] + " " + to_string(num - 151);
else if (num > 181 && num <= 212)
return months[6] + " " + to_string(num - 181);
else if (num > 212 && num <= 243)
return months[7] + " " + to_string(num - 212);
else if (num > 243 && num <= 273)
return months[8] + " " + to_string(num - 243);
else if (num > 273 && num <= 304)
return months[9] + " " + to_string(num - 273);
else if (num > 304 && num <= 334)
return months[10] + " " + to_string(num - 304);
else if (num > 334 && num <= 365)
return months[11] + " " + to_string(num - 334);
else
return "Invalid number.\n";
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:26:53.190",
"Id": "398804",
"Score": "3",
"body": "What about leap years? February can have 28 or 29 days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T16:15:33.343",
"Id": "398825",
"Sc... | [
{
"body": "<p>This code is incomplete, so we'll have to guess there's a definition of <code>namespace DayOfYear</code>, or <code>struct DayOfYear</code>, somewhere. In future, please provide more context for reviews - ideally, we'd be able to take your code and compile it ourselves.</p>\n\n<p>There's a problem... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T10:24:47.467",
"Id": "206712",
"Score": "1",
"Tags": [
"c++",
"c++11",
"datetime"
],
"Title": "Translate a day in year to month and day"
} | 206712 |
<p>So i'm using this for pooling my gameObjects in game. Every other script can ask for a <em>pooled</em> <code>GameObject</code> using <code>GetElementFromPool</code> and normaly i'm using return to pool when <code>GameObject</code> is disabled.</p>
<p>My doubts:
1: I'm taking the last <code>gameObject</code> from the <code>List<GameObject></code> since the list have an <code>array</code> in ts implementation, so taking the last object will avoid shifts i suppose. am i right?</p>
<p>2: Can i avoid renaming the Instantiated GameObject in Unity? Instantiate will name it "name(Clone)"</p>
<p>3: Of course any other suggestion is welcome</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolSystem : MonoBehaviour
{
public static Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>();
#region cached
private static GameObject lastReturned;
#endregion
public static GameObject GetElementFromPool(GameObject g)
{
if (!pool.ContainsKey(g.name))
{
lastReturned = Instantiate(g) as GameObject;
pool.Add(g.name, new List<GameObject>());
lastReturned.name = g.name;
return lastReturned;
}
if (pool[g.name].Count == 0)
{
lastReturned = Instantiate(g) as GameObject;
lastReturned.name = g.name;
}
else
{
lastReturned = pool[g.name][pool[g.name].Count - 1];
pool[g.name].RemoveAt(pool[g.name].Count - 1);
}
return lastReturned;
}
public static void AddToPool(GameObject g)
{
if (!pool.ContainsKey(g.name))
{
pool.Add(g.name, new List<GameObject>());
}
pool[g.name].Add(g);
}
}
</code></pre>
<p>Reviewed version:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolSystem : MonoBehaviour
{
public static Dictionary<string, Stack<GameObject>> pool = new Dictionary<string, Stack<GameObject>>();
#region cached
private static GameObject lastReturned;
private static Stack<GameObject> lastUsedStack;
#endregion
public static GameObject GetElementFromPool(GameObject g)
{
if (pool.TryGetValue(g.name, out lastUsedStack))
{
if (pool[g.name].Count == 0)
{
lastReturned = Instantiate(g) as GameObject;
lastReturned.name = g.name;
}
else
{
lastReturned = pool[g.name].Pop();
}
}
else
{
lastReturned = Instantiate(g) as GameObject;
pool.Add(g.name, new Stack<GameObject>());
lastReturned.name = g.name;
return lastReturned;
}
return lastReturned;
}
public static void AddToPool(GameObject g)
{
if (!pool.ContainsKey(g.name))
{
pool.Add(g.name, new Stack<GameObject>());
}
pool[g.name].Push(g);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T12:00:34.067",
"Id": "398784",
"Score": "0",
"body": "Why do you need `AddToPool` when `GetElementFromPool` is doing virtually exactly the same thing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T1... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T11:13:35.903",
"Id": "206716",
"Score": "2",
"Tags": [
"c#",
"unity3d"
],
"Title": "Unity Generic Pool System"
} | 206716 |
<p>I am working on a simple event mechanism for c++. Since Iam not very experienced I would like to share my code in order to get some thoughts. </p>
<p>I also dont like the BIND_X macros. Ideas how to simplify the binding process are welcome as well any comments regarding problems, bad style... </p>
<pre><code>#ifndef EVENTS_H
#define EVENTS_H
#include <functional>
#include <algorithm>
#include <random>
#include <limits>
#include <string>
#include <forward_list>
#include <mutex>
namespace event {
// The type of the source identifier passed to each event listener
typedef const std::string& source_t;
///
/// \brief A handle that identifiers listeners.
///
/// \details Listeners are functions that get called once a event is fired.
/// This struct is used to identify such functions and is used to detach them.
///
struct listener_handle
{
public:
///
/// \brief Create a new handle
/// \param s The source
/// \param h The handle id
///
listener_handle(source_t s="", int h=0) :
source(s),
handle(h)
{ }
///
/// \brief Equals operator
/// \param other The handle to compare
/// \return True, if the handles are equal
///
bool operator==(const listener_handle& other) const
{
return this->source == other.source &&
this->handle == other.handle;
}
std::string source;
int handle;
};
template <class... T>
///
/// \brief The event class.
///
class Event
{
public:
typedef std::function<void(source_t, T...)> func;
///
/// \brief Create new instance
/// \param source The name of the event source.
///
Event(source_t source) :
source(source)
{}
///
/// \brief Release resources
///
virtual ~Event()
{
this->listeners.clear();
}
///
/// \brief Attach an event
/// \param newListener The event listener to attach
/// \return The handle that may be used to detach the event
///
virtual listener_handle& Attach(const func& newListener)
{
this->listeners.push_front(Listener{newListener, this->createListenerHandle()});
return this->listeners.front().handle;
}
///
/// \brief Detach an event using its id
/// \param id The id of the event to detach
///
virtual void Detach(const listener_handle& handle)
{
this->listeners.remove_if([handle] (const Listener& l) {return l.handle == handle;});
}
///
/// \brief Call all listeners
/// \param argument The EventArgs to send
///
virtual void Invoke(const T&... args) const
{
std::for_each(std::begin(this->listeners), std::end(this->listeners), [this, &args...] (const Listener& l) {
l.listener(this->source, args...);
});
}
private:
struct Listener {
func listener;
listener_handle handle;
};
///
/// \brief Create a random number using per thread local seed.
/// \return A random number between int min and int max
///
int createRandom() const
{
static std::mt19937 gen{std::random_device{}()};
static std::uniform_int_distribution<> dist{
std::numeric_limits<int>::min(),
std::numeric_limits<int>::max()};
return dist(gen);
}
///
/// \brief Create a new listener handle using the registered source name
/// \return A new listener handle
///
listener_handle createListenerHandle() const
{
return listener_handle{this->source, this->createRandom()};
}
std::string source;
std::forward_list<Listener> listeners;
};
template <typename... T>
///
/// \brief The thread safe event class.
///
/// \details This class should be used if the exposed event may be accessed from multiple threads.
///
class TsEvent : public Event<T...>
{
public:
///
/// \copydoc Event::Event()
///
TsEvent(source_t source): Event<T...>(source)
{ }
///
/// \copydoc Event::~Event()
///
virtual ~TsEvent()
{ }
///
/// \copydoc Event::Attach()
///
virtual listener_handle& Attach(const typename Event<T...>::func& newListener) override
{
std::lock_guard<std::mutex> lg(this->m);
return Event<T...>::Attach(newListener);
}
///
/// \copydoc Event::Detach()
///
virtual void Detach(const listener_handle& handle) override
{
std::lock_guard<std::mutex> lg(this->m);
return Event<T...>::Detach(handle);
}
///
/// \copydoc Event::Invoke()
///
virtual void Invoke(const T&... args) const override
{
std::lock_guard<std::mutex> lg(this->m);
return Event<T...>::Invoke(args...);
}
private:
std::mutex m;
};
} //event namespace
#endif // EVENTS_H
</code></pre>
<p>Sample usage (assume CallMe is a static function with 2 parameter):</p>
<pre><code>#include <string>
#include <iostream>
#include "event.hpp"
void CallMe(std::string s, int i) {
std::cout << s << "-" << i << '\n';
}
int main() {
auto t = new event::Event<int>{"Basic"};
auto handle = t->Attach(std::function<void(std::string, int)>{CallMe});
t->Invoke(5);
t->Detach(handle);
delete t;
}
</code></pre>
<p>Note: The bind macros are used to simplify binding of methods that require some kind of instance so call. Assuming a class s exposes an event e that requires 3 parameter and callMe (defined inside receiver) satisfies this, one may use it like that:</p>
<pre><code>auto handle = s->e->Attach(BIND_3(receiver::callMe, r));
</code></pre>
<p>Edit: Here is an example of how to avoid the BIND_X macros (and that is why i got rid if them)</p>
<pre><code>auto handle = s->e->Attach([r](const std::string& s, int a, int b) {r->callMe(s, a, b);});
</code></pre>
| [] | [
{
"body": "<p>Using <code>std::function</code> you don't ensure signature matching (It work if argument are just convertible). some kind of function_traits can be applied here.</p>\n\n<p>Try to check at compile time that the signature of the given callback match what you expect.</p>\n\n<p>The loop in <code>Invo... | {
"AcceptedAnswerId": "206787",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T13:26:44.877",
"Id": "206723",
"Score": "3",
"Tags": [
"c++",
"event-handling"
],
"Title": "Simple event mechanism"
} | 206723 |
<p>I'm using the <a href="https://github.com/bchavez/Bogus" rel="noreferrer">Bogus</a> library to mock up some data for testing.</p>
<p>This is my main method demonstrating how the faking service should be used:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
IFakerService r = new FakerService();
var dogs = r.Generate<Dog>(10);
var customers = r.Generate<Customer>(10);
var cats = r.Generate<Cat>(10);
}
}
</code></pre>
<p>A Dog class looks like:</p>
<pre><code>public class Dog
{
public string Name { get; set; }
public bool IsGoodBoy => true;
}
</code></pre>
<p>My interface simply defines the only method the service should expose:</p>
<pre><code>public interface IFakerService
{
IEnumerable<T> Generate<T>(int count) where T : class;
}
</code></pre>
<p>And the service itself:</p>
<pre><code>public class FakerService : IFakerService
{
// Can we do better than <Type, object> ?
private Dictionary<Type, object> _fakers;
public FakerService()
{
_fakers = InitialiseFakers();
}
public IEnumerable<T> Generate<T>(int count) where T : class
{
var faker = GetFaker<T>();
return faker.Generate(count);
}
// Types which can be faked are registered here
private Dictionary<Type, object> InitialiseFakers()
{
return new Dictionary<Type, object>()
{
{typeof(Dog), new DogFaker().GetFaker()},
{typeof(Cat), new CatFaker().GetFaker()},
{typeof(Customer), new CustomerFaker().GetFaker()}
};
}
private Faker<T> GetFaker<T>() where T : class
{
if (!_fakers.ContainsKey(typeof(T)))
{
throw new ArgumentException($"Type: {typeof(T).FullName} not registered with FakerService");
}
var faker = (Faker<T>)_fakers[typeof(T)];
return faker;
}
}
</code></pre>
<p>The interface for Faker objects:</p>
<pre><code>public interface IFaker<T> where T : class
{
Faker<T> GetFaker();
}
</code></pre>
<p>And one of the implementations:</p>
<pre><code>public class DogFaker : IFaker<Dog>
{
public Faker<Dog> GetFaker()
{
return new Faker<Dog>()
.RuleFor(dog => dog.Name, f => f.Name.FirstName(Name.Gender.Male))
.RuleFor(dog => dog.IsGoodBoy, f => f.Random.Bool());
}
}
</code></pre>
<p>Overall I'm quite happy with how it looks - the parts that I was wondering if I could improve on are:</p>
<pre><code>private Dictionary<Type, object> _fakers;
...
return new Dictionary<Type, object>()
{
{typeof(Dog), new DogFaker().GetFaker()}
}
...
var faker = (Faker<T>)_fakers[typeof(T)];
</code></pre>
<p>Any advice is appreciated!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:08:58.300",
"Id": "398800",
"Score": "3",
"body": "IsGoodBoy should ALWAYS return true >:("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T15:45:14.770",
"Id": "398818",
"Score": "0",
"... | [
{
"body": "<blockquote>\n<pre><code>public interface IFaker<T> where T : class\n{\n Faker<T> GetFaker();\n}\n</code></pre>\n</blockquote>\n\n<p>I don't think you need this interface and the additional call to <code>GetFaker</code>. Instead you can derive your class from the <code>Faker<T></... | {
"AcceptedAnswerId": "206779",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T13:37:52.350",
"Id": "206724",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"generics",
"interface"
],
"Title": "Service for generating faked objects"
} | 206724 |
<blockquote>
<p><strong>The Problem</strong></p>
<p>Sniffed any good packets lately, dude? Hopefully you haven’t done this illegally, but rest assured that there
are some who have. If you surf the Internet, you have probably visited companies’ net sites where they sell
their products online: you give them your credit card number and they ship you the goods. That’s a
convenient way to shop if you can ensure that your credit card number isn’t being “sniffed” up by wily
hackers and used illicitly.</p>
<p>The Internet is an example of a packet-switched network. This means that information is sent in
discrete groups of bits called packets from computer to computer. For example, when I send email to
someone in the Philippines, my message (at the binary level) is broken up into packets, and routed packet
by packet (not all at once) from computer to computer, ultimately to the recipient’s computer.</p>
<p>“Packet sniffing” refers to writing a program that grabs the individual packets that come your
computer’s way and reads their contents. Now the term “packet sniffing” has obvious unethical
connotations: usually it refers to writing a program that reads packets addressed to computers other than
your own. But the principle is exactly the same when you only intercept those packets that are intended for
you.</p>
<p>Let’s suppose that a network packet consists of three parts: a special start-of-packet bit pattern,the packet content, and a special end-of-packet bit pattern. Suppose that the start- and end-of-packet
pattern are both 1000001 and that the packet content is no more than three consecutive sequences of 7 bits(1’s and 0’s). So, to write a program to “sniff” packets you need only to write a program that scans its
input and “decodes” everything between pairs of 1000001.</p>
<p>For this problem assume that the content of each packet is binary representation of no more than
three ASCII characters, each encoded in 7 “bits” (0’s and 1’s). Your task is to write a program that prints
out the message (in English) that is being transmitted by a sequence of packets.</p>
<p><strong>Sample Input</strong></p>
<p>Take your input from the text file <code>prob4.in</code>. Here’s a sample of its content:
</p>
<pre><code>10000011100010110111111011111000001100000101000011000001
</code></pre>
<p>You are guaranteed two things: (1) the encoding is correct, and (2) only lower case letters and punctuation are encoded in the packet.</p>
<p><strong>Sample Output</strong></p>
<p>Your program should direct its output to the screen. The correct output for the sample input above is:
</p>
<pre><code>boo!
</code></pre>
</blockquote>
<p><strong>packetsniffer.py</strong></p>
<pre><code>with open('prob4.in') as f:
for line in f:
line = line.strip().replace('1000001', '')
print(''.join([chr(int(c, 2)) for c in [line[i:i+7] for i in range(0, len(line), 7)]]))
</code></pre>
<p>Any advice on performance enhancement, solution simplification or that is topical is appreciated!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:42:07.807",
"Id": "398806",
"Score": "0",
"body": "So it cannot happen that '1000001' is generated by two consective asci characters?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:48:17.723",
... | [
{
"body": "<p>Your code looks good, except that you do not really need the <code>c</code>, and hence the nesting, in the list comprehension. You can use <code>line[i:i+7]</code> directly in <code>int</code>, making it a bit shorter:</p>\n\n<pre><code>''.join([chr(int(line[i:i+7], 2)) for i in range(0, len(line)... | {
"AcceptedAnswerId": "206728",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:12:30.373",
"Id": "206726",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Contest Solution: Packet Sniffer"
} | 206726 |
<p>I am building a contact management system. Each contact can relate to the business in one of three ways: client, service provider, and third party. </p>
<p>I have a JSON file containing the relation types and their importance to the business (so I could priorities messages, for example):</p>
<pre><code>{
"Relations": [
{
"Name": "Client",
"Importance": 1
},
{
"Name": "Service Provider",
"Importance": 2
},
{
"Name": "ThirdParty",
"Importance": 3
}
]
}
</code></pre>
<p>I have a method that gets the name of the relation and retrieves a <code>JObject</code> containing the JSON representing this relation, using Json.NET:</p>
<pre><code>private JObject GetRelationJSON(string relationName)
{
string jString = File.ReadAllText("relations.json");
JObject relationsJSON = JsonConvert.DeserializeObject<JObject>(jString);
// I am specifically not sure about this line
return (JObject)(relationsJSON["Relations"].Where(r => ((string)r["Name"]).Equals(relationName)).ToList()[0]);
}
</code></pre>
<p>Note that I am not allowed to deserialize the JSON into POCO classes.</p>
<p>How can I improve this code? Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:48:56.167",
"Id": "398808",
"Score": "1",
"body": "_I am not allowed to deserialize the JSON into POCO classes._ - this is a very strange limitation. Could you explain why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Cre... | [
{
"body": "<p>Not being able to use POCO is tough enough so don't make your life even harder with the line you're asking about. It's much easier to query it with <a href=\"https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html\" rel=\"nofollow noreferrer\"><code>JsonPath</code></a> lik... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T14:45:09.057",
"Id": "206727",
"Score": "2",
"Tags": [
"c#",
"json",
"json.net"
],
"Title": "Getting a JObject by a property value"
} | 206727 |
<h1>Background</h1>
<p>When NumPy is linked against multithreaded implementations of BLAS (like MKL or OpenBLAS), the computationally intensive parts of a program run on multiple cores (sometimes all cores) automatically. </p>
<p>This is bad when:</p>
<ul>
<li>you are sharing resources</li>
<li>you know of a better way to parallelize your program.</li>
</ul>
<p>In these cases it is reasonable to restrict the number of threads used by MKL/OpenBLAS to 1, and parallelize your program manually. </p>
<p>My solution below involves loading the libraries at runtime and calling the corresponding C functions from Python.</p>
<h1>Questions</h1>
<ol>
<li>Are there any best/better practices in solving this problem?</li>
<li>What are the pitfalls of my approach?</li>
<li>Please comment on code quality in general.</li>
</ol>
<h1>Example of use</h1>
<pre><code>import numpy
# this uses however many threads MKL/OpenBLAS uses
result = numpy.linalg.svd(matrix)
# this uses one thread
with single_threaded(numpy):
result = numpy.linalg.svd(matrix)
</code></pre>
<h1>Implementation</h1>
<ol>
<li><p>Imports and definitions</p>
<pre><code>import subprocess
import re
import sys
import os
import glob
import warnings
import ctypes
MKL = 'mkl'
OPENBLAS = 'openblas'
</code></pre></li>
<li><p><strong>Class <code>BLAS</code></strong>, abstracting a BLAS library with methods to get and set the number of threads:</p>
<pre><code>class BLAS:
def __init__(self, cdll, kind):
if kind not in (MKL, OPENBLAS):
raise ValueError(f'kind must be {MKL} or {OPENBLAS}, got {kind} instead.')
self.kind = kind
self.cdll = cdll
if kind == MKL:
self.get_n_threads = cdll.MKL_Get_Max_Threads
self.set_n_threads = cdll.MKL_Set_Num_Threads
else:
self.get_n_threads = cdll.openblas_get_num_threads
self.set_n_threads = cdll.openblas_set_num_threads
</code></pre></li>
<li><p><strong>Function <code>get_blas</code></strong>, returning a <code>BLAS</code> object given an imported NumPy module.</p>
<pre><code>def get_blas(numpy_module):
LDD = 'ldd'
LDD_PATTERN = r'^\t(?P<lib>.*{}.*) => (?P<path>.*) \(0x.*$'
NUMPY_PATH = os.path.join(numpy_module.__path__[0], 'core')
MULTIARRAY_PATH = glob.glob(os.path.join(NUMPY_PATH, 'multiarray.*so'))[0]
ldd_result = subprocess.run(
args=[LDD, MULTIARRAY_PATH],
check=True,
stdout=subprocess.PIPE,
universal_newlines=True
)
output = ldd_result.stdout
if MKL in output:
kind = MKL
elif OPENBLAS in output:
kind = OPENBLAS
else:
return None
pattern = LDD_PATTERN.format(kind)
match = re.search(pattern, output, flags=re.MULTILINE)
if match:
lib = ctypes.CDLL(match.groupdict()['path'])
return BLAS(lib, kind)
else:
return None
</code></pre></li>
<li><p><strong>Context manager <code>single_threaded</code></strong>, that takes an imported NumPy module, sets number of threads to 1 on enter, resets to previous value on exit.</p>
<pre><code>class single_threaded:
def __init__(self, numpy_module):
self.blas = get_blas(numpy_module)
def __enter__(self):
if self.blas is not None:
self.old_n_threads = self.blas.get_n_threads()
self.blas.set_n_threads(1)
else:
warnings.warn(
'No MKL/OpenBLAS found, assuming NumPy is single-threaded.'
)
def __exit__(self, *args):
if self.blas is not None:
self.blas.set_n_threads(self.old_n_threads)
if self.blas.get_n_threads() != self.old_n_threads:
message = (
f'Failed to reset {self.blas.kind} '
f'to {self.old_n_threads} threads (previous value).'
)
raise RuntimeError(message)
</code></pre></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T16:57:54.400",
"Id": "398827",
"Score": "1",
"body": "Could you add the definitions for `MKL` and `OPENBLAS`, please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T17:35:10.843",
"Id": "398831",... | [
{
"body": "<blockquote>\n <p>What are the pitfalls of my approach?</p>\n</blockquote>\n\n<p>Calling the functions setting the maximum number of threads to use change a global state inside the respective libraries which makes the decorator not thread safe. When you use the numpy functions from several different... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T16:50:33.910",
"Id": "206736",
"Score": "4",
"Tags": [
"python",
"multithreading",
"numpy"
],
"Title": "Better way to set number of threads used by NumPy"
} | 206736 |
<p>I am trying to write a program that will read the highest and lowest voltage along with its associated amp and time. I am able to find the max, but I am getting all zeros for the minimum value. I need help. Please and thank you.</p>
<p>Sample of txt file:</p>
<pre><code>Time Volt Ampere
0.0001 9.77667 0.147408
0.00015 9.76583 0.147525
0.0002 9.76833 0.147692
0.00025 9.75833 0.147442
0.0003 9.76833 0.147192
0.00035 9.78167 0.1473
0.0004 9.76667 0.147317
0.00045 9.765 0.14715
0.0005 9.75667 0.147
0.00055 9.765 0.14695
0.0006 9.77 0.1471
0.00065 9.7675 0.147417
0.0007 9.7725 0.147417
0.00075 9.755 0.14735
0.0008 9.765 0.147725
0.00085 9.76583 0.147783
</code></pre>
<p>Expected Min Output:</p>
<pre><code>Time = 0.00075 Volt = 9.755 Ampere = 0.14735
</code></pre>
<p>Expected Max Output:</p>
<pre><code>Time= 0.00035 Volt = 9.78167 Ampere = 0.1473
</code></pre>
<hr>
<pre><code>int main(void)
{
//Declare Variables
string a, b, c;
double time, volt, ampere;
double maxVolt = 0, maxTime, maxAmpere;
double minVolt = 10, minTime, minAmpere;
//Read from the Volts.txt file
ifstream myFile("D:\\tabit\\Documents\\Volts.txt");
//Check if the file can be opened
if (myFile.is_open())
{
while (myFile >> a >> b >> c)
{
time = atof(a.c_str());
volt = atof(b.c_str());
ampere = atof(c.c_str());
if (volt >= maxVolt)
{
maxTime = time;
maxVolt = volt;
maxAmpere = ampere;
}
if (volt < minVolt)
{
minTime = time;
minVolt = volt;
minAmpere = ampere;
}
}
//Close the file
myFile.close();
}
//Give error message if the file cannot be opened
else return(1);
//Display the Maximum results
cout << "Max Volt: " << maxVolt << endl;
cout << "Max Time: " << maxTime << endl;
cout << "Max Ampere: " << maxAmpere << endl;
//Display the Minimum results
cout << "Min Volt: " << minVolt << endl;
cout << "Min Time: " << minTime << endl;
cout << "Min Ampere: " << minAmpere << endl;
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>The value of <code>atof(\"Volt\")</code> is zero. The corresponding values of <code>atof(\"Time\")</code> and <code>atof(\"Ampere\")</code> are also zero, which gives you the minimum values of zero you observed. </p>\n\n<p>You need to skip the first line of the file. Adding this before the whil... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T18:49:41.693",
"Id": "206744",
"Score": "2",
"Tags": [
"c++",
"beginner"
],
"Title": "Reading Min and Max From Text File"
} | 206744 |
<p>I made a small <a href="https://en.wikipedia.org/wiki/Stack-oriented_programming" rel="nofollow noreferrer">stack-oriented language</a> in Rust. It tries to run anything it is given. To elaborate: Division by zero gives zero. If there is nothing on the stack and a request is made that involves popping off the stack, instead of just throwing an error, it acts as if <code>0.0</code> is always available on the stack. Currently it just supports a few small basic arithmetical operations, swapping the stack, duplicating the stack, printing and a jump command. It is a smaller version of the <a href="https://github.com/slongfield/simpleStack" rel="nofollow noreferrer">simpleStack</a> language. The tests are currently more like sanity checks. Here is the code:</p>
<h1><code>src/lib.rs</code></h1>
<pre><code>mod words;
/// Given a list of commands, execute the commands.
///
/// # Arguments
///
/// * `tokens` - A slice of tokens to be executed.
/// * `stack` - The stack to keep the current state of the program.
fn execute_program(tokens: &[&str],
stack: &mut Vec<f64>,
output: &mut Vec<f64>) -> Vec<f64> {
// Analogous to the role of a "register" for a Turing machine.
let mut reg: usize = 0;
loop {
let tok = tokens.get(reg);
match tok {
Some(&"+") => words::add(stack),
Some(&"-") => words::sub(stack),
Some(&"*") => words::mul(stack),
Some(&"/") => words::div(stack),
Some(&"dup") => words::dup(stack),
Some(&"swp") => words::swp(stack),
Some(&"jnz") => words::jnz(stack, &mut reg),
Some(&"print") => words::print_float(stack, output),
Some(_) => words::parse_number(tok.unwrap(), stack),
None => break
}
reg += 1;
}
output.to_vec()
}
/// Evaluates a string of code.
///
/// # Arguments
///
/// * `code` - The string of code to be executed.
///
/// *Note* The value returned is the "output" of the code. Output is not done
/// through stdout for easier debugging.
pub fn eval(code: String) -> Vec<f64> {
let tokens: Vec<&str> = code.split(' ').collect();
let mut stack: Vec<f64> = Vec::new();
let mut output: Vec<f64> = Vec::new();
execute_program(tokens.as_slice(), &mut stack, &mut output)
}
</code></pre>
<h1><code>src/words.rs</code></h1>
<pre><code>//! The `word` module contains the verbs and nouns that create a program. Verbs
//! are functions (regardless of airity) and nouns are data.
/// Extracts two values off the top of a stack.
///
/// # Arguments
///
/// * `$stack` - stack to be mutated.
macro_rules! get_ops {
($stack:expr) => {
($stack.pop().unwrap_or(0.0),
$stack.pop().unwrap_or(0.0))
}
}
/// Parses a numerical value to a float.
///
/// # Arguments
///
/// `token` - The value to be converted to a float.
/// `stack` - The stack to push the token onto.
///
/// *Note* - If `parse_number` is **not** given a number, it will still return
/// `0.0`.
#[inline(always)]
pub fn parse_number(token: &str, stack: &mut Vec<f64>) {
let number = token.parse::<f64>().unwrap_or(0.0);
stack.push(number);
}
/// Pops the top two elements off the stack and adds them.
///
/// # Arguments
///
/// * `stack` - The stack to pop from and push onto.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn add(stack: &mut Vec<f64>) {
let (a, b) = get_ops!(stack);
stack.push(a + b);
}
/// Pops the top two elements off the stack and subtracts them.
///
/// # Arguments
///
/// * `stack` - The stack to pop from and push onto.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn sub(stack: &mut Vec<f64>) {
let (a, b) = get_ops!(stack);
stack.push(a - b);
}
/// Pops the top two elements off the stack and multiplies them.
///
/// # Arguments
///
/// * `stack` - The stack to pop from and push onto.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn mul(stack: &mut Vec<f64>) {
let (a, b) = get_ops!(stack);
stack.push(a * b);
}
/// Pops the top two elements off the stack and divides them.
///
/// # Arguments
///
/// * `stack` - The stack to pop from and push onto.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used. If division by `0.0` occurs, then a value of `0.0` pushed
/// to `stack` instead.
#[inline(always)]
pub fn div(stack: &mut Vec<f64>) {
let (a, b) = get_ops!(stack);
if b == 0.0 {
stack.push(0.0);
} else {
stack.push(a / b);
}
}
/// Pops the top element off the stack and pushes two copies of it on the stack.
///
/// # Arguments
///
/// * `stack` - The stack to pop from and push onto.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used, thus `0.0` is pushed on to the stack twice.
#[inline(always)]
pub fn dup(stack: &mut Vec<f64>) {
let to_dup = stack.pop().unwrap_or(0.0);
stack.push(to_dup);
stack.push(to_dup);
}
/// Pops the top two elements off the stack and swaps their values.
///
/// # Arguments
///
/// * `stack` - The stack to pop from and push onto.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn swp(stack: &mut Vec<f64>) {
let (first, second) = get_ops!(stack);
stack.push(second);
stack.push(first);
}
/// Pops off two values off the stack. If the first value is not zero, take the
/// value of the second value and jump to that location in code.
///
/// # Arguments
///
/// * `reg` - The the current location of the register.
/// * `stack` - The stack to pop from and push onto.
///
#[inline(always)]
pub fn jnz(stack: &mut Vec<f64>, reg: &mut usize) {
let (cond, jump) = get_ops!(stack);
if cond != 0.0 {
*reg = jump as usize;
}
}
/// Prints the top value of a particular stack.
///
/// # Arguments
///
/// * `stack` - The stack to pop from.
/// * `output` - The output vector to push onto.
///
/// *Note* - Does not "print" to stdout, instead it prints to the `output` par-
/// ameter. This is for better debugging and test.
#[inline(always)]
pub fn print_float(stack: &mut Vec<f64>, output: &mut Vec<f64>) {
output.push(stack.pop().unwrap_or(0.0))
}
</code></pre>
<h1><code>src/bin/imastack.rs</code></h1>
<pre><code>extern crate imastack;
use std::io;
use std::io::Write;
/// Simple REPL for the imastack langauge.
fn main() {
loop {
let mut code = String::new();
print!("> ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut code)
.expect("Failed to read line");
let output = imastack::eval(code.trim().to_string());
for num in output {
print!("{} ", num);
}
println!()
}
}
</code></pre>
<h1><code>Cargo.toml</code></h1>
<pre><code>[package]
name = "imastack"
version = "0.1.0"
authors = ["Christopher Sumnicht <csumnicht@berkeley.edu>"]
</code></pre>
<h1><code>tests/integration_test.rs</code></h1>
<pre><code>extern crate imastack;
#[test]
fn basic_add() {
assert_eq!(
imastack::eval("1 2 + print".to_string()),
vec![3.0]);
}
#[test]
fn basic_sub() {
assert_eq!(
imastack::eval("1 2 - print".to_string()),
vec![1.0]);
}
#[test]
fn basic_mul() {
assert_eq!(
imastack::eval("3 3 * print".to_string()),
vec![9.0]);
}
#[test]
fn basic_div() {
assert_eq!(
imastack::eval("3 6 / print".to_string()),
vec![2.0]);
}
#[test]
fn div_by_zero_is_zero() {
assert_eq!(
imastack::eval("0 1 / print".to_string()),
vec![0.0]);
}
#[test]
fn basic_swp() {
assert_eq!(
imastack::eval("1 2 swp print print".to_string()),
vec![2.0, 1.0]);
}
#[test]
fn basic_dup() {
assert_eq!(
imastack::eval("1 dup print print".to_string()),
vec![1.0, 1.0]);
}
#[test]
fn basic_jnz() {
assert_eq!(
imastack::eval("1 4 jnz 0 1 print".to_string()),
vec![1.0]);
}
</code></pre>
<p>Here is the <a href="https://github.com/thyrgle/imastack" rel="nofollow noreferrer">Cargo project on Github</a>. A basic REPL can be launched with <code>cargo run --bin imastack</code>.</p>
| [] | [
{
"body": "<h2>Fundamental design</h2>\n\n<p>First I'm going to address some issues I see with the design of your interpreter. These aren't problems with the code per say, just things I suggest to assist in maintainability, extensibility, etc.</p>\n\n<h3>Stack design</h3>\n\n<p>Right now, you're using a <code>V... | {
"AcceptedAnswerId": "206817",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T18:52:23.943",
"Id": "206745",
"Score": "2",
"Tags": [
"rust",
"interpreter"
],
"Title": "Small stack based language in Rust"
} | 206745 |
<p>I've made registry/factory class for C++ so I can instantiate different classes at runtime based on some kind of key. My design is partially based on this blog post: <a href="http://www.nirfriedman.com/2018/04/29/unforgettable-factory/" rel="nofollow noreferrer">http://www.nirfriedman.com/2018/04/29/unforgettable-factory/</a> . So you might read it first to get a broad overview. In short: Instead of manually adding derived classes to a big switch statement in some factory function, your base class only needs to inherit from <code>registry_t<my_base_class_t, my_key_type_t></code>. Registrars just need to inherit from <code>my_base_class_t::register_const<my_derived_class_t, my_identifier></code> or <code>my_base_class_t::register_dyn<my_derived_class_t></code>. All registration is done automatically without any additional code. It supports passing parameters to the constructors and it's possible to change the returned ptr type (default: <code>unique_ptr</code>).</p>
<pre><code>#include <memory>
#include <unordered_map>
template<typename t, t value>
struct dummy_user_t {};
// t_derived: class inheriting from registry_t
// t_key: the type that should be passed as key
// t_ptr: the type of ptr that should be returned to the user
// t_args: constructor signature
template<typename t_derived, typename t_key, typename t_ptr = std::unique_ptr<t_derived>, typename... t_args>
struct registry_t
{
using factory_type = t_derived*(*)(t_args&&... args);
friend t_derived;
private:
registry_t() = default;
struct shared_t
{
template<typename t, auto>
friend struct register_const;
friend registry_t;
private:
// avoid undefined static member initialization order
static std::unordered_map<t_key, factory_type>& get_factories()
{
static std::unordered_map<t_key, factory_type> s_factories;
return s_factories;
}
};
protected:
using identifier_t = t_key;
public:
template<typename t, auto>
friend struct register_const;
[[nodiscard]]
static t_ptr make(const t_key& key, t_args&&... args)
{
static_assert(std::is_base_of_v<registry_t<t_derived, t_key, t_ptr, t_args...>, t_derived>,
"Trying to instantiate derived class of non-registry");
// return instantiated object as requested ptr type (default std::unique_ptr)
return t_ptr {shared_t::get_factories().at(key)(std::forward<t_args>(args)...)};
}
public:
template<typename t_registrar, auto key>
struct register_const : t_derived
{
friend t_registrar;
private:
using t_derived::t_derived;
static const bool s_registered;
// "use" s_registered so it is actually instantiated
using value_user_t = dummy_user_t<const bool&, s_registered>;
struct private_t
{
friend register_const;
private:
static bool register_class() // associate factory function with corresponding key
{
shared_t::get_factories()[t_key {key}] = [](t_args&&... args) -> t_derived*
{
return new t_registrar(std::forward<t_args>(args)...);
};
return true;
}
};
};
template<typename t_registrar>
struct register_dyn : t_derived
{
friend t_registrar;
private:
using t_derived::t_derived;
static const bool s_registered;
using value_user_t = dummy_user_t<const bool&, s_registered>;
struct private_t
{
friend register_dyn;
private:
static bool register_class()
{
shared_t::get_factories()[t_registrar::get_key()] = [](t_args&&... args) -> t_derived*
{
return new t_registrar(std::forward<t_args>(args)...);
};
return true;
}
};
};
};
// initialize s_registered with register_class() so it's called at program startup
template<typename t_derived, typename t_key, typename t_ptr, typename... t_args>
template<typename t_registrar, auto key>
const bool registry_t<t_derived, t_key, t_ptr, t_args...>::register_const<t_registrar, key>::s_registered
{registry_t<t_derived, t_key, t_ptr, t_args...>::register_const<t_registrar, key>::private_t::register_class()};
template<typename t_derived, typename t_key, typename t_ptr, typename... t_args>
template<typename t_registrar>
const bool registry_t<t_derived, t_key, t_ptr, t_args...>::register_dyn<t_registrar>::s_registered
{registry_t<t_derived, t_key, t_ptr, t_args...>::register_dyn<t_registrar>::private_t::register_class()};
</code></pre>
<p>And here's a small example:</p>
<pre><code>#include <iostream>
// paste implementation here
enum class animal_type
{
pig = 1,
cow
};
// make animal_t a registry with key type unsigned and no constructor arguments:
struct animal_t : registry_t<animal_t, animal_type>
{
virtual ~animal_t() = default;
virtual void print_name() const = 0;
};
// pig_t inherits from animal_t and is assigned the key 1
struct pig_t : animal_t::register_const<pig_t, animal_type::pig>
{
void print_name() const override
{
std::cout << "pig\n";
}
};
// cow_t also inherits from animal_t but the key can be determined at runtime
struct cow_t : animal_t::register_dyn<cow_t>
{
static identifier_t get_key()
{
return animal_type::cow;
}
void print_name() const override
{
std::cout << "cow\n";
}
};
int main()
{
// create a pig_t
std::unique_ptr<animal_t> x {animal_t::make(animal_type::pig)};
// create a cow_t
auto y {animal_t::make(animal_type::cow)};
// correct objects have been returned
x->print_name();
y->print_name();
return 0;
}
</code></pre>
<p>Since this is quite a big chunk of code here's already a small FAQ for questions that are very likely to be asked:</p>
<p><strong>Why make everything private and declare <code>t_derived</code> as friend? Why not use protected?</strong></p>
<p><code>registry_t</code> relies on the CRT Pattern. The private constructor guarantees that only the correct class can inherit from it: </p>
<p><code>struct my_class : registry_t<my_other_class, int> {}; // <- Error</code></p>
<p><strong>What are <code>shared_t</code> and <code>private_t</code> for?</strong></p>
<p>The ultimate drawback of the trick mentioned above is that all private members bubble up to the inheriting class. Putting these in nested classes prevents that.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T16:50:29.970",
"Id": "398959",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>Your code compile on GCC but not on Clang, he don't like (as me) these few lines :</p>\n\n<pre><code>template<typename t_derived, typename t_key, typename t_ptr, typename... t_args>\ntemplate<typename t_registrar, auto key>\nconst bool registry_t<t_derived, t_key, t_ptr, t_args...&g... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T19:33:06.147",
"Id": "206748",
"Score": "2",
"Tags": [
"c++",
"inheritance",
"template-meta-programming",
"c++17"
],
"Title": "Boilerplate free registry/factory class for C++"
} | 206748 |
<p>I'm making a simple 2D game engine, and to make collision detection more effective I tried making a QuadTree class. I don't know if this will work, but that's not that important. You don't have to waste Your time testing it, but I would like to know if this is an efficient design in terms of logic, especially the update() method altough I made it so this method is only called when at least one of the objects is moved.</p>
<p>The classes Handler, CollideableObject and GameObject are not necessary for this class, but I put them here for context's sake.</p>
<p>I'm happy to hear any oppinion and see any modification, so feel free to use this code and / or modify it in any way.</p>
<p>Sorry if my english description and my code is hard to understand, I'm still a beginner.</p>
<p>The code:</p>
<pre><code>import java.awt.Rectangle;
import java.util.LinkedList;
/**
*
* This class is not independent, the minimum requirements to use it are the classes {@link Handler}, {@link GameObject} and {@link CollideableObject}.
* <br> <br>
* This class is optional, and is only adviced to use when the amount of collision detections reach an inefficient number.
* The class increases performacne by placing each object in the parameter handler by sorting them into a hierachical system in wich specific nodes can hold an added amount of objects.
* These nodes automatically split if the amount reaches the chosen amount.
* <br> <br>
* Keep in mind that this class supports objects with 2D qualities
*
* @see {@link Handler}, {@link GameObject}, {@link CollideableObject}, {@link ObservableList}
* @version 1.0
* @author Kristóf Bácskai
*
*/
public class QuadTree {
private class QuadTreeNode extends QuadTree {
private final QuadTree parent;
public QuadTreeNode(QuadTree parent, int objectCap, double x, double y) {
super(parent.getHandler(), objectCap, x, y, parent.getWidth() / 2, parent.getHeight() / 2);
this.parent = parent;
}
public final QuadTree getParent() {
return parent;
}
}
private final Handler handler; //This object is not important for this
class, but as you can see in later on it contains a list of all the
objects in the game.
private int objectCap;
private final QuadTreeNode[] nodes;
protected final LinkedList<CollideableObject> objects; // The type
ColliedeableObject has an x, y value and a java.awt.Shape object as a
hitbox
protected final double x, y, width, height;
private boolean isSplit;
/**
* @param handler used as source of processable objects
* @param objectCap the amount of objects in a single node before
splitting it
* @param width of node
* @param height height of node
*
* @author Bácskai Kristóf
*
*/
public QuadTree(Handler handler, int objectCap, double width, double height) {
if (handler.equals(null)) throw new IllegalArgumentException("Handler can't be null");
if (objectCap < 2) throw new IllegalArgumentException("Object cap has to be above 1");
if (width < 1 || height < 1) throw new IllegalArgumentException("Width and height values have to be greater than 1");
this.handler = handler;
this.objectCap = objectCap;
x = 0;
y = 0;
this.width = width;
this.height = height;
isSplit = false;
nodes = new QuadTreeNode[4];
objects = new LinkedList<CollideableObject>();
}
protected QuadTree(Handler handler, int objectCap, double x, double y, double width, double height) {
if (handler.equals(null)) throw new IllegalArgumentException("Handler can't be null");
if (objectCap < 2) throw new IllegalArgumentException("Object cap has to be above 1");
if (width < 1 || height < 1) throw new IllegalArgumentException("Width and height values have to be greater than 1");
this.handler = handler;
this.objectCap = objectCap;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
nodes = new QuadTreeNode[4];
objects = new LinkedList<CollideableObject>();
}
public final void update() {
for (CollideableObject object : objects) if (!handler.getObjects().contains(object)) remove(object);
for (QuadTreeNode node : nodes) {
for (CollideableObject object : objects) {
if (!handler.getObjects().contains(object)) remove(object);
if (node.getObjects().contains(object) && !object.getHitbox().intersects(node.getBounds())) node.remove(object);
}
if (node.getObjects().size() >= node.getObjectCap()) node.split();
if (node.getObjects().size() < node.getObjectCap()) node.mergeChildren();
}
if (!isSplit) return;
for (QuadTreeNode node : nodes) {
node.update();
}
}
public final void insert(CollideableObject object) {
objects.add(object);
for (QuadTreeNode node : nodes) {
if (object.getHitbox().intersects(node.getBounds())) node.insert(object);
}
}
public final void remove(CollideableObject object) {
objects.remove(object);
for (QuadTreeNode node : nodes) {
if (node.objects.remove(object)) node.remove(object);
}
}
protected final void split() {
nodes[0] = new QuadTreeNode(this, getObjectCap(), 0, 0);
nodes[1] = new QuadTreeNode(this, getObjectCap(), getWidth() / 2, 0);
nodes[2] = new QuadTreeNode(this, getObjectCap(), 0, getHeight() / 2);
nodes[3] = new QuadTreeNode(this, getObjectCap(), getWidth() / 2, getHeight() / 2);
for (QuadTreeNode node : nodes) {
for (CollideableObject object : objects)
if (object.getHitbox().intersects(node.getBounds())) node.insert(object);
}
isSplit = true;
}
protected final void mergeChildren() {
for (int i = 0; i < nodes.length; i++) nodes[i] = null;
isSplit = false;
}
public final LinkedList<CollideableObject> getObjects() {
return (LinkedList<CollideableObject>) objects.clone();
}
public final Handler getHandler() {
return handler;
}
public final int getObjectCap() {
return objectCap;
}
public final void setObjectCap(int objectCap) {
this.objectCap = objectCap;
}
public final double getWidth() {
return width;
}
public final double getHeight() {
return height;
}
public Rectangle.Double getBounds() {
return new Rectangle.Double(0, 0, width, height);
}
public boolean isSplit() {
return isSplit;
}
}
</code></pre>
<p>CollideableObject.java:</p>
<pre><code>import static com.bacskai.game_engine.tools.Tools.areIntersecting;
import java.awt.Point;
import java.awt.Shape;
import java.util.LinkedList;
public abstract class CollideableObject extends GameObject {
private Shape hitbox;
public CollideableObject(int x, int y, Shape hitbox) {
super(x, y);
this.hitbox = hitbox;
}
public CollideableObject(int x, int y, int velX, int velY, Shape hitbox) {
super(x, y, velX, velY);
this.hitbox = hitbox;
}
public final void basicTick() {
super.basicTick();
if (checkCollisions()) eventsInLastTick.add(ObjectEvent.Collided);
}
public abstract void collide(CollideableObject objects);
protected boolean checkCollisions() {
boolean collided = false;
LinkedList<CollideableObject> likelyCollisions = new LinkedList<CollideableObject>();
likelyCollisions.remove(this);
for (CollideableObject object : likelyCollisions) {
if (areIntersecting(object.getHitbox(), getHitbox())) {
/*
The areIntersecting(Shape hitbox1, Shape hitbox2) method:
public static boolean areIntersecting(Shape shape, Shape shape2) {
Area area = new Area(shape);
area.intersect(new Area(shape2));
return !area.isEmpty();
}
*/
collide(object);
collided = true;
}
}
return collided;
}
public Point getLocation() {
return new Point(getX(), getY());
}
public Shape getHitbox() {
return hitbox;
}
public final void setHitbox(Shape value) {
hitbox = value;
}
}
</code></pre>
<p>GameObject.java:</p>
<pre><code>import java.awt.Graphics;
import java.util.LinkedList;
public abstract class GameObject {
private Handler handler;
private int x, y, velX, velY;
protected final LinkedList<ObjectEvent> eventsInLastTick;
public GameObject(int x, int y) {
this.x = x;
this.y = y;
eventsInLastTick = new LinkedList<ObjectEvent>();
}
public GameObject(int x, int y, int velX, int velY) {
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
eventsInLastTick = new LinkedList<ObjectEvent>();
}
protected void basicTick() {
x += velX;
y += velY;
if (velX != 0 || velY != 0) eventsInLastTick.add(ObjectEvent.Moved);
}
public abstract void tick();
public void render(Graphics g) {}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}
public final LinkedList<ObjectEvent> getEventsInLastTick() {
return eventsInLastTick;
}
protected final void clearEvents() {
eventsInLastTick.clear();
}
}
</code></pre>
<p>Handler.java:</p>
<pre><code>import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
public abstract class Handler {
private final LinkedList<GameObject> objects;
private QuadTree quadTree;
public Handler() {
objects = new LinkedList<GameObject>();
}
public Handler(QuadTree quadTree) {
objects = new LinkedList<GameObject>();
this.quadTree = quadTree;
}
public abstract void handleEvent(GameObject object, ObjectEvent events);
private final void handleEvents(GameObject object) {
for (ObjectEvent event : object.getEventsInLastTick()) {
if (object.getClass().isInstance(event.getObjectType())) handleEvent(object, event);
else throw new ClassCastException("Event" + event.name() + " is undefinded for the type " + object.getClass());
}
}
public final void tickAll() {
for (GameObject object : objects) {
object.tick();
handleEvents(object);
object.clearEvents();
}
}
public final void renderAll(Graphics g) {
for (GameObject object : objects) {
object.render(g);
}
}
public final BufferedImage renderAll(BufferedImage image) {
BufferedImage dest = image;
Graphics g = dest.getGraphics();
for (GameObject object : objects) {
object.render(g);
}
g.dispose();
return dest;
}
public final void addObject(GameObject object) {
if (objects.contains(object)) throw new IllegalArgumentException("This object is already added to this handler");
object.setHandler(this);
objects.add(object);
if (!quadTree.equals(null) && object instanceof CollideableObject) quadTree.insert((CollideableObject) object);
}
public final void removeObject(GameObject object) {
object.setHandler(null);
objects.remove(object);
if (!quadTree.equals(null) && object instanceof CollideableObject) quadTree.remove((CollideableObject) object);
}
public final LinkedList<GameObject> getObjects() {
return (LinkedList<GameObject>) objects.clone();
}
public final QuadTree getQuadTree() {
return quadTree;
}
public final void setQuadTree(QuadTree quadTree) {
if (!(quadTree.equals(null) && quadTree.getHandler().equals(this))) throw new IllegalArgumentException("The parameter QuadTree must have it's handler set to this");
this.quadTree = quadTree;
}
}
</code></pre>
<p>ObjectEvent.java:</p>
<pre><code>public enum ObjectEvent {
Moved(GameObject.class),
Collided(CollideableObject.class);
private Class<?> objType;
private ObjectEvent(Class<?> objType) {
this.objType = objType;
}
public Class<?> getObjectType() {
return objType;
}
}
</code></pre>
<p>Thanks for Your time!</p>
| [] | [
{
"body": "<p>Something I would immediately recommend from looking at your code is that you should not put random whitespace in your code. Whenever you space out random parts, you should ensure you do so with good reason - such as splitting up various logical parts of your codebase.</p>\n\n<p>Also, you want to ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T19:46:13.277",
"Id": "206750",
"Score": "0",
"Tags": [
"java",
"game",
"collision"
],
"Title": "Self Updtating QuadTree"
} | 206750 |
<p>I was wondering if the following code could be altered to speed up the scraping process. I know xrp has many transactions, but it takes an hour to go through half a day of transactions (at the busiest times, 2016-2018). My thinking is that the <code>try</code>, <code>except</code> statements are slowing it down but I am not sure. I would prefer to go through at least a week every hour. </p>
<p>The <code>if</code> and <code>else</code> statements perform important filtering; that behavior needs to be preserved.</p>
<pre><code>def get_data(last_date): #Date has to be inputted like so: "2018-08-03"
import requests
import json
import os
import time
os.chdir("") #Enter in directory
headers = "TransactionType,Ledger,Tx,TimeStamp,ToAddress,FromAddress,Amount,Currency\n"
f = open("data.csv","w")
f.write(headers)
success = False
marker = ""
counter = 1
while success == False:
try:
r = requests.get("https://data.ripple.com/v2/transactions?end=" + last_date + "&descending=true" + "&limit=100" + marker)
counter += 1
page = r.text
jsonPg = json.loads(page)
transactions = jsonPg["transactions"]
print(transactions[0]["date"])
for item in transactions:
type_of = item["tx"]["TransactionType"]
tx = item["hash"]
ledger = item["ledger_index"]
timestamp = item["date"]
if type_of == "Payment" and item["meta"]["TransactionResult"] == "tesSUCCESS":
if "RippleState" not in str(item):
to_address = item["tx"]["Destination"]
from_address = item["tx"]["Account"]
try:
amount = float(item["meta"]["delivered_amount"])/1000000.0
currency = "XRP"
except:
amount = item["meta"]["delivered_amount"]["value"]
currency = item["meta"]["delivered_amount"]["currency"]
f.write(type_of + "," + str(ledger) + "," + tx + "," + timestamp + "," + to_address + "," +
from_address + "," + str(amount) + "," + currency + "\n")
elif "RippleState" in str(item):
meta = item["meta"]["AffectedNodes"]
meta = [i for i in meta if "DeletedNode" not in i]
meta = [i for i in meta if "DirectoryNode" not in str(i)]
meta = [i for i in meta if "Offer" not in str(i)]
for p in meta:
if "RippleState" in str(p):
try:
amount = float(p["ModifiedNode"]["FinalFields"]["Balance"]["value"]) - float(p["ModifiedNode"]["PreviousFields"]["Balance"]["value"])
currency = p["ModifiedNode"]["FinalFields"]["Balance"]["currency"]
if amount > 0:
to_address = p["ModifiedNode"]["FinalFields"]["LowLimit"]["issuer"]
from_address = p["ModifiedNode"]["FinalFields"]["HighLimit"]["issuer"]
else:
to_address = p["ModifiedNode"]["FinalFields"]["HighLimit"]["issuer"]
from_address = p["ModifiedNode"]["FinalFields"]["LowLimit"]["issuer"]
except:
amount = float(p["CreatedNode"]["NewFields"]["Balance"]["value"])
currency = p["CreatedNode"]["NewFields"]["Balance"]["currency"]
if amount > 0:
to_address = p["CreatedNode"]["NewFields"]["LowLimit"]["issuer"]
from_address = p["CreatedNode"]["NewFields"]["HighLimit"]["issuer"]
else:
to_address = p["CreatedNode"]["NewFields"]["HighLimit"]["issuer"]
from_address = p["CreatedNode"]["NewFields"]["LowLimit"]["issuer"]
elif "RippleState" not in str(p) and "FinalFields" in str(p) and "PreviousFields" in str(p):
try:
amount = (float(p["ModifiedNode"]["FinalFields"]["Balance"]) - float(p["ModifiedNode"]["PreviousFields"]["Balance"]))/1000000.0
currency = "XRP"
if amount > 0:
to_address = p["ModifiedNode"]["FinalFields"]["Account"]
from_address = "NEED TO ADD!!"
else:
to_address = "NEED TO ADD!!"
from_address = p["ModifiedNode"]["FinalFields"]["Account"]
except:
continue
else:
continue
f.write(type_of + "," + str(ledger) + "," + tx + "," + timestamp + "," + to_address + "," +
from_address + "," + str(amount) + "," + currency + "\n")
else:
continue
elif type_of == "OfferCreate" and item["meta"]["TransactionResult"] == "tesSUCCESS":
if "RippleState" in str(item) and len(item["meta"]["AffectedNodes"]) >= 5:
#print(tx)
metaT = item["meta"]["AffectedNodes"]
metaT = [i for i in metaT if "DeletedNode" not in i]
metaT = [i for i in metaT if "DirectoryNode" not in str(i)]
metaT = [i for i in metaT if "Offer" not in str(i)]
for q in metaT:
if "RippleState" in str(q):
try:
amount = float(q["ModifiedNode"]["FinalFields"]["Balance"]["value"]) - float(q["ModifiedNode"]["PreviousFields"]["Balance"]["value"])
currency = q["ModifiedNode"]["FinalFields"]["Balance"]["currency"]
if amount > 0:
#print(tx)
to_address = q["ModifiedNode"]["FinalFields"]["LowLimit"]["issuer"]
from_address = q["ModifiedNode"]["FinalFields"]["HighLimit"]["issuer"]
else:
to_address = q["ModifiedNode"]["FinalFields"]["HighLimit"]["issuer"]
from_address = q["ModifiedNode"]["FinalFields"]["LowLimit"]["issuer"]
except:
amount = float(q["CreatedNode"]["NewFields"]["Balance"]["value"])
currency = q["CreatedNode"]["NewFields"]["Balance"]["currency"]
if amount > 0:
to_address = q["CreatedNode"]["NewFields"]["LowLimit"]["issuer"]
from_address = q["CreatedNode"]["NewFields"]["HighLimit"]["issuer"]
else:
to_address = q["CreatedNode"]["NewFields"]["HighLimit"]["issuer"]
from_address = q["CreatedNode"]["NewFields"]["LowLimit"]["issuer"]
elif "RippleState" not in str(q) and "PreviousFields" in str(q) and "FinalFields" in str(q):
try:
amount = (float(q["ModifiedNode"]["FinalFields"]["Balance"]) - float(q["ModifiedNode"]["PreviousFields"]["Balance"]))/1000000.0
currency = "XRP"
if amount > 0:
to_address = q["ModifiedNode"]["FinalFields"]["Account"]
from_address = "NEED TO ADD!!"
else:
to_address = "NEED TO ADD!!"
from_address = q["ModifiedNode"]["FinalFields"]["Account"]
except:
continue
else:
continue
f.write(type_of + "," + str(ledger) + "," + tx + "," + timestamp + "," + to_address + "," +
from_address + "," + str(amount) + "," + currency + "\n")
else:
continue
else:
continue
if page.find("marker") == -1:
success = True
#print("YES!")
else:
marker = "&marker=" + jsonPg["marker"]
#print("marker
except:
print("Slept!")
time.sleep(3)
print("Worked!")
f.close()
get_data("2016-05-01")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T17:13:09.833",
"Id": "398964",
"Score": "1",
"body": "Can you explain the `time.sleep(3)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T19:22:12.453",
"Id": "398978",
"Score": "1",
"bod... | [
{
"body": "<p>Creating a requests session instead of using the requests.get should speed it up, example, instead of using:</p>\n\n<pre><code>while ...:\n r = requests.get('http://...')\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>s = requests.Session()\nwhile ...:\n r = s.get('http://...')\n</code></pre>\n... | {
"AcceptedAnswerId": "206752",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T19:51:06.923",
"Id": "206751",
"Score": "0",
"Tags": [
"python",
"performance",
"json",
"api",
"pagination"
],
"Title": "Web scraping and speeding up performance"
} | 206751 |
<p>I am a python beginner and I wrote a program that compares between the binary search method for finding a number and the linear one. However, when I run it It does not function properly and would stop when I enter an input and print nothing. Please, may someone explain what is wrong with it? THANK YOU SO MUCH </p>
<pre><code>import random
import time
n=1000000
start = time.time()
lst=[random.randint(0,100*n) for i in range(n)]
start=time.time()
def linear():
for c in lst:
if c==e:
return "found"
else:
return "not found"
end = time.time() # record end time
print('time to sort:', (end-start)/100, 'seconds')
print(linear())
lst=[random.randint(0,100*n) for i in range(n)]
start=time.time()
def binary(e,lst):
Ubound=len(lst)-1
Lbound=0
mid=(Ubound+Lbound)//2
found=True
lst.sort()
while found and Lbound<=Ubound:
if e==lst[mid] :
found=True
return found
elif lst[mid]<e:
Lbound=mid+1
else:
Ubound=mid-1
return found
end=time.time()
print('time to sort:', (end-start)/100, 'seconds')
e=int(input("what are you looking for?"))
if binary(e,lst):`enter code here`
print("item has been found")
else:
print("item has not been found")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T20:40:15.663",
"Id": "398841",
"Score": "0",
"body": "This question would be better served on [Stack Overflow](https://stackoverflow.com/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T21:03:21.533"... | [
{
"body": "<p>Take a look at this portion of your code:</p>\n\n<pre><code>found=True\n lst.sort()\n\n while found and Lbound<=Ubound:\n</code></pre>\n\n<p>You set found to true before checking if it exists. Here you should set it to false before you run the loop.</p>\n\n<p>Also, please keep in mind, as menti... | {
"AcceptedAnswerId": "206767",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T20:37:07.967",
"Id": "206753",
"Score": "-1",
"Tags": [
"python"
],
"Title": "comparing between binary search method and linear search"
} | 206753 |
<p><a href="http://www.cplusplus.com/reference/string/stoi/" rel="nofollow noreferrer"><code>std::stoi</code></a> may throw exceptions so it needs to be surrounded by try/catch.</p>
<p>In applications where <code>std::stoi</code> may be used frequently, it could be useful to have a wrapper.</p>
<p>Is this good practice?</p>
<pre><code>int _stoi(std::string str, int* p_value) {
// wrapping std::stoi because it may throw an exception
try {
*p_value = std::stoi(str);
return 0;
}
catch (const std::invalid_argument& ia) {
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;
}
catch (const std::out_of_range& oor) {
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;
}
catch (const std::exception& e)
{
//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T22:26:30.457",
"Id": "398846",
"Score": "2",
"body": "[std::strtol](http://www.cplusplus.com/reference/cstdlib/strtol/) addresses the problem in a much cleaner way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate":... | [
{
"body": "<p>This wrapper effectively removes some of the available functionality from <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stol\" rel=\"nofollow noreferrer\"><code>std::stoi()</code></a> because its signature is</p>\n\n<pre><code>int stoi(const std::string& str, std::size_t* pos... | {
"AcceptedAnswerId": "206758",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T20:42:13.517",
"Id": "206754",
"Score": "5",
"Tags": [
"c++",
"error-handling",
"integer"
],
"Title": "An exception-safe wrapper for std::stoi"
} | 206754 |
<p>To give a bit of a background, I'm organizing a small session about <strong>reinforcement-learning</strong>, specifically <code>Q-learning</code>, to a group of high school students in the following month to give them a glance into the kind of opportunities waiting for them to tackle in this amazing field of AI and Computer Science. Just a small stint to motivate them, to be honest :)</p>
<p>I hence seek the guidance of this wonderful community (that is you!) to judge the understandability and the readability of my code which I had drafted some time ago. The code which follows is predominantly written in basic JavaScript and since it's targeted for a set of audience who aren't completely comfortable with most of the modern paradigms, I would like to keep it as simple as possible. I've tried to document the code heavily covering potentially all important cases in layman terms to make it more clear. You can see the effect of the code in action here: <a href="https://nileshsah.github.io/reinforcement-learning-flappybird/" rel="nofollow noreferrer">https://nileshsah.github.io/reinforcement-learning-flappybird/</a> <em>(you just need to tap the game to start and then leave it alone for the computer shall learn to play it by its own)</em>. The complete repository for the game and the algorithm can be found <a href="https://github.com/nileshsah/reinforcement-learning-flappybird" rel="nofollow noreferrer">here</a>.</p>
<p>I do realize that it's a bit too much of a code to review (around 300 lines) but if in the process you get to learn something new then oh well, I guess it'll be a win-win situation for both of us :) Please take your time and share your thoughts regarding "<em>which part of the code is hard to comprehend and how I can improve it</em>".</p>
<p>Sharing the code: <a href="https://github.com/nileshsah/reinforcement-learning-flappybird/blob/master/js/brain.js" rel="nofollow noreferrer">https://github.com/nileshsah/reinforcement-learning-flappybird/blob/master/js/brain.js</a></p>
<pre><code>/**
* The file contains solely the Q-learning model for training our flappy bird.
* It takes input from the environment such as the position of the flappy bird,
* the tubes etc and responds back with the appropriate action to take.
*
* Author @nellex
*/
/**
* The Q-table forms the heart of the Q-learning algorithm. Maintained for our
* agent Flappy bird, the table represents the state-action function, i.e. the
* relationship between a set of states (S) and the set of actions (A) =>
* Q[S,A]. For a given state 's' and a given action 'a', Q(s,a) denotes the
* expected reward of doing the action 'a' in the state 's'.
*
* In our learning model, the state of the environment is defined by:
* (1) speedY: The speed of the flappy bird in the Y-axis, i.e. by what rate the
* bird is going up or falling down
* (2) tubeX: The X-coordinate of the next incoming tube, i.e. how far the next
* tube is from the flappy bird
* (3) diffY: We define the ideal position from which the flappy bird should pass
* through to be the very middle of vertical space between the two tubes. The
* parameter 'diffY' denotes the difference between the Y-coordinate of the flappy
* bird to the Y-coordinate of our ideal passage position, i.e. how down below or
* above our flappy bird is from where it should pass from the tube.
*/
var Q_table = {};
/**
* The action set comprises of:
* (1) Stay: Take no action, and just go with the flow of the gravity
* (2) Jump: Push the flappy bird upwards
*/
var actionSet = {
STAY : 0,
JUMP : 1
};
/**
* Defining the parameters for our Q-learning model,
* (1) Learning rate, alpha: Ranging between [0,1], it determines how quickly should
* the flappy bird override it's old learned actions with the new ones for the
* corresponding state
* (2) Discount factor, gamma: Used for determining the importance of future reward.
*
* In our game, if the flappy bird fails to clear the tube, the action which it
* took recently previously will be penalized more than the action which it took 10
* steps ago. This is because it's the recent actions which has a more influence on
* the success of the bird.
*/
var gamma = 0.8; // Discounted rewards
var alpha = 0.1; // Learning rate
// Frame buffer for mainting the state-action pairs in the current episode
var frameBuffer = [];
// Number of frames in the current frame buffer
var episodeFrameCount = 0;
// Flag to determine if the current episode is still ongoing or is completed by
// maintaing an index to the next incoming tube
var targetTubeIndex;
// The tube which the bird must clear next
var targetTube;
// To maintain the count on the number of trials
var trials = 0;
/**
* Function to lookup the estimated Q-value (reward) in the Q-table for a given
* state-action pair
* @param {*} state State of the environment as described above
* @param {*} action The action to be taken
*/
function getQ(state, action) {
var config = [ state.diffY, state.speedY, state.tubeX, action ];
if (!(config in Q_table)) {
// If there's no entry in the given Q-table for the given state-action
// pair, return a default reward score as 0
return 0;
}
return Q_table[config];
}
/**
* Function to update the Q-value (reward) entry for the given state-action pair
* @param {*} state The state of the environment
* @param {*} action The action taken for the given state
* @param {*} reward The reward to be awarded for the state-action pair
*/
function setQ(state, action, reward) {
var config = [ state.diffY, state.speedY, state.tubeX, action ];
if (!(config in Q_table)) {
Q_table[config] = 0;
}
Q_table[config] += reward;
}
/**
* Function responsible for selecting the appropriate action corresponding to
* the given state The action which has a higher Q-value for the given state is
* 'generally' executed
* @param {*} state
*/
function getAction(state) {
// Why always follow the rules? Once in a while (1/100000), our flappy bird
// takes a random decision without looking up the Q-table to explore a new
// possibility. This is to help the flappy bird to not get stuck on a single
// path.
var takeRandomDecision = Math.ceil(Math.random() * 100000)%90001;
if (takeRandomDecision == 0) {
console.log("Going random baby!");
// 1 out of 4 times, it'll take a decision to jump
var shouldJump = ((Math.random() * 100 )%4 == 0);
if (shouldJump) {
return actionSet.JUMP;
} else {
return actionSet.STAY;
}
}
// Lookup the Q-table for rewards corresponding to Jump and Stay action for
// the given state
var rewardForStay = getQ(state, actionSet.STAY);
var rewardForJump = getQ(state, actionSet.JUMP);
if (rewardForStay > rewardForJump) {
// If reward for Stay is higher, command the flappy bird to stay
return actionSet.STAY;
} else if (rewardForStay < rewardForJump) {
// If reward for Jump is higher, command the flappy bird to jump
return actionSet.JUMP;
} else {
// This is the case when the reward for both the actions are the same In
// such a case, we determine randomly the action to be taken Generally, the
// probability of jumping is lower as compared to stay to mimic the natural
// scenario We press jump much less occasionally than we let the flappy bird
// fall
var shouldJump = (Math.ceil( Math.random() * 100 )%25 == 0);
if (shouldJump) {
return actionSet.JUMP;
} else {
return actionSet.STAY;
}
}
}
/**
* Function responsible for rewarding the flappy bird according to its
* performance One thing to note here is that we found the behaviour of our
* Flappy Bird to be highly episodic. As soon as your flappy bird clears one
* obstacle, we terminate our episode there and then and reward it postively A
* new episode is then started for the next obstacle i.e. the next tube which is
* treated completely independent from the previous one
*
* We reward the flappy bird at the end of an episode, hence we maintain a frame
* buffer to store the state-action pairs in a sequential order and decide upon
* the reward to be awarded for that state-action on the completion of the
* episode
* @param {*} reward The amound of reward to be awarded to the Flappy Bird
* @param {*} wasSuccessful Determines if the reward to be awarded should be
* negative or positive depending upon if the episode was completed successfully
* or not
*/
function rewardTheBird(reward, wasSuccessful) {
// Minumun number of frames to be maintained in the frame buffer for the
// episode (for maintaining the state-action sequecne tail)
var minFramSize = 5;
// Tolerable deviation from the ideal passage position between the tubes in px
var theta = 1;
var frameSize = Math.max(minFramSize, episodeFrameCount);
// Iterate over the state-action sequence trail, from the most recent to the
// most oldest
for (var i = frameBuffer.length-2; i >= 0 && frameSize > 0; i--) {
var config = frameBuffer[i];
var state = config.env;
var action = config.action;
// The reward for the state is influenced by how close the flappy bird was
// from the ideal passage position
var rewardForState = (reward - Math.abs(state.diffY));
// Determine if the reward for given state-action pair should be positive or
// negative
if (!wasSuccessful) {
if (state.diffY >= theta && action == actionSet.JUMP) {
// If the bird was above the ideal passage position and it still decided
// to jump, reward negatively
rewardForState = -rewardForState;
} else if(state.diffY <= -theta && action == actionSet.STAY) {
// If the bird was below the ideal passage position and it still decided
// to not jump (stay), reward negatively
rewardForState = -rewardForState;
} else {
// The bird took the right decision, so don't award it negatively
rewardForState = +0.5;
}
}
// Update the Q-value for the state-action pair according to the Q-learning
// algorithm Ref: https://en.wikipedia.org/wiki/Q-learning
var futureState = frameBuffer[i+1].env;
var optimalFutureValue = Math.max(getQ(futureState, actionSet.STAY),
getQ(futureState, actionSet.JUMP));
var updateValue = alpha*(rewardForState + gamma * optimalFutureValue - getQ(state, action));
setQ(state, action, updateValue)
frameSize--;
}
// Allocating reward is complete, hence clear the frame buffer but still try to
// maintain the most recent 5 state-action pair Since the last actions taken in
// the previous episode affects the position of the bird in the next episdoe
frameBuffer = frameBuffer.slice(Math.max(frameBuffer.length-minFramSize, 1));
episodeFrameCount = 0;
}
/**
* Function to negatively reward the flappy bird when the game is over
*/
function triggerGameOver() {
var reward = 100;
rewardTheBird(reward, false);
console.log( "GameOver:", score, Object.keys(Q_table).length, trials );
// Reset the episode flag
targetTubeIndex = -1;
episodeFrameCount = 0;
trials++;
}
/**
* This function is executed for every step in the game and is responsible for
* forming the state and delegating the action to be taken back to our flappy
* bird
*/
function nextStep() {
// If the game hasn't started yet then do nothing
if (gameState != GAME)
return;
// Logic to determine if the Flappy Bird successfully surpassed the tube The
// changing of the targetTubeIndex denotes the completion of an episode
if (birdX < tubes[0].x + 3 && (tubes[0].x < tubes[1].x || tubes[1].x + 3 < birdX)) {
targetTube = tubes[0];
if (targetTubeIndex == 1) {
// The target tube changed from [1] to [0], which means the tube[1] was
// crossed successfully Hence reward the bird positively
rewardTheBird(5, true);
}
targetTubeIndex = 0;
} else {
targetTube = tubes[1];
if (targetTubeIndex == 0) {
// The target tube changed from index [0] to [1], which means the tube[0]
// was crossed successfully Hence reward the bird positively
rewardTheBird(5, true);
}
targetTubeIndex = 1;
}
// We'll take no action if the tube is too far from the bird
if (targetTube.x - birdX > 28) {
return;
}
// Else, we'll form our state from the current environment parameters to be
// ingested by our algorithm
var state = {
speedY: Math.round(birdYSpeed * 100),
tubeX: targetTube.x,
diffY: (targetTube.y+17+6) - (birdY+1)
};
// Query the Q-table to determine the appropriate action to be taken for the
// current state
var actionToBeTaken = getAction(state);
// Push the state-action pair to the frame buffer so what we can determine the
// reward for it later on
var config = {
env: state,
action: actionToBeTaken
};
frameBuffer.push(config);
episodeFrameCount++;
// Delegate the action to our flappy bird
if (actionToBeTaken == actionSet.JUMP) {
birdYSpeed = -1.4;
} else {
// For stay action, we do nothing but just let the bird go down due to
// gravity
}
}
</code></pre>
<p>Finally, thank you so much for your valuable time. You guys are way too awesome! :)</p>
| [] | [
{
"body": "<h1>Review</h1>\n\n<p>This review has grown a little beyond a review as I have enjoyed playing with Q_learning. Take what you can, if anything, from the review and modifications I have made. </p>\n\n<p>The majority of changes (suggestions only) are aimed at increasing performance, with the learning m... | {
"AcceptedAnswerId": "206785",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-01T21:06:58.463",
"Id": "206756",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"machine-learning"
],
"Title": "Reinforcement Learning for Flappy Bird in JavaScript"
} | 206756 |
<blockquote>
<p><strong>The Problem</strong></p>
<p>A character is known to its homeboys as a super freq if it occurs with frequency greater than 15% in a given passage of text. Write a program that reads an ASCII text file and identifies all the English alphabet (A-Z, a-z) super freqs in that text file. Your program should be case insensitive.</p>
<p><strong>Sample Input</strong></p>
<p>Your program should take its input from the text file <code>prob2.in</code>. Three examples (A, B and C) of the possible content of this file are shown below:
</p>
<pre><code>(A) Sally sells sea shells by the sea shore.
(B) How now brown cow.
(C) Hey Sam!
</code></pre>
<p><strong>Sample Output</strong></p>
<p>Your program should direct its output to the screen. Appropriate output for the sample inputs (A, B and C) is shown below:
</p>
<pre><code>(A) S is a super freq.
(B) O is a super freq.
W is a super freq.
(C) There are no super freqs.
</code></pre>
</blockquote>
<p><strong>superfreq.py</strong></p>
<pre><code>import re
from collections import Counter
with open('prob2.in') as f:
for line in f:
s = re.sub(r"[^a-z]+", '', line.lower())
d, c = Counter(s), 0
for e in d:
if d[e] / len(line) > 0.15:
print('{0} is a super freq.'.format(e.upper()))
c += 1
if (c == 0):
print('There are no super freqs.')
</code></pre>
<p>Any advice on performance enhancement and solution simplification or that is topical is appreciated!</p>
| [] | [
{
"body": "<p>The variable names <code>c</code>, <code>d</code>, and <code>e</code> are too cryptic. (<code>f</code> is fine, because it's a customary variable for a file. In my solution below, I use <code>c</code> consistently for characters during iteration, which is also acceptable.)</p>\n\n<p>Why do you n... | {
"AcceptedAnswerId": "206774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T01:20:48.713",
"Id": "206761",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Contest Solution: Super Freq"
} | 206761 |
<p>I've been studying C on my own using K&R 2nd Edition, and started exploring GTK+ to practice some of the concepts I've learned by making GUI applications. This is the first GUI application I've built, designed in Glade and coded in C.</p>
<p>I've also included my Makefile with compile options and the Glade XML file code generated. I believe I'm using the appropriate settings for warnings in GCC. I would appreciate any and all feedback on the code as well as the compiler settings I'm using.</p>
<p><strong>main.c</strong></p>
<pre><code>#include <gtk/gtk.h>
#include <stdio.h>
#include <string.h>
#include "handlers.h"
#include "utilities.h"
// Setup sets up the Builder/Window, importing Glade
void setup(GtkBuilder **builder, GtkWidget **window, char *windowName) {
gtk_init(NULL, NULL);
char fileName[64];
sprintf(fileName, "%s.glade", windowName);
*builder = gtk_builder_new();
gtk_builder_add_from_file(*builder, fileName, NULL);
*window = GTK_WIDGET(gtk_builder_get_object(*builder, windowName));
gtk_builder_connect_signals(*builder, NULL);
}
int main(void) {
GtkBuilder *builder;
GtkWidget *window;
setup(&builder, &window, "window_main");
GtkWidget *mask_button;
GtkWidget *number_field;
GtkWidget *bitmask_field;
GtkWidget *output_label;
setup_element(&builder, &mask_button, "mask_button");
setup_element(&builder, &number_field, "number_field");
setup_element(&builder, &bitmask_field, "bitmask_field");
setup_element(&builder, &output_label, "output_label");
// Widgets into the callback handler, to avoid storing widgets them globally
GtkWidget *widgets[] = {number_field, bitmask_field, output_label};
g_signal_connect(mask_button, "clicked", G_CALLBACK(on_button_clicked), widgets);
g_object_unref(G_OBJECT(builder));
gtk_widget_show(window);
gtk_main();
return 0;
}
</code></pre>
<p><strong>handlers.c</strong></p>
<pre><code>#include <gtk/gtk.h>
#include <stdio.h>
#include <stdint.h>
#include "utilities.h"
// When "Mask" is pressed
void on_button_clicked(void *ptr, GtkWidget *widgets[]) {
(void)ptr; // We don't need the button widget
GtkWidget *number_field = GTK_WIDGET(widgets[0]);
GtkWidget *bitmask_field = GTK_WIDGET(widgets[1]);
GtkWidget *output_label = GTK_WIDGET(widgets[2]);
uint64_t number = (int) strtol(gtk_entry_get_text(GTK_ENTRY(number_field)), NULL, 2);
uint64_t mask = (int) strtol(gtk_entry_get_text(GTK_ENTRY(bitmask_field)), NULL, 2);
if (number > ULLONG_MAX || mask > ULLONG_MAX || number < 0 || mask < 0) {
set_label_text(&output_label, "Sorry, only unsigned long long ints supported for now!");
return;
}
g_debug("Number: %lu\nMask: %lu\n", number, mask);
char str[sizeof(uint64_t)];
sprintf(str, "%lu", number & mask);
set_label_text(&output_label, str);
}
// Called when number field is changed
void on_number_change(GtkWidget *number_field, GtkWidget *base10_number_label) {
uint64_t number = strtol(gtk_entry_get_text(GTK_ENTRY(number_field)), NULL, 2);
GtkWidget *widget = GTK_WIDGET(base10_number_label);
char str[sizeof(uint64_t)];
sprintf(str, "(%lu)", number);
set_label_text(&widget, str);
}
// Called when mask field is changed
void on_bitmask_change(GtkWidget *bitmask_field, GtkWidget *base10_mask_label) {
uint64_t mask = strtol(gtk_entry_get_text(GTK_ENTRY(bitmask_field)), NULL, 2);
GtkWidget *widget = GTK_WIDGET(base10_mask_label);
char str[sizeof(uint64_t)];
sprintf(str, "(%lu)", mask);
set_label_text(&widget, str);
}
// Called on exit
void on_window_main_destroy() {
gtk_main_quit();
}
</code></pre>
<p><strong>utilities.c</strong></p>
<pre><code>#include <gtk/gtk.h>
// Helper method to set text of a label
void set_label_text(GtkWidget **widget, char *string) {
gtk_label_set_text(GTK_LABEL(*widget), string);
}
// Sets up Glade XML element
void setup_element(GtkBuilder **builder, GtkWidget **element, char* elementName) {
*element = GTK_WIDGET(gtk_builder_get_object(*builder, elementName));
}
</code></pre>
<p><strong>window_main.glade</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkWindow" id="window_main">
<property name="can_focus">False</property>
<property name="title" translatable="yes">Bit Masker</property>
<property name="resizable">False</property>
<property name="window_position">center-always</property>
<property name="default_width">400</property>
<property name="default_height">100</property>
<property name="gravity">static</property>
<signal name="destroy" handler="on_window_main_destroy" swapped="no"/>
<child type="titlebar">
<placeholder/>
</child>
<child>
<object class="GtkFixed">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkLabel" id="number">
<property name="width_request">77</property>
<property name="height_request">25</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Number:</property>
</object>
<packing>
<property name="x">5</property>
<property name="y">19</property>
</packing>
</child>
<child>
<object class="GtkButton" id="mask_button">
<property name="label" translatable="yes">Mask</property>
<property name="width_request">109</property>
<property name="height_request">45</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="x">165</property>
<property name="y">115</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="bitmask">
<property name="width_request">81</property>
<property name="height_request">27</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Bit-Mask:</property>
</object>
<packing>
<property name="x">3</property>
<property name="y">71</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="bitmask_field">
<property name="width_request">261</property>
<property name="height_request">34</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="max_width_chars">32</property>
<property name="placeholder_text" translatable="yes">10101010</property>
<signal name="changed" handler="on_bitmask_change" object="base10_mask_label" swapped="no"/>
</object>
<packing>
<property name="x">107</property>
<property name="y">65</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="output_label">
<property name="width_request">243</property>
<property name="height_request">20</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<attributes>
<attribute name="foreground" value="#eeeeeeeeecec"/>
</attributes>
</object>
<packing>
<property name="x">101</property>
<property name="y">171</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="number_field">
<property name="width_request">259</property>
<property name="height_request">34</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="max_width_chars">32</property>
<property name="placeholder_text" translatable="yes">11111111</property>
<signal name="changed" handler="on_number_change" object="base10_number_label" swapped="no"/>
</object>
<packing>
<property name="x">108</property>
<property name="y">15</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="base10_number_label">
<property name="width_request">20</property>
<property name="height_request">24</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">(0)</property>
</object>
<packing>
<property name="x">373</property>
<property name="y">21</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="base10_mask_label">
<property name="width_request">20</property>
<property name="height_request">23</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">(0)</property>
</object>
<packing>
<property name="x">371</property>
<property name="y">71</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
</code></pre>
<p><strong>Makefile</strong></p>
<pre><code>all: clean compile run
compile:
gcc -o bitmasker *.c -Wall -Wextra -pedantic `pkg-config --cflags --libs gtk+-3.0` -export-dynamic
run:
./bitmasker
clean:
rm -f bitmasker
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T05:19:58.980",
"Id": "398871",
"Score": "0",
"body": "Faraz,changing your code once answers arrive is poor Code Review etiquette. Post rolled back."
}
] | [
{
"body": "<p><strong>Incorrect buffer size</strong></p>\n\n<p>Code is certainly broken.</p>\n\n<pre><code>char str[sizeof(uint64_t)];\nsprintf(str, \"%lu\", number & mask);\n</code></pre>\n\n<p>To print the decimal form of an arbitrary <code>uint64_t</code> as great as 18,446,744,073,709,551,615 (2<sup>64<... | {
"AcceptedAnswerId": "206773",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T02:29:36.170",
"Id": "206766",
"Score": "4",
"Tags": [
"beginner",
"c",
"calculator",
"bitwise",
"gtk"
],
"Title": "C bit mask calculator written using GTK+ 3"
} | 206766 |
<p>I solved this practice problem in preparation for school exams.</p>
<blockquote>
<p>The owner of a taxi company wants a system that calculates how much money his taxis take in one day.</p>
<p>Write and test a program for the owner.</p>
<ul>
<li><p>Your program must include appropriate prompts for the entry of data.</p></li>
<li><p>Error messages and other output need to be set out clearly and understandably.</p></li>
<li><p>All variables, constants and other identifiers must have meaningful names.</p></li>
</ul>
<p>You will need to complete these three tasks. Each task must be fully tested.</p>
<h3>TASK 1 – calculate the money owed for one trip</h3>
<p>The cost of a trip in a taxi is calculated based on the numbers of KMs traveled and the type of taxi that you are traveling in. The taxi company has three different types of taxi available:</p>
<ul>
<li>a saloon car, that seats up to 4,</li>
<li>a people carrier, that seats up 8,</li>
<li>a mini-van, that seats up to 12.</li>
</ul>
<p>For a trip in a saloon car the base amount is RM2.50 and then a charge of RM1.00 per KM. For a trip in a people carrier the base amount is RM4.00 and a charge of RM1.25 per KM. For a trip in a mini- van the base amount is RM5.00 and a charge of RM1.50 per KM. The minimum trip length is 3KM and the maximum trip length is 50KM. Once the trip is complete a 6% service tax is added.</p>
<h3>TASK 2 – record what happens in a day</h3>
<p>The owner of the taxi company wants to keep a record of the journeys done by each one of his taxis in a day. For each one of his three taxis record the length of each trip and the number of people carried. Your program should store a maximum of 24 trips or 350km worth of trips, whichever comes first. Your program should be able to output a list of the jobs done by each one of the three taxis.</p>
<h3>TASK 3 – calculate the money taken for all the taxis at the end of the day.</h3>
<p>At the end of the day use the data stored for each taxi to calculate the total amount of money taken and the total number of people carried by each one of the three taxis. Using the average price of RM2.79 per litre use the information in the table below to calculate the fuel cost for each taxi:</p>
<ul>
<li>the saloon car uses 7.4L/100km</li>
<li>the people carrier uses 8.6L/100km</li>
<li>and the mini-van uses 9.2L/100km</li>
</ul>
<p>Provide a report for the owner to show this information.</p>
</blockquote>
<p>Here is my rather messy solution:</p>
<pre><code>saloon = []
people_car = []
mini = []
count = 0
total_seats = 0
total_cost = 0
mini_distance = 0
sln_distance = 0
ppl_distance = 0
def check(distance):
try:
distance = float(distance)
except ValueError:
print("Enter a number")
return False
while True:
print("[1] Add to List (" + repr(count) + " entered)")
print("[2] View List")
print("[3] View Information and Costs")
print("[4] Exit")
menu = input("Enter command: ")
if menu == "1":
clarify = input("Add to list? (yes/no) ")
if clarify == "yes" and count < 25:
while True:
if count > 24:
print("You have reached the maximum amount of list inputs!")
break
seats = input("How many riders? (type exit to exit) ")
try:
seats = int(seats)
except ValueError:
print("Please enter a number \n=======================================")
pass
break
if int(seats) > 0 and int(seats) < 5:
car_type = input("You will be taking the saloon car? (yes/no) ")
if car_type == "yes":
distance = input("How far was the trip? ")
if check(distance) == False:
break
if distance > 0 and distance < 51 and sln_distance < 351:
count += 1
len_sum = float(2.50) + distance
total_sum = len_sum * 1.06
print("Price is: RM" + repr(round(total_sum, 2)) + "\n=======================================")
saloon.append("Riders: " + repr(seats) + "Revenue: RM" + repr(round(total_sum, 2)) + " | ")
total_seats += seats
total_cost += round(total_sum, 2)
sln_distance += distance
elif sln_distance > 350:
print("This car has reached it's limit")
elif distance < 1 or distance > 50:
print("Please enter a valid distance between 1 and 50")
else:
print("Have you tried digits?")
elif car_type == "no":
print("Command cancelled")
else:
print("Please redo")
if int(seats) > 4 and int(seats) < 9:
car_type = input("You will be taking the people carrier? (yes/no)")
if car_type == "yes":
distance = input("How far was the trip? ")
if check(distance) == False:
break
if distance > 0 and distance < 51:
count += 1
dis_cos = distance * 1.25
len_sum = float(4) + dis_cos
total_sum = len_sum * 1.06
print("Price is: RM" + repr(round(total_sum, 2)) + "\n=======================================")
people_car.append("Riders: " + repr(seats) + "Revenue: RM" + repr(round(total_sum, 2)) + " | ")
total_seats += seats
total_cost += round(total_sum, 2)
ppl_distance += distance
elif ppl_distance > 350:
print("This car has reached it's limit")
elif distance < 1 or distance > 50:
print("Please enter a valid distance between 1 and 50")
else:
print("Have you tried digits?")
elif car_type == "no":
print("Please redo")
else:
print("Please redo")
if int(seats) > 8 and int(seats) < 13:
car_type = input("You will be taking the mini van? (yes/no)")
if car_type == "yes":
distance = input("How far was the trip? ")
if check(distance) == False:
break
if distance > 0 and distance < 51:
count += 1
dis_cos = distance * 1.5
len_sum = float(5) + dis_cos
total_sum = len_sum * 1.06
print("Price is: RM" + repr(round(total_sum, 2)) + "\n=======================================")
mini.append("Riders: " + repr(seats) + "Revenue: RM" + repr(round(total_sum, 2)) + " | ")
total_seats += seats
total_cost += round(total_sum, 2)
mini_distance += distance
elif mini_distance > 350:
print("This car has reached it's limit")
elif distance < 1 or distance > 50:
print("Please enter a valid distance between 1 and 50")
else:
print("Have you tried digits?")
elif car_type == "no":
print("Please redo")
else:
print("Please enter a valid answer")
elif seats == "exit":
break
elif seats < 1 or seats > 12:
print("Enter within the given range")
elif (not int(seats) > 0) or (not int(seats) < 13) or (not seats == "exit"):
print("========================================")
if clarify == "no":
break
else:
continue
else:
print("Please redo \n=======================================")
elif count == int(24):
count += 1
print("You have reached the maximum amount of list inputs!")
elif menu == "2":
print("Saloon: " + ' '.join(saloon) + "\nPeople carrier: " + ' '.join(people_car) + "\nMini van: " + ' '.join(mini))
print("========================================")
elif menu == "3":
print("Riders: " + repr(total_seats) + "\nCost: RM" + repr(total_cost))
def calc(a):
avg_cost = float(a) / 100
return avg_cost * 7.4
final_sln = float(calc(sln_distance))
final_ppl = float(calc(ppl_distance))
final_mini = float(calc(mini_distance))
print("Saloon fuel cost: RM" + repr(round(final_sln, 2)))
print("People carrier fuel cost: RM" + repr(round(final_ppl, 2)))
print("Mini van fuel cost: RM" + repr(round(final_mini, 2)))
print("========================================")
elif menu == "4":
prompt = input("Exit program? (yes/no)")
if prompt == "yes":
exit()
else:
print("Command canceled")
continue
</code></pre>
| [] | [
{
"body": "<p>To start off, I suggest you split the chunk of if/elif statements into individual functions. By doing this, it'll be easier for someone reader (such as your teacher) to be able to tell what each part of the code is doing. It's also important because it'll help you remember your code when you come ... | {
"AcceptedAnswerId": "206791",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T04:18:46.127",
"Id": "206771",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "Taxi fare calculator, trip recorder, and fuel calculator"
} | 206771 |
<p><strong>Problem</strong> - Given three sorted arrays find combinations which are closest to each other.</p>
<p><strong>example</strong> - </p>
<pre><code>i/p - 3,8,18 7,11,16 10,15,19
o/p - (8,7,10)
i/p - 2,2,6 11,15,15 8,8,18
o/p - (6,11,8)
</code></pre>
<p>Kindly review this scala code and suggest improvements</p>
<pre><code>import scala.math.Ordering._
object NearestMatch {
def main(args: Array[String]) = {
val size = args(0).toInt
val range = args(1).toInt
val (a,b,c) = (Array.fill(size)(scala.util.Random.nextInt(range)).sorted,
Array.fill(size)(scala.util.Random.nextInt(range)).sorted,
Array.fill(size)(scala.util.Random.nextInt(range)).sorted)
println(a.mkString(","))
println(b.mkString(","))
println(c.mkString(","))
var (i,j,k) = (0,0,0)
var (pa,pb,pc) = (0,0,0)
var curDiff = 12345 // a very large number
while (i < a.size && j < b.size && k < c.size) {
val min = Math.min(a(i), Math.min(b(j), c(k)))
val max = Math.max(a(i), Math.max(b(j), c(k)))
val newDiff = max-min
if (curDiff > newDiff) {
pa = i
pb = j
pc = k
curDiff = newDiff
}
if (a(i) == min) i+=1
else if (b(j) == min) j+=1
else k+=1
}
println(a(pa), b(pb), c(pc))
}
}
</code></pre>
| [] | [
{
"body": "<p>A few things I noticed while looking over the code:</p>\n\n<ol>\n<li>You don't need the <code>import scala.math.Ordering._</code> statement. It's not buying you anything.</li>\n<li>It would be easier to read/follow the code if you used better variable names.</li>\n<li><code>12345</code> actually i... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T05:04:26.343",
"Id": "206775",
"Score": "1",
"Tags": [
"array",
"interview-questions",
"scala",
"combinatorics"
],
"Title": "Find the combination of matches which are closest to each other"
} | 206775 |
<p>I've created a Calculator using <code>HTML</code>, <code>CSS</code> and core <code>JS</code>.</p>
<p>I just need some suggestions or improvements on my code.</p>
<p><strong>Here is how my app works:</strong><br>
So, basically, firstly the user enters a number, then clicks on an operator, after then the current number on the screen gets stored in a variable <code>firstOperand</code> and the operator pressed gets stored in a variable <code>currentOperator</code>, then the user enters another number, after then he presses an operator, then the current number on the screen gets stored in a variable <code>secondOperand</code>.</p>
<p>The operator stored in <code>currentOperator</code> now have both the operands, so the answers get shown on the screen, then, the answer gets stored in the <code>firstOperator</code> and the last operator pressed gets stored in the <code>currentOperator</code> and this process continues.</p>
<p>So, if you have any suggestions or improvements for the code, kindly share.</p>
<p><strong>Link to GitHub repo:</strong> <a href="https://github.com/HarshitSeksaria/Calculator/tree/49ef4b06d2783d96ea8a4c28106a983f665691f6" rel="nofollow noreferrer">https://github.com/HarshitSeksaria/Calculator/tree/49ef4b06d2783d96ea8a4c28106a983f665691f6</a></p>
<p><strong>Code Snippet:</strong></p>
<p><em>Kindly, switch to full page.</em></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>let firstOperatorPressed = false;
let firstOperand = 0;
let secondOperand = 0;
let currentOperator = '';
let operatorPressedRecently = false;
// When user clicks on any numeric button, this function will be executed
function buttonPressed(number) {
let currentNumber = document.getElementById('screen-text').innerHTML;
if (currentNumber == '0' || operatorPressedRecently) {
var changedNumber = number;
} else {
var changedNumber = currentNumber + number;
}
document.getElementById('screen-text').innerHTML = changedNumber;
operatorPressedRecently = false;
}
// function when any operator is pressed
function buttonOperatorPressed(operator) {
operatorPressedRecently = true;
if (firstOperatorPressed) {
secondOperand = parseInt(document.getElementById('screen-text').innerHTML);
switch(currentOperator) {
case '+':
firstOperand = firstOperand + secondOperand;
break;
case '-':
firstOperand = firstOperand - secondOperand;
break;
case '*':
firstOperand = firstOperand * secondOperand;
break;
case '/':
firstOperand = firstOperand / secondOperand;
}
document.getElementById('screen-text').innerHTML = firstOperand;
document.getElementById('history').innerHTML += ' ' + currentOperator + ' ' + secondOperand;
} else {
firstOperand = parseInt(document.getElementById('screen-text').innerHTML);
document.getElementById('screen-text').innerHTML = '0';
document.getElementById('history').innerHTML = firstOperand;
}
firstOperatorPressed = true;
currentOperator = operator;
}
// function when = is pressed
function buttonEqualPressed() {
operatorPressedRecently = true;
if(firstOperatorPressed) {
secondOperand = parseInt(document.getElementById('screen-text').innerHTML);
switch(currentOperator) {
case '+':
firstOperand = firstOperand + secondOperand;
break;
case '-':
firstOperand = firstOperand - secondOperand;
break;
case '*':
firstOperand = firstOperand * secondOperand;
break;
case '/':
firstOperand = firstOperand / secondOperand;
}
document.getElementById('screen-text').innerHTML = firstOperand;
firstOperand = parseInt(document.getElementById('screen-text').innerHTML);
firstOperatorPressed = false;
document.getElementById('history').innerHTML = document.getElementById('screen-text').innerHTML;
}
}
function buttonClearPressed() {
document.getElementById('screen-text').innerHTML = '0';
firstOperand = 0;
secondOperand = 0;
firstOperatorPressed = false;
currentOperator = '';
document.getElementById('history').innerHTML = '';
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Styles for whole page */
body {
font-family: Arial, Helvetica, sans-serif;
background-image: url(https://i.stack.imgur.com/qg7MO.png);
}
/* Styles for whole calculator */
#wrapper {
height: 75vh;
width: 51vh;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
margin: auto;
background-color: #F5F5F5;
border-radius: 10px;
animation: fadein 3s;
background-color: #783393;
}
/* Styles for Heading (Calculator) */
#heading {
color: #F5F5F5;
font-size: 2em;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
text-align: center;
background-color: #8B78E6;
padding-block-start: 0.67em;
padding-block-end: 0.67em;
margin-block-start: 0em;
margin-block-end: 0em;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
}
/* Styles for history display */
#history {
min-height: 6vh;
overflow-x: auto;
white-space: nowrap;
text-align: end;
font-family: consolas;
font-size: 2em;
padding: 7px;
color: #fcfcfc;
background-color: #FB6F6F;
}
/* Styles for main display */
#screen-text {
color: #fcfcfc;
padding: 7px;
font-family: consolas;
font-size: 2em;
text-align: end;
background-color: #212121;
}
/* Styles for background of History, Main Display and buttons */
#content {
position: absolute;
left: 0; right: 0;
margin: auto;
width: 51vh;
background-color: #783393;
display: inline-block;
border-radius: 10px;
}
/* Styles for all the buttons */
.button {
background-color: #783393;
border: solid 0px #212121;
color: white;
width: 12vh;
height: 12vh;
cursor: pointer;
font-family: 'Consolas';
text-decoration: none;
font-size: 1.5em;
transition: 0.5s;
}
/* Style for the button when the mouse is over it */
.button:hover {
box-shadow: 0px 10px 20px 0px rgba(0,0,0,0.4);
transform: scale(1.1);
}
/* Animation to fadein the calculator on reload */
@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="main.js"></script>
</head>
<body>
<div id="wrapper">
<h1 id="heading">Calculator</h1>
<div id="content">
<div id="history"></div>
<div id="screen-text">0</div>
<div id="top-section">
<input type="button" onclick="buttonPressed('7')" class="button" value="7">
<input type="button" onclick="buttonPressed('8')" class="button" value="8">
<input type="button" onclick="buttonPressed('9')" class="button" value="9">
<input type="button" onclick="buttonOperatorPressed('+')" class="button" value="+">
</div>
<div id="middle-section">
<input type="button" onclick="buttonPressed('4')" class="button" value="4">
<input type="button" onclick="buttonPressed('5')" class="button" value="5">
<input type="button" onclick="buttonPressed('6')" class="button" value="6">
<input type="button" onclick="buttonOperatorPressed('-')" class="button" value="-">
</div>
<div id="bottom-section">
<input type="button" onclick="buttonPressed('1')" class="button" value="1">
<input type="button" onclick="buttonPressed('2')" class="button" value="2">
<input type="button" onclick="buttonPressed('3')" class="button" value="3">
<input type="button" onclick="buttonOperatorPressed('*')" class="button" value="*">
</div>
<div id="more-section">
<input style="border-bottom-left-radius: 10px" type="button" onclick="buttonClearPressed()" class="button" value="C">
<input type="button" onclick="buttonPressed('0')" class="button" value="0">
<input type="button" onclick="buttonEqualPressed()" class="button" value="=">
<input style="border-bottom-right-radius: 10px" type="button" onclick="buttonOperatorPressed('/')" class="button" value="/">
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h1>HTML</h1>\n\n<p>Current convention is to prefer classes over IDs for CSS. </p>\n\n<hr>\n\n<p>Try using to structure your HTML more semantically. For one, use semantic elements instead of <code>div</code> everywhere. One example could be <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/... | {
"AcceptedAnswerId": "206804",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T07:36:15.497",
"Id": "206780",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"html",
"css",
"calculator"
],
"Title": "Calculator application by an HTML beginner"
} | 206780 |
<p>Improving on <a href="https://codereview.stackexchange.com/questions/161953/implementation-of-logarithmic-random-distribution-satisfying-randomnumberdistrib">this code review</a>, I provide <code>logarithmic_distribution</code> to satisfy the C++ <a href="http://en.cppreference.com/w/cpp/named_req/RandomNumberDistribution" rel="nofollow noreferrer">RandomNumberDistribution concept</a> implementing the PDF</p>
<pre><code>p(x) = N*(m + k * log(x))
</code></pre>
<p>with <code>min <= x <= max</code>. Parameters are <code>m</code>, <code>k</code>, <code>min</code>, <code>max</code>, while <code>N</code> is a normalization constant (to be determined from the parameters). Here is the header file</p>
<pre><code>// file logarithmic_distribution.h
#ifndef logarithmic_distribution_h
#define logarithmic_distribution_h
#include <iostream>
#include <random>
#include <tuple>
namespace my_random {
/**
random distribution p(x) = N*(m + k * log(x)) x in [min,max]
satisfying the RandomNumberDistribution concept, see
http://en.cppreference.com/w/cpp/named_req/RandomNumberDistribution
*/
struct logarithmic_distribution
{
using result_type = double;
struct param_type // required by RandomNumberDistribution concept
{
using distribution_type = logarithmic_distribution;
/// constructor throws if pdf is not well defined, in particular if
/// min < 0, min >= max, or pdf(xmin) < 0.
param_type(double m, double k, double min, double max);
param_type(double m=0.0, double k=1.0, double max=2.0)
: param_type(m,k,1,max) {}
bool operator== (param_type const&p) const noexcept
{
return std::make_tuple( m(), k(), min(), max()) ==
std::make_tuple(p.m(), p.k(), p.min(), p.max());
}
bool operator!= (param_type const&p) const noexcept
{ return ! operator==(p); }
double m() const noexcept
{ return m_m; }
double k() const noexcept
{ return m_k; }
double min() const noexcept
{ return m_min; }
double max() const noexcept
{ return m_max; }
friend std::ostream&operator<<(std::ostream&, param_type const&);
friend std::istream&operator>>(std::istream&, param_type&);
protected:
double m_m;
double m_k;
double m_min, m_max;
}; // struct my_random::logarithmic_distribution::param_type
private:
struct auxiliary // the actual implementation
: param_type
{
auxiliary(param_type const&) noexcept;
template<typename Generator>
result_type operator() (Generator &g) const
{ return sample(m_unif(g)); }
double pdf(double x) const noexcept;
double cdf(double x) const noexcept;
double mean() const noexcept;
double var() const noexcept;
private:
double m_mk;
double m_alna;
double m_cdfb, m_icdfb;
std::uniform_real_distribution<double> m_unif;
double aux_pdf(double) const noexcept;
double aux_cdf(double,double) const noexcept;
double aux_mean(double) const noexcept;
double aux_var(double) const noexcept;
result_type sample(double) const;
} m_aux;
public:
logarithmic_distribution(param_type const&p) noexcept
: m_aux(p) {}
logarithmic_distribution(double m, double k, double min, double max)
: logarithmic_distribution(param_type(m,k,min,max)) {}
logarithmic_distribution(double m=0.0, double k=1.0, double max=2.0)
: logarithmic_distribution(param_type(m,k,max)) {}
double m() const noexcept
{ return m_aux.m(); }
double k() const noexcept
{ return m_aux.k(); }
double min() const noexcept
{ return m_aux.min(); }
double max() const noexcept
{ return m_aux.max(); }
param_type const& param() const noexcept
{ return m_aux; }
bool operator==(logarithmic_distribution const&other) const noexcept
{ return param() == other.param(); }
bool operator!=(logarithmic_distribution const&other) const noexcept
{ return param() != other.param(); }
void param(param_type const&p)
{ m_aux = auxiliary(p); }
void reset() const noexcept {}
friend std::ostream&operator<<(std::ostream&os, logarithmic_distribution const&d)
{ return os << d.param(); }
friend std::istream&operator>>(std::istream&is, logarithmic_distribution&d)
{
param_type p;
is >> p;
d.param(p);
return is;
}
template<typename Generator>
result_type operator() (Generator &g) const
{ return m_aux(g); }
template<typename Generator>
result_type operator() (Generator &g, param_type const&p) const
{ return auxiliary(p)(g); }
double pdf(double x) const
{ return m_aux.pdf(x); }
double cdf(double x) const
{ return m_aux.cdf(x); }
double mean() const
{ return m_aux.mean(); }
double variance() const
{ return m_aux.var(); }
}; // struct my_random::logarithmic_distribution
} // namespace my_random
#endif // logarithmic_distribution_h
</code></pre>
<p>And here the source code:</p>
<pre><code>// file logarithmic_distribution.cc
#include "logarithmic_distribution.h"
#include <exception>
#include <string>
#include <limits>
#include <cmath>
namespace my_random {
using namespace std;
logarithmic_distribution::param_type::
param_type(double m, double k, double min, double max)
: m_m(m), m_k(k), m_min(min), m_max(max)
{
if(min <= 0.)
throw runtime_error("logarithmic pdf: min <= 0");
if(max <= min)
throw runtime_error("logarithmic pdf: min >= max");
if((m+k*log(min)) < 0.)
throw runtime_error("logarithmic pdf <0 at x=min");
}
logarithmic_distribution::auxiliary::auxiliary(param_type const&p) noexcept
: param_type(p)
, m_mk (m_m - m_k)
, m_alna (m_min * log(m_min) )
, m_cdfb (m_mk*(m_max-m_min)+m_k*(m_max*log(m_max)-m_alna))
, m_icdfb(1/m_cdfb)
, m_unif (0.0,m_cdfb) {}
inline
double logarithmic_distribution::auxiliary::aux_pdf(double logx) const noexcept
{ return m_m + m_k * logx; }
double logarithmic_distribution::auxiliary::pdf(double x) const noexcept
{ return m_icdfb * aux_pdf(log(x)); }
inline
double logarithmic_distribution::auxiliary::aux_cdf(double x, double logx) const noexcept
{ return m_mk * (x-m_min) + m_k * (x*logx - m_alna); }
double logarithmic_distribution::auxiliary::cdf(double x) const noexcept
{ return m_icdfb * aux_cdf(x,log(x)); }
inline
double logarithmic_distribution::auxiliary::aux_mean(double x) const noexcept
{ return x*x*(m_m + m_k*(log(x)-0.5)); }
double logarithmic_distribution::auxiliary::mean() const noexcept
{ return 0.5*( aux_mean(m_max) - aux_mean(m_min) )*m_icdfb; }
inline
double logarithmic_distribution::auxiliary::aux_var(double x) const noexcept
{ return x*x*x*(m_m + m_k*(log(x)-0.33333333333333333)); }
double logarithmic_distribution::auxiliary::var() const noexcept
{
double mom1=mean();
double mom2=0.33333333333333333*(aux_var(m_max)-aux_var(m_min))*m_icdfb;
return mom2-mom1*mom1;
}
double logarithmic_distribution::auxiliary::sample(const double C) const
{
const unsigned max_iterations = 100;
const double eps = 10*numeric_limits<double>::epsilon();
if(C <= 0) return min();
if(C >= m_cdfb) return max();
// find x where cdf(x)=C using bracketed Newton-Raphson (NR)
double xl = min();
double xh = max();
double dxo= xh-xl;
double dx = dxo;
double x = xl+C*dx/m_cdfb; // linear interpolation
double lx = log(x);
double df = aux_pdf(lx);
double f = aux_cdf(x,lx) - C;
for(unsigned it=0; it!=max_iterations; ++it) {
double xo = x;
if((f>0? ((x-xh)*f>df) : ((x-xl)*f<df)) || // if NR goes outside of bracket
(abs(f+f) > abs(dxo*df))) { // or NR convergence is slow
dxo= dx; // bisection
dx = 0.5*(xh-xl);
x = xl+dx;
} else { // otherwise
dxo= dx; // Newton-Raphson
dx = f/df;
x -= dx;
}
if((xo<=x && xo>=x) || abs(dx)<=eps*abs(x)) // test for convergence
return x;
lx = log(x);
df = aux_pdf(lx);
f = aux_cdf(x,lx) - C;
if(f<0) xl=x; else xh=x; // maintain bracket
}
throw runtime_error("logarithmic_distribution: exceeded " +
to_string(max_iterations) + " iterations");
}
ostream&operator<<(ostream&os, logarithmic_distribution::param_type const&p)
{
using ios_base = ostream::ios_base;
const auto flags = os.flags();
const auto fill = os.fill();
const auto prec = os.precision();
const auto space = os.widen(' ');
os.flags(ios_base::scientific | ios_base::left);
os.fill(space);
os.precision(numeric_limits<double>::max_digits10);
os << p.m_m << space
<< p.m_k << space
<< p.m_min << space
<< p.m_max;
os.flags(flags);
os.fill(fill);
os.precision(prec);
return os;
}
istream&operator>>(istream&is, logarithmic_distribution::param_type &p)
{
using ios_base = istream::ios_base;
const auto flags = is.flags();
is.flags(ios_base::dec | ios_base::skipws);
is >> p.m_m >> p.m_k >> p.m_min >> p.m_max;
is.flags(flags);
return is;
}
} // namespace my_random
</code></pre>
<p>One particular question I have regards the design of <code>logarithmic_distribution</code>, which follows the following pattern</p>
<pre><code>struct logarithmic_distribution
{
struct param_type { ... };
private:
struct auxiliary : param_type { /* full implementation */ }
m_aux;
public:
/* functionality implemented using m_aux */
};
</code></pre>
<p>An alternative would be</p>
<pre><code>namespace details {
struct logarithmic_distribution_parameters { ... };
}
struct logarithmic_distribution
: details::logarithmic_distribution_parameters
{
using param_type = details::logarithmic_distribution_parameters;
/* full implementation similar to auxiliary above */
};
</code></pre>
<p>This avoids the re-direction (which however is fully inlined), but is somewhat arkward to implement (e.g.\ construction is best done using a <code>setup()</code> function). I wonder whether there are any principle design considerations that favour this alternative, or whether there is another yet better way.</p>
| [] | [
{
"body": "<ul>\n<li><p>I don't advise importing all the names from <code>std</code> into your own namespace, even if only in the implementation file. That's a recipe for confusion and errors - in the worst case, a function added to later standards could be an unambiguously better match at a call site, as <a h... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T10:22:51.117",
"Id": "206788",
"Score": "1",
"Tags": [
"c++",
"c++11",
"random"
],
"Title": "Implementing a random distribution satisfying RandomNumberDistribution concept"
} | 206788 |
<pre><code>class Generator
{
public function createCodes($count, $project, $generator)
{
$batchSize = 250;
$batches = ceil($count / $batchSize);
$sharedColumns = [
'timestamp' => time(),
'parent_id' => $project->id,
'source' => $generator->name,
'generator_id' => $generator->id,
];
$created = 0;
for ($batch = 0; $batch < $batches; $batch++) {
$size = min($batchSize, $count - $created);
$time = time();
$inserts = [];
for ($i = 0; $i < $size; $i++) {
$parentCode = self::generateCode();
$inserts[] = [
'type' => 'parent',
'parent_code' => '',
'code' => $parentCode,
'series' => self::generateSeries(),
];
for ($j = 0; $j < $generator->children; $j++) {
$inserts[] = [
'type' => 'child',
'parent_code' => $parentCode,
'code' => self::generateCode(),
'series' => self::generateSeries(),
];
}
}
$columns = array_keys($sharedColumns + $inserts[0]);
$valueString = '(' . implode(', ', array_fill(0, count($columns), '?')) . ')';
$queryString = 'INSERT INTO project_codes (' . implode(',', array_map('Database::quoteIdentifier', $columns)) . ') VALUES ';
$queryString .= implode(',', array_fill(0, count($inserts), $valueString));
// Flatten all entries and add shared columns
$values = array_reduce($inserts, function ($carry, $item) use ($sharedColumns) {
return array_merge($carry, array_values($sharedColumns), array_values($item));
}, []);
$query = \Database::getInstance()->prepare($queryString);
$query->execute($values);
$created += $size;
}
}
static $codeChars = 'ABCDEFGHJKLMNPQRTUVWXY34789';
protected static function generateCode()
{
return substr(str_shuffle(self::$codeChars), 0, 9);
}
protected static function generateSeries()
{
$numbers = range(1, 30);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 5);
return implode(',', $numbers);
}
}
</code></pre>
<p>The software this code is used in manages prize draws. Companies let the software generate codes that they can e.g. print on their products. Buyers of these products can enter codes back into the system to enter a prize draw. At specified dates the system draws winners from the entered codes and notifies them. </p>
<p>What this particular piece of code should be capable of is to generate a specified amount of random (and unique) codes so they can later be exported by the company and printed on their products. The generated code is stored in the <code>code</code> column, but winners are determined by the <code>series</code> column which is hidden from the end user/customer.</p>
<p>The code doesn't yet guarantee uniqueness. My plan is to select all duplicates for <code>code</code> and <code>series</code> (after generation and inserts) and just generate new ones until there are no duplicates anymore. That way I don't have to check each of the million generated codes for uniqueness.</p>
<hr>
<p>I tested this with a count of 1 million, which took 163s to complete and according to <code>memory_get_peak_usage(true)</code> consumed 4MB of RAM (which I find unlikely, but ok).</p>
<p>I experimented with different batch sizes but the gain of fewer queries seemed to pretty much cancel out with the additional function calls and higher array sizes for the array reduction.</p>
<p>Is there anything I can do to decrease execution time? I don't expect a million entries to be generated in 10 seconds, but if there's any gain to be had I'd appreciate it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T12:57:17.163",
"Id": "398915",
"Score": "0",
"body": "To review your code, we need to know what it's *for*. Not just \"creating database entries\", but what *kind* of entries, for what *purpose* - give us the real-world motivation ... | [
{
"body": "<p>Prepare <strong>once</strong>. That's the very idea behind a <a href=\"https://phpdelusions.net/pdo#multiexec\" rel=\"nofollow noreferrer\">prepared statement</a>. It should give you like 5% gain. </p>\n\n<p><s>Wrap all batches in a single transaction. It could also help you in several ways.</s... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T12:03:20.030",
"Id": "206793",
"Score": "0",
"Tags": [
"performance",
"php",
"mysql"
],
"Title": "Performance for creating millions of database entries"
} | 206793 |
<blockquote>
<p><strong>The Problem</strong></p>
<p>After his brush with the Justice Department over fundraising with Buddhist monks, the Vice President devised a plan to
ensure that such activities are carried out in a more discrete manner and are kept less noticeable. Realizing the Democratic
National Committee’s need for more and more money in the campaign war chest, Mr. Gore devised a “rhythm method” for
accepting campaign donations from Buddhist monks and yet avoiding the conception of an independent counsel. Gore’s
theory is that if the donations are spaced no less than 28 days apart, an independent counsel will not be necessary.</p>
<p>To help Mr. Gore keep track of when it’s okay to accept money from Buddhist monks, you must write a program to
automatically scan the White House email logs for messages from “veep@whitehouse.gov” addressed to“buddha@whitehouse.gov” (the code name for the Al Gore Rhythm Method). Each such email is a secret entry in Mr.Gore’s Buddhist monk fundraising dairy. Your program must send Mr. Gore (“veep@whitehouse.gov”) a reply to
each such email advising him when the next donation may be accepted. You should assume that the email was sent the day
that the donation was accepted. To maintain more secrecy, Mr. Gore refers to a Buddhist monk as a “BM.”</p>
<p><strong>Sample Input</strong></p>
<p>Your program must process the White House electronic mail log, stored in the file whmail.log as input. The mail log is
an ASCII text file which contains a sequence of one or more valid email messages. Each email message consists of a header
followed by the body. A header consists of exactly four lines, each of which begins with a unique keyword. The first line is
the sender line and begins with the keyword From which is followed by a character string representing the email address of
the sender. The second line is the recipient line and begins with the keyword To which is followed by a character string
representing the email address of the recipient of the message. The third line is the date line and begins with the keyword
<code>Date</code> which is followed by a character string representing the date on which the email message was received. The fourth
line is the subject line and begins with the keyword Subject which is followed by an arbitrary character string. A single
blank space separates the keyword on each header line from the character string that follows. The body of an email message
is simply a sequence of one or more lines of text any of which may be blank. The body begins on the fifth line of the email
message. There will be normal White House email interspersed with the Al Gore Rhythm email, but your program should
ignore all email other than those from “veep” to “buddha.”
Sample contents of <code>whmail.log</code> could appear as:</p>
<pre class="lang-none prettyprint-override"><code>From bill@whitehouse.gov
To buffy@airhead.net
Date Saturday, October 4, 1997
Subject Get together
Hey, honeypie. Ole Big Daddy sure is missin you. I’ll be a
lookin for you to come around again this weekend.
Love,
Bill
From veep@whitehouse.gov
To buddha@whitehouse.gov
Date Monday, October 6, 1997
Subject BM
Dear Buddha, I just had a BM. Please advise.
From reno@justice.gov
To bill@whitehouse.gov
Date Wednesday, October 8, 1997
Subject Roby Ridge
Mr. President:
The situation with the lady in Roby is quickly deteriorating.
I advise we use an Apache loaded with napalm to flush the crazy
woman out. If it kills her, it serves her right for that Vaseline
trick. Dead or alive, at least it will be over. If I don’t hear
from you within the next hour, I’ll send for the chopper.
Janet
</code></pre>
<p><strong>Sample Output</strong></p>
<p>The output of your program must be directed to the screen and must consist of a reply email for each Al Gore Rhythm email
found in the log. Each reply must specify the date on which the next donation may be accepted. Your output must be
formatted <em>exactly</em> as that below, which is the output corresponding to the sample input above.</p>
<pre class="lang-none prettyprint-override"><code>From buddha@whitehouse.gov
To veep@whitehouse.gov
Date Saturday, November 8, 1997
Subject Re: BM
Thank you for advising me of your BM. You may not have
another BM until Monday, November 3, 1997.
</code></pre>
</blockquote>
<p><strong>algore.py</strong></p>
<pre class="lang-python prettyprint-override"><code>import datetime
def search_match(t, f):
return t.startswith('From veep@whitehouse.gov') and f.startswith('To buddha@whitehouse.gov')
def get_date(date):
prefix = date.strftime('%A, %B ')
day = date.strftime('%d').lstrip('0')
postfix = date.strftime(', %Y')
return '{0}{1}{2}'.format(prefix, day, postfix)
with open('whmail.log') as f:
for line in f:
if search_match(line, f.readline()):
date, subject = datetime.datetime.strptime(f.readline().strip()[5:], "%A, %B %d, %Y"), f.readline()
subject = 'Re:' + subject[7:]
limit = date + datetime.timedelta(days=28)
sent = limit + datetime.timedelta(days=5)
print('From veep@whitehouse.gov\nTo buddha@whitehouse.gov\nDate {0}\nSubject {1}\nThank you for advising me of your BM. You may not have\nanother BM until {2}'.format(get_date(sent), subject, get_date(limit)))
</code></pre>
<p>Any advice on performance enhancement and solution simplification is appreciated, as are topical comments!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T05:59:22.630",
"Id": "399126",
"Score": "2",
"body": "Could you specify exactly what version of Python and OS you are running? I'm not convinced that your code actually works correctly."
},
{
"ContentLicense": "CC BY-SA 4.0"... | [
{
"body": "<h2>Buggy / fragile code</h2>\n\n<p>As evidenced by the comments debating whether this code works or not, this code is fragile, if not outright broken.</p>\n\n<ul>\n<li><p><strong>In Python 2:</strong> If you run the program in Python 2, it will crash and explicitly tell you what the problem is:</p>\... | {
"AcceptedAnswerId": "207022",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T13:19:50.453",
"Id": "206795",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"datetime"
],
"Title": "Contest Solution: Al Gore Rhythm"
} | 206795 |
<p>I'm having some trouble improving the Connect 4 game that is made in Python. I was wondering if I could get rid of the <code>global</code> statements and pass the variables between parameters and return its values. Also to put all of this in a class. I was wondering if this is possible.</p>
<p>And any more improvements that I could use would be appreciated a lot. Be gentle since I'm a newbie with Python. </p>
<pre><code>grids = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
check = []
user = 1
# THIS WAS VERSION ONE
# def GridBuilder(x,y):
# Colum_Count_Str = x
# Colum_Count = int(Colum_Count_Str)
# Row_Count_Str = y
# Row_Count = int(Row_Count_Str)
#
# Grids = [] * Colum_Count
#
# for Current_Grid_Insert in range (Colum_Count):
# Grids.insert(Current_Grid_Insert,[0]*Row_Count)
#
# return Grids
class FullCapacity_error(Exception):
pass
def user_def():
#Change the global vartiables into local variables
#Define them in the parameters of the functions.
global user
if user < 2:
user = 2
else:
user = 1
return user
def FullCapacity():
global FullCapacity_error
while True:
try:
if grids[3][userInput - 1] != 0:
raise FullCapacity_error
else:
break
except FullCapacity_error:
print("This row is full, try another one!")
confirmed()
def confirmed():
PlayTheGame = True
while PlayTheGame:
try:
global userInput
userInput = int(input("\n Input a coin, player " + str(user) + "(1,4)\n"))
if 5 > userInput > 0:
PlayTheGame = False
else:
print("This number exceeds the board value.")
except ValueError:
print("This number exceeds the board value.")
def placement_def():
for i in range(0, 4):
counter = 0
FullCapacity()
if grids[i][userInput - 1] == 0:
grids[i][userInput - 1] = int(user)
print("\n Current Board\n", grids[3], "\n", grids[2], "\n", grids[1], "\n", grids[0])
break
def check_def():
global loop
global check
for i in range(0, 4):
for a in range(0, 4):
check.append(grids[i][a])
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
else:
check = []
for i in range(0, 4):
for a in range(0, 4):
check.append(grids[a][i])
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
else:
check = []
def checkEmpty_def():
global check
for i in range(0, 4):
for a in range(0, 4):
check.append(grids[i][a])
if 0 not in check:
print("full")
def checks_def():
return check_def() and checkEmpty_def() and diagcheck_def()
def diagcheck_def():
global loop
global check
check = []
diag = 0
for i in range(0, 4):
check.append(grids[diag][diag])
diag = diag + 1
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
check = []
diag = 3
diag2 = 0
for i in range(0, 4):
check.append(grids[diag][diag2])
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
loop = True
while loop:
check_def()
confirmed()
placement_def()
checks_def()
if not loop:
break
user_def()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T13:57:30.230",
"Id": "398922",
"Score": "5",
"body": "Welcome to Code Review! When you say you're \"having some trouble fixing\" do you mean it's broken as is, or are you trying to improve it but are unable to do so without breaking... | [
{
"body": "<h2>Design</h2>\n\n<p>You've got the right diagnosis: your functions are poorly designed, such that it is unclear what their inputs and outputs are. We definitely need to fix your functions so that they act the way functions should. Redesigning the code to be object-oriented would not necessarily i... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T13:40:32.853",
"Id": "206798",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"connect-four"
],
"Title": "Connect 4 on a 4×4 board in Python"
} | 206798 |
<p>Take an integer representing a day of the year and translate it to a string consisting of the month followed by day of the month. For example, Day 32 would be February 1.
I've already submitted my <a href="https://codereview.stackexchange.com/questions/206712/translate-a-day-in-year-to-month-and-day">first attempt</a>, but after looking at ctime library, I came up with this method.
So, the function just takes a single parameter, a day number in a year, e.g. "60" and returns a month and day string. </p>
<pre><code>#include <iostream>
#include <string>
#include <ctime>
using namespace std;
string convertDayOfYear(int num);
int main()
{
const int DAY_IN_YEAR = 60;
string time = convertDayOfYear(DAY_IN_YEAR);
cout << time << endl;
}
string convertDayOfYear(int num)
{
struct tm *date;
const long secPerday = 86400;
long days = (48 * 365) + 12; // years since 1970 plus leap years
time_t time = days * secPerday;
date = gmtime(&time);
time += num * secPerday;
date = gmtime(&time);
char output[26];
strftime(output, 26, "%B %d", date);
string str(output);
return str;}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T14:15:47.200",
"Id": "398925",
"Score": "0",
"body": "It was pointed out in response to your previous question that the conversion depends on whether you have a day in a leap year or not: Day #61 can be March 1 or March 2. How does ... | [
{
"body": "<h1>Avoid <code>using namespace std;</code></h1>\n<p>It's dangerous to import lots of names into the global namespace - newly-added standard identifiers could easily collide with your own, causing hard-to-debug breakage in future. Don't be reluctant to write <code>std::</code> where you need it - it... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T14:06:05.787",
"Id": "206800",
"Score": "-2",
"Tags": [
"c++",
"c++11",
"datetime"
],
"Title": "Translate a day in year to month and day 2nd method"
} | 206800 |
<p>this program seems to be working well so far, but I know it can be cleaner and more efficients with certain functions/methods. As I'm still beginning to code any feedback would be very welcome.</p>
<pre><code># Creating class named contacts with methods for editing and adding new
# contacts. Also there are static methods for showing a specific or all
# contacts data and for showing if there's no contact saved on the address book.
class Contact:
def __init__(self, name, surname, number, email):
self.name = name
self.surname = surname
self.number = number
self.email = email
def edit_name(self, name):
self.name = name
return self.name
def edit_surname(self, surname):
self.surname = surname
return self.surname
def edit_number(self, number):
self.number = number
return self.number
def edit_email(self, email):
self.email = email
return self.email
@classmethod
def add(cls, name, surname, number, email):
return cls(name, surname, number, email)
# This method prints prints all data of a specific entry it index is provided
# otherwise it prints data of all entries saved in address book (fullnames,
# numbers and emails)
@staticmethod
def summary(index=0):
if index == 0:
for j in range(0, len(address_book)):
print(address_book[j].name, address_book[j].surname, end=' / ')
print(address_book[j].number, '/', address_book[j].email)
else:
print(address_book[index].name, address_book[index].surname, end=' / ')
print(address_book[index].number, '/', address_book[index].email)
print()
return None
# Prints only the names saved in the address book
@staticmethod
def saved():
print('CONTACTS SAVED: ', end='')
for j in range(0, len(address_book)):
print(j, address_book[j].name, end=' || ')
return None
# Prompts the user if there's no contact saved in address book
@staticmethod
def isempty(list):
if len(list) == 0:
print('NO CONTACT SAVED\n')
return True
return False
</code></pre>
<p>The program now prompts the user for an option ranging from 0-5. Each option has a funcion in the address book: add, modify, delete, view, view all, finish. </p>
<pre><code>address_book = []
msg_error = '{}Invalid option{}'.format('\033[31m', '\033[m' # Red text
access = input('Press any key to access')
while True:
print('=-=-===-=-=-=-=- CONTACTS MENU -=-=-=-=-=-==-==')
print("""[ 1 ] ADD [ 3 ] DELETE [ 5 ] VIEW ALL
[ 2 ] MODIFY [ 4 ] VIEW [ 0 ] FINISH""")
option = input('>>> ')
#This if and elif blocks check if user input ranges from 0-5
if not option.isnumeric():
print(msg_error)
continue
elif option not in '012345':
print(msg_error)
continue
# If between 0-5, convert value to integer and...
else:
option = int(option)
if option == 0:
print('>>> Program ended\n')
break
# Add new contact
elif option == 1:
name = input('Name: ').capitalize().strip()
surname = input('Surname: ').capitalize().strip()
number = input('Number: ').strip()
email = input('Email: ').strip().lower()
# Trasnform into Contact class and append to address book
address_book.append(Contact.add(name, surname, number, email))
print('Contact saved\n')
# Modify a contact
elif option == 2:
if Contact.isempty(address_book):
continue
Contact.saved()
name_index = int(input('\nModify which name? '))
print('\nModify which entry?')
entry_index = int(input('[ 1 ] NAME [ 2 ] SURNAME [ 3 ] NUMBER [ 4 ] EMAIL\n>>>'))
# Use object methods to modify within the list address book
# User wants to modify name
if entry_index == 1:
modification = input('New name: ').capitalize().strip()
address_book[name_index].edit_name(modification)
# User wants to modify surname
elif entry_index == 2:
modification = input('New surname: ').capitalize().strip()
address_book[name_index].edit_surname(modification)
# User wants to modify number
elif entry_index == 3:
modification = input('New number: ').strip()
address_book[name_index].edit_number(modification)
# User wants to modify email
elif entry_index == 4:
modification = input('New email: ').lower().strip()
address_book[name_index].edit_email(modification)
print('Modification saved\n')
# Delete a contact
elif option == 3:
if Contact.isempty(address_book):
continue
Contact.saved()
name_index = int(input('\nWhich contact delete? '))
del address_book[name_index]
print('Contact deleted')
# View specific contact details
elif option == 4:
if Contact.isempty(address_book):
continue
Contact.saved()
index = int(input('\nContact position: '))
Contact.summary(index)
# View details of all contacts
elif option == 5:
if Contact.isempty(address_book):
continue
Contact.summary()
</code></pre>
| [] | [
{
"body": "<p>You are using Python classes in a weird way.</p>\n\n<ul>\n<li><p>First, if you want to create a new <code>Contact</code> instance, just call <code>Contact(name, surname, number, email)</code>. No need for <code>Contact.add</code>, which does exactly the same thing.</p></li>\n<li><p>Next, all of yo... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T14:27:23.433",
"Id": "206801",
"Score": "3",
"Tags": [
"python",
"beginner",
"object-oriented",
"python-3.x"
],
"Title": "Little Address Book coded in Python 3"
} | 206801 |
<p>I wrote a simple Snake game in Pygame, with GUI. It`s my first Pygame game and one of my first projects in Python. My goal with this implementation is to make it bug-free with fluid UI and as fast/minimal as possible. </p>
<p>This game is meant for both HUMAN and AI players, the first one receives user input and play and the second one play directly (you can have a look at the AI code on the github <a href="https://github.com/Neves4/SnakeAI" rel="nofollow noreferrer">repo</a>). </p>
<p>Can someone give me some advice on what changes do I need to follow best practices? (which includes speed improvement, better readability and reduction of the overall code)</p>
<p>Below is the full code and you can download the ready to run file in <a href="https://drive.google.com/open?id=1vNkZJaGSwhOI3xZxIzuT8ETf0_TlJUyb" rel="nofollow noreferrer">this link</a>.</p>
<h1>snake.py</h1>
<h2>Imports, docstrings and global vars</h2>
<p>I tried to follow the Google Style Python for all docstrings and a <a href="https://stackoverflow.com/questions/1523427/what-is-the-common-header-format-of-python-files">common header format.</a></p>
<pre><code>#!/usr/bin/env python
"""SnakeGame: A simple and fun exploration, meant to be used by AI algorithms.
"""
import sys # To close the window when the game is over
from os import environ, path # To center the game window the best possible
import random # Random numbers used for the food
import logging # Logging function for movements and errors
from itertools import tee # For the color gradient on snake
import pygame # This is the engine used in the game
import numpy as np
__author__ = "Victor Neves"
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "Victor Neves"
__email__ = "victorneves478@gmail.com"
__status__ = "Production"
# Actions, options and forbidden moves
options = {'QUIT': 0, 'PLAY': 1, 'BENCHMARK': 2, 'LEADERBOARDS': 3, 'MENU': 4,
'ADD_LEADERBOARDS': 5}
relative_actions = {'LEFT': 0, 'FORWARD': 1, 'RIGHT': 2}
actions = {'LEFT': 0, 'RIGHT': 1, 'UP': 2, 'DOWN': 3, 'IDLE': 4}
forbidden_moves = [(0, 1), (1, 0), (2, 3), (3, 2)]
# Possible rewards in the game
rewards = {'MOVE': -0.005, 'GAME_OVER': -1, 'SCORED': 1}
# Types of point in the board
point_type = {'EMPTY': 0, 'FOOD': 1, 'BODY': 2, 'HEAD': 3, 'DANGEROUS': 4}
# Speed levels possible to human players
levels = [" EASY ", " MEDIUM ", " HARD ", " MEGA HARDCORE "]
</code></pre>
<h2>Classes</h2>
<p>The classes are GlobalVariables, TextBlock, Snake FoodGenerator and Game.</p>
<ul>
<li><strong>GlobalVariables</strong>: Holds all global variables, which can be changed and hosted in it's class.</li>
<li><strong>TextBlock</strong>: Pygame text structure, which can be a menu or normal text.</li>
<li><strong>Snake</strong>: The snake in the board, holds all of it's parts.</li>
<li><strong>FoodGenerator</strong>: Holds the food position and generate food if necessary.</li>
<li><strong>Game</strong>: Where all things related to the window, main loop, matches and GUI are hosted. My guess is that it's where the code can be optimized the most. There are two type of players that can call the Game, humans and AI. Some functions are meant for AI usage, like state, is_win and others for humans, like handle_input.</li>
</ul>
<h3>GlobalVariables</h3>
<pre><code>class GlobalVariables:
"""Global variables to be used while drawing and moving the snake game.
Attributes
----------
BOARD_SIZE: int, optional, default = 30
The size of the board.
BLOCK_SIZE: int, optional, default = 20
The size in pixels of a block.
HEAD_COLOR: tuple of 3 * int, optional, default = (42, 42, 42)
Color of the head. Start of the body color gradient.
TAIL_COLOR: tuple of 3 * int, optional, default = (152, 152, 152)
Color of the tail. End of the body color gradient.
FOOD_COLOR: tuple of 3 * int, optional, default = (200, 0, 0)
Color of the food.
GAME_SPEED: int, optional, default = 10
Speed in ticks of the game. The higher the faster.
BENCHMARK: int, optional, default = 10
Ammount of matches to BENCHMARK and possibly go to leaderboards.
"""
def __init__(self, BOARD_SIZE = 30, BLOCK_SIZE = 20,
HEAD_COLOR = (42, 42, 42), TAIL_COLOR = (152, 152, 152),
FOOD_COLOR = (200, 0, 0), GAME_SPEED = 10, BENCHMARK = 10):
"""Initialize all global variables. Can be updated with argument_handler.
"""
self.BOARD_SIZE = BOARD_SIZE
self.BLOCK_SIZE = BLOCK_SIZE
self.HEAD_COLOR = HEAD_COLOR
self.TAIL_COLOR = TAIL_COLOR
self.FOOD_COLOR = FOOD_COLOR
self.GAME_SPEED = GAME_SPEED
self.BENCHMARK = BENCHMARK
if self.BOARD_SIZE > 50: # Warn the user about performance
logger.warning('WARNING: BOARD IS TOO BIG, IT MAY RUN SLOWER.')
</code></pre>
<h3>TextBlock</h3>
<pre><code>class TextBlock:
"""Block of text class, used by pygame. Can be used to both text and menu.
Attributes:
----------
text: string
The text to be displayed.
pos: tuple of 2 * int
Color of the tail. End of the body color gradient.
screen: pygame window object
The screen where the text is drawn.
scale: int, optional, default = 1 / 12
Adaptive scale to resize if the board size changes.
type: string, optional, default = "text"
Assert whether the BlockText is a text or menu option.
"""
def __init__(self, text, pos, screen, scale = (1 / 12), type = "text"):
"""Initialize, set position of the rectangle and render the text block."""
self.type = type
self.hovered = False
self.text = text
self.pos = pos
self.screen = screen
self.scale = scale
self.set_rect()
self.draw()
def draw(self):
"""Set what to render and blit on the pygame screen."""
self.set_rend()
self.screen.blit(self.rend, self.rect)
def set_rend(self):
"""Set what to render (font, colors, sizes)"""
font = pygame.font.Font(resource_path("resources/fonts/freesansbold.ttf"),
int((var.BOARD_SIZE * var.BLOCK_SIZE) * self.scale))
self.rend = font.render(self.text, True, self.get_color(),
self.get_background())
def get_color(self):
"""Get color to render for text and menu (hovered or not).
Return
----------
color: tuple of 3 * int
The color that will be rendered for the text block.
"""
color = pygame.Color(42, 42, 42)
if self.type == "menu":
if self.hovered:
pass
else:
color = pygame.Color(152, 152, 152)
return color
def get_background(self):
"""Get background color to render for text (hovered or not) and menu.
Return
----------
color: tuple of 3 * int
The color that will be rendered for the background of the text block.
"""
color = None
if self.type == "menu":
if self.hovered:
color = pygame.Color(152, 152, 152)
return color
def set_rect(self):
"""Set the rectangle and it's position to draw on the screen."""
self.set_rend()
self.rect = self.rend.get_rect()
self.rect.center = self.pos
</code></pre>
<h3>Snake</h3>
<pre><code>class Snake:
"""Player (snake) class which initializes head, body and board.
The body attribute represents a list of positions of the body, which are in-
cremented when moving/eating on the position [0]. The orientation represents
where the snake is looking at (head) and collisions happen when any element
is superposed with the head.
Attributes
----------
head: list of 2 * int, default = [BOARD_SIZE / 4, BOARD_SIZE / 4]
The head of the snake, located according to the board size.
body: list of lists of 2 * int
Starts with 3 parts and grows when food is eaten.
previous_action: int, default = 1
Last action which the snake took.
length: int, default = 3
Variable length of the snake, can increase when food is eaten.
"""
def __init__(self):
"""Inits Snake with 3 body parts (one is the head) and pointing right"""
self.head = [int(var.BOARD_SIZE / 4), int(var.BOARD_SIZE / 4)]
self.body = [[self.head[0], self.head[1]],
[self.head[0] - 1, self.head[1]],
[self.head[0] - 2, self.head[1]]]
self.previous_action = 1
self.length = 3
def move(self, action, food_pos):
"""According to orientation, move 1 block. If the head is not positioned
on food, pop a body part. Else, return without popping.
Return
----------
ate_food: boolean
Flag which represents whether the snake ate or not food.
"""
ate_food = False
if action == actions['IDLE']\
or (action, self.previous_action) in forbidden_moves:
action = self.previous_action
else:
self.previous_action = action
if action == actions['LEFT']:
self.head[0] -= 1
elif action == actions['RIGHT']:
self.head[0] += 1
elif action == actions['UP']:
self.head[1] -= 1
elif action == actions['DOWN']:
self.head[1] += 1
self.body.insert(0, list(self.head))
if self.head == food_pos:
logger.info('EVENT: FOOD EATEN')
self.length = len(self.body)
ate_food = True
else:
self.body.pop()
return ate_food
</code></pre>
<h3>FoodGenerator</h3>
<pre><code>class FoodGenerator:
"""Generate and keep track of food.
Attributes
----------
pos:
Current position of food.
is_food_on_screen:
Flag for existence of food.
"""
def __init__(self, body):
"""Initialize a food piece and set existence flag."""
self.is_food_on_screen = False
self.pos = self.generate_food(body)
def generate_food(self, body):
"""Generate food and verify if it's on a valid place.
Return
----------
pos: tuple of 2 * int
Position of the food that was generated. It can't be in the body.
"""
if not self.is_food_on_screen:
while True:
food = [int((var.BOARD_SIZE - 1) * random.random()),
int((var.BOARD_SIZE - 1) * random.random())]
if food in body:
continue
else:
self.pos = food
break
logger.info('EVENT: FOOD APPEARED')
self.is_food_on_screen = True
return self.pos
</code></pre>
<h3>Game</h3>
<pre><code>class Game:
"""Hold the game window and functions.
Attributes
----------
window: pygame display
Pygame window to show the game.
fps: pygame time clock
Define Clock and ticks in which the game will be displayed.
snake: object
The actual snake who is going to be played.
food_generator: object
Generator of food which responds to the snake.
food_pos: tuple of 2 * int
Position of the food on the board.
game_over: boolean
Flag for game_over.
player: string
Define if human or robots are playing the game.
board_size: int, optional, default = 30
The size of the board.
local_state: boolean, optional, default = False
Whether to use or not game expertise (used mostly by robots players).
relative_pos: boolean, optional, default = False
Whether to use or not relative position of the snake head. Instead of
actions, use relative_actions.
screen_rect: tuple of 2 * int
The screen rectangle, used to draw relatively positioned blocks.
"""
def __init__(self, player, board_size = 30, local_state = False, relative_pos = False):
"""Initialize window, fps and score. Change nb_actions if relative_pos"""
var.BOARD_SIZE = board_size
self.local_state = local_state
self.relative_pos = relative_pos
self.player = player
if player == "ROBOT":
if self.relative_pos:
self.nb_actions = 3
else:
self.nb_actions = 5
self.reset_game()
def reset_game(self):
"""Reset the game environment."""
self.step = 0
self.snake = Snake()
self.food_generator = FoodGenerator(self.snake.body)
self.food_pos = self.food_generator.pos
self.scored = False
self.game_over = False
def create_window(self):
"""Create a pygame display with BOARD_SIZE * BLOCK_SIZE dimension."""
pygame.init()
flags = pygame.DOUBLEBUF
self.window = pygame.display.set_mode((var.BOARD_SIZE * var.BLOCK_SIZE,\
var.BOARD_SIZE * var.BLOCK_SIZE),
flags)
self.window.set_alpha(None)
self.screen_rect = self.window.get_rect()
self.fps = pygame.time.Clock()
def menu(self):
"""Main menu of the game.
Return
----------
selected_option: int
The selected option in the main loop.
"""
pygame.display.set_caption("SNAKE GAME | PLAY NOW!")
img = pygame.image.load(resource_path("resources/images/snake_logo.png"))
img = pygame.transform.scale(img, (var.BOARD_SIZE * var.BLOCK_SIZE, int(var.BOARD_SIZE * var.BLOCK_SIZE / 3)))
img_rect = img.get_rect()
img_rect.center = self.screen_rect.center
menu_options = [TextBlock(' PLAY GAME ', (self.screen_rect.centerx,
4 * self.screen_rect.centery / 10),
self.window, (1 / 12), "menu"),
TextBlock(' BENCHMARK ', (self.screen_rect.centerx,
6 * self.screen_rect.centery / 10),
self.window, (1 / 12), "menu"),
TextBlock(' LEADERBOARDS ', (self.screen_rect.centerx,
8 * self.screen_rect.centery / 10),
self.window, (1 / 12), "menu"),
TextBlock(' QUIT ', (self.screen_rect.centerx,
10 * self.screen_rect.centery / 10),
self.window, (1 / 12), "menu")]
selected = False
selected_option = None
while not selected:
pygame.event.pump()
ev = pygame.event.get()
self.window.fill(pygame.Color(225, 225, 225))
for option in menu_options:
option.draw()
if option.rect.collidepoint(pygame.mouse.get_pos()):
option.hovered = True
if option == menu_options[0]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['PLAY']
elif option == menu_options[1]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['BENCHMARK']
elif option == menu_options[2]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['LEADERBOARDS']
elif option == menu_options[3]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['QUIT']
else:
option.hovered = False
if selected_option is not None:
selected = True
self.window.blit(img, img_rect.bottomleft)
pygame.display.update()
return selected_option
def start_match(self):
"""Create some wait time before the actual drawing of the game."""
for i in range(3):
time = str(3 - i)
self.window.fill(pygame.Color(225, 225, 225))
# Game starts in 3, 2, 1
text = [TextBlock('Game starts in', (self.screen_rect.centerx,
4 * self.screen_rect.centery / 10),
self.window, (1 / 10), "text"),
TextBlock(time, (self.screen_rect.centerx,
12 * self.screen_rect.centery / 10),
self.window, (1 / 1.5), "text")]
for text_block in text:
text_block.draw()
pygame.display.update()
pygame.display.set_caption("SNAKE GAME | Game starts in "
+ time + " second(s) ...")
pygame.time.wait(1000)
logger.info('EVENT: GAME START')
def start(self):
"""Use menu to select the option/game mode."""
opt = self.menu()
running = True
while running:
if opt == options['QUIT']:
pygame.quit()
sys.exit()
elif opt == options['PLAY']:
var.GAME_SPEED = self.select_speed()
self.reset_game()
self.start_match()
score = self.single_player()
opt = self.over(score)
elif opt == options['BENCHMARK']:
var.GAME_SPEED = self.select_speed()
score = []
for i in range(var.BENCHMARK):
self.reset_game()
self.start_match()
score.append(self.single_player())
opt = self.over(score)
elif opt == options['LEADERBOARDS']:
pass
elif opt == options['ADD_LEADERBOARDS']:
pass
elif opt == options['MENU']:
opt = self.menu()
def over(self, score):
"""If collision with wall or body, end the game and open options.
Return
----------
selected_option: int
The selected option in the main loop.
"""
menu_options = [None] * 5
menu_options[0] = TextBlock(' PLAY AGAIN ', (self.screen_rect.centerx,
4 * self.screen_rect.centery / 10),
self.window, (1 / 15), "menu")
menu_options[1] = TextBlock(' GO TO MENU ', (self.screen_rect.centerx,
6 * self.screen_rect.centery / 10),
self.window, (1 / 15), "menu")
menu_options[3] = TextBlock(' QUIT ', (self.screen_rect.centerx,
10 * self.screen_rect.centery / 10),
self.window, (1 / 15), "menu")
if isinstance(score, int):
text_score = 'SCORE: ' + str(score)
else:
text_score = 'MEAN SCORE: ' + str(sum(score) / var.BENCHMARK)
menu_options[2] = TextBlock(' ADD TO LEADERBOARDS ', (self.screen_rect.centerx,
8 * self.screen_rect.centery / 10),
self.window, (1 / 15), "menu")
pygame.display.set_caption("SNAKE GAME | " + text_score
+ " | GAME OVER...")
logger.info('EVENT: GAME OVER | FINAL ' + text_score)
menu_options[4] = TextBlock(text_score, (self.screen_rect.centerx,
15 * self.screen_rect.centery / 10),
self.window, (1 / 10), "text")
selected = False
selected_option = None
while not selected:
pygame.event.pump()
ev = pygame.event.get()
# Game over screen
self.window.fill(pygame.Color(225, 225, 225))
for option in menu_options:
if option is not None:
option.draw()
if option.rect.collidepoint(pygame.mouse.get_pos()):
option.hovered = True
if option == menu_options[0]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['PLAY']
elif option == menu_options[1]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['MENU']
elif option == menu_options[2]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
selected_option = options['ADD_LEADERBOARDS']
elif option == menu_options[3]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
pygame.quit()
sys.exit()
else:
option.hovered = False
if selected_option is not None:
selected = True
pygame.display.update()
return selected_option
def select_speed(self):
"""Speed menu, right before calling start_match.
Return
----------
speed: int
The selected speed in the main loop.
"""
menu_options = [TextBlock(levels[0], (self.screen_rect.centerx,
4 * self.screen_rect.centery / 10),
self.window, (1 / 10), "menu"),
TextBlock(levels[1], (self.screen_rect.centerx,
8 * self.screen_rect.centery / 10),
self.window, (1 / 10), "menu"),
TextBlock(levels[2], (self.screen_rect.centerx,
12 * self.screen_rect.centery / 10),
self.window, (1 / 10), "menu"),
TextBlock(levels[3], (self.screen_rect.centerx,
16 * self.screen_rect.centery / 10),
self.window, (1 / 10), "menu")]
selected = False
speed = None
while not selected:
pygame.event.pump()
ev = pygame.event.get()
# Game over screen
self.window.fill(pygame.Color(225, 225, 225))
for option in menu_options:
if option is not None:
option.draw()
if option.rect.collidepoint(pygame.mouse.get_pos()):
option.hovered = True
if option == menu_options[0]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
speed = 10
elif option == menu_options[1]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
speed = 20
elif option == menu_options[2]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
speed = 30
elif option == menu_options[3]:
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
speed = 45
else:
option.hovered = False
if speed is not None:
selected = True
pygame.display.update()
return speed
def single_player(self):
"""Game loop for single_player (HUMANS).
Return
----------
score: int
The final score for the match (discounted of initial length).
"""
# The main loop, it pump key_presses and update the board every tick.
previous_size = self.snake.length # Initial size of the snake
current_size = previous_size # Initial size
color_list = self.gradient([(42, 42, 42), (152, 152, 152)],\
previous_size)
# Main loop, where the snake keeps going each tick. It generate food,
# check collisions and draw.
while not self.game_over:
action = self.handle_input()
self.game_over = self.play(action)
self.draw(color_list)
current_size = self.snake.length # Update the body size
if current_size > previous_size:
color_list = self.gradient([(42, 42, 42), (152, 152, 152)],\
current_size)
previous_size = current_size
score = current_size - 3
return score
def check_collision(self):
"""Check wether any collisions happened with the wall or body.
Return
----------
collided: boolean
Whether the snake collided or not.
"""
collided = False
if self.snake.head[0] > (var.BOARD_SIZE - 1) or self.snake.head[0] < 0:
logger.info('EVENT: WALL COLLISION')
collided = True
elif self.snake.head[1] > (var.BOARD_SIZE - 1) or self.snake.head[1] < 0:
logger.info('EVENT: WALL COLLISION')
collided = True
elif self.snake.head in self.snake.body[1:]:
logger.info('EVENT: BODY COLLISION')
collided = True
return collided
def is_won(self):
"""Verify if the score is greater than 0.
Return
----------
won: boolean
Whether the score is greater than 0.
"""
return self.snake.length > 3
def generate_food(self):
"""Generate new food if needed.
Return
----------
food_pos: tuple of 2 * int
Current position of the food.
"""
food_pos = self.food_generator.generate_food(self.snake.body)
return food_pos
def handle_input(self):
"""After getting current pressed keys, handle important cases.
Return
----------
action: int
Handle human input to assess the next action.
"""
pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN])
keys = pygame.key.get_pressed()
pygame.event.pump()
action = self.snake.previous_action
if keys[pygame.K_ESCAPE] or keys[pygame.K_q]:
logger.info('ACTION: KEY PRESSED: ESCAPE or Q')
self.over(self.snake.length - 3)
elif keys[pygame.K_LEFT]:
logger.info('ACTION: KEY PRESSED: LEFT')
action = actions['LEFT']
elif keys[pygame.K_RIGHT]:
logger.info('ACTION: KEY PRESSED: RIGHT')
action = actions['RIGHT']
elif keys[pygame.K_UP]:
logger.info('ACTION: KEY PRESSED: UP')
action = actions['UP']
elif keys[pygame.K_DOWN]:
logger.info('ACTION: KEY PRESSED: DOWN')
action = actions['DOWN']
return action
def eval_local_safety(self, canvas, body):
"""Evaluate the safety of the head's possible next movements.
Return
----------
canvas: np.array of size BOARD_SIZE**2
After using game expertise, change canvas values to DANGEROUS if true.
"""
if (body[0][0] + 1) > (var.BOARD_SIZE - 1)\
or ([body[0][0] + 1, body[0][1]]) in body[1:]:
canvas[var.BOARD_SIZE - 1, 0] = point_type['DANGEROUS']
if (body[0][0] - 1) < 0 or ([body[0][0] - 1, body[0][1]]) in body[1:]:
canvas[var.BOARD_SIZE - 1, 1] = point_type['DANGEROUS']
if (body[0][1] - 1) < 0 or ([body[0][0], body[0][1] - 1]) in body[1:]:
canvas[var.BOARD_SIZE - 1, 2] = point_type['DANGEROUS']
if (body[0][1] + 1) > (var.BOARD_SIZE - 1)\
or ([body[0][0], body[0][1] + 1]) in body[1:]:
canvas[var.BOARD_SIZE - 1, 3] = point_type['DANGEROUS']
return canvas
def state(self):
"""Create a matrix of the current state of the game.
Return
----------
canvas: np.array of size BOARD_SIZE**2
Return the current state of the game in a matrix.
"""
canvas = np.zeros((var.BOARD_SIZE, var.BOARD_SIZE))
if self.game_over:
pass
else:
body = self.snake.body
for part in body:
canvas[part[0], part[1]] = point_type['BODY']
canvas[body[0][0], body[0][1]] = point_type['HEAD']
if self.local_state:
canvas = self.eval_local_safety(canvas, body)
canvas[self.food_pos[0], self.food_pos[1]] = point_type['FOOD']
return canvas
def relative_to_absolute(self, action):
"""Translate relative actions to absolute.
Return
----------
action: int
Translated action from relative to absolute.
"""
if action == relative_actions['FORWARD']:
action = self.snake.previous_action
elif action == relative_actions['LEFT']:
if self.snake.previous_action == actions['LEFT']:
action = actions['DOWN']
elif self.snake.previous_action == actions['RIGHT']:
action = actions['UP']
elif self.snake.previous_action == actions['UP']:
action = actions['LEFT']
else:
action = actions['RIGHT']
else:
if self.snake.previous_action == actions['LEFT']:
action = actions['UP']
elif self.snake.previous_action == actions['RIGHT']:
action = actions['DOWN']
elif self.snake.previous_action == actions['UP']:
action = actions['RIGHT']
else:
action = actions['LEFT']
return action
def play(self, action):
"""Move the snake to the direction, eat and check collision."""
self.scored = False
self.step += 1
self.food_pos = self.generate_food()
if self.relative_pos:
action = self.relative_to_absolute(action)
if self.snake.move(action, self.food_pos):
self.scored = True
self.food_generator.is_food_on_screen = False
if self.player == "HUMAN":
if self.check_collision():
return True
elif self.check_collision() or self.step > 50 * self.snake.length:
self.game_over = True
def get_reward(self):
"""Return the current score. Can be used as the reward function.
Return
----------
reward: float
Current reward of the game.
"""
reward = rewards['MOVE']
if self.game_over:
reward = rewards['GAME_OVER']
elif self.scored:
reward = self.snake.length
return reward
def gradient(self, colors, steps, components = 3):
"""Function to create RGB gradients given 2 colors and steps. If
component is changed to 4, it does the same to RGBA colors.
Return
----------
result: list of steps length of tuple of 3 * int (if RGBA, 4 * int)
List of colors of calculated gradient from start to end.
"""
def linear_gradient(start, finish, substeps):
yield start
for i in range(1, substeps):
yield tuple([(start[j] + (float(i) / (substeps-1)) * (finish[j]\
- start[j])) for j in range(components)])
def pairs(seq):
a, b = tee(seq)
next(b, None)
return zip(a, b)
result = []
substeps = int(float(steps) / (len(colors) - 1))
for a, b in pairs(colors):
for c in linear_gradient(a, b, substeps):
result.append(c)
return result
def draw(self, color_list):
"""Draw the game, the snake and the food using pygame."""
self.window.fill(pygame.Color(225, 225, 225))
for part, color in zip(self.snake.body, color_list):
pygame.draw.rect(self.window, color, pygame.Rect(part[0] *\
var.BLOCK_SIZE, part[1] * var.BLOCK_SIZE, \
var.BLOCK_SIZE, var.BLOCK_SIZE))
pygame.draw.rect(self.window, var.FOOD_COLOR,\
pygame.Rect(self.food_pos[0] * var.BLOCK_SIZE,\
self.food_pos[1] * var.BLOCK_SIZE, var.BLOCK_SIZE,\
var.BLOCK_SIZE))
pygame.display.set_caption("SNAKE GAME | Score: "
+ str(self.snake.length - 3))
pygame.display.update()
self.fps.tick(var.GAME_SPEED)
</code></pre>
<h2>Support function, global variables init and <strong>main</strong></h2>
<pre><code>def resource_path(relative_path):
"""Function to return absolute paths. Used while creating .exe file."""
if hasattr(sys, '_MEIPASS'):
return path.join(sys._MEIPASS, relative_path)
return path.join(path.dirname(path.realpath(__file__)), relative_path)
var = GlobalVariables() # Initializing GlobalVariables
logger = logging.getLogger(__name__) # Setting logger
environ['SDL_VIDEO_CENTERED'] = '1' # Centering the window
if __name__ == '__main__':
"""The main function where the game will be executed."""
# Setup basic configurations for logging in this module
logging.basicConfig(format = '%(asctime)s %(module)s %(levelname)s: %(message)s',
datefmt = '%m/%d/%Y %I:%M:%S %p', level = logging.INFO)
game = Game(player = "HUMAN")
game.create_window()
game.start()
</code></pre>
| [] | [
{
"body": "<p>Generally it looks really good to me. One thing that stuck out to me was that you have a lot of repeated code:</p>\n\n<pre><code>for option in menu_options:\n option.draw()\n\n if option.rect.collidepoint(pygame.mouse.get_pos()):\n option.hovered = True\n\n if option == menu_op... | {
"AcceptedAnswerId": "207167",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T14:34:39.067",
"Id": "206803",
"Score": "1",
"Tags": [
"python",
"beginner",
"game",
"pygame",
"snake-game"
],
"Title": "Implementation of the Snake game in Pygame, with GUI"
} | 206803 |
<p>Im new to javascript programming and i am required to make a web app. Node.js will be used as the js runtime environment. In order to minimize the amount of time needed for debugging as the app develops I would like to implement a robust error handling scheme. However, due to my limited background I am not sure if what I am implementing is best practise or if it is even adequate. So any feedback will be accepted.</p>
<p>The function is asynchronous and will use catch to detect if any errors occurred while operating. A try-catch statement will be used to catch any errors. This was done in order to allow for individual error identification from the functions. My aim is to propagate the errors up to the calling function that will handle it in the highest level catch statement (in my case where it is logged *this will change eventually). Any feedback?</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>create: async function(req, res) {
let data = JSON.parse(req.body.data);
let result;
let request_body;
let sub_networks_lora;
try {
request_body = sub_network_api_request_data(data, 1);
result = await lora_app_server.create_applications(request_body)
.catch(err => {
//Error updating application on lora app server
throw err;
});
await db_sub_networks.create_sub_network(result.data.id, data.sub_network_name, data.network_id)
.catch(err => {
throw err;
//Error creating sub network in database
});
sub_networks_lora = await get_sub_networks()
.catch(err => {
throw err;
//Error getting networks from lora app server
})
sub_networks_lora = JSON.stringify(sub_networks_lora);
res.status(200).send({
sub_networks_lora
});
} catch (err) {
console.log(err)
} finally {}
}</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T15:53:10.123",
"Id": "398946",
"Score": "3",
"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><code>try...catch</code> will only handle one error, the remainder, if any, will be uncaught errors.</p>\n\n<p>One approach would be to use <code>Promise.all()</code> and <code>Array.prototype.map()</code> within the <code>async</code> function, <code>throw</code> errors from within <code>.then()<... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T15:22:20.010",
"Id": "206806",
"Score": "-1",
"Tags": [
"javascript",
"node.js",
"error-handling",
"async-await"
],
"Title": "#Error Handling- Propagating errors to calling function."
} | 206806 |
<h2>Intro</h2>
<p>I'm going through the K&R book (2nd edition, ANSI C ver.) and want to get the most from it: learn (outdated) C and practice problem-solving at the same time. I believe that the author's intention was to give the reader a good exercise, to make him think hard about what he can do with the tools introduced, so I'm sticking to program features introduced so far and using "future" features and standards only if they don't change the program logic.</p>
<p>Compiling with <code>gcc -Wall -Wextra -Wconversion -pedantic -std=c99</code>.</p>
<h2>K&R Exercise 1-18</h2>
<p>Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.</p>
<h2>Solution</h2>
<p>My solution reuses functions coded in the previous exercises (<code>getline</code> & <code>copy</code>) and adds a new function <code>size_t trimtrail(char line[]);</code> to solve the problem. For lines that can fit in the buffer, the solution is straightforward. However, what if they can't? The <code>main</code> routine deals with that.</p>
<p>Since dynamic memory allocation hasn't been introduced, I don't see a way to completely trim arbitrary length lines. Therefore, solution does the next best thing: trim the ends, and signal whether there's more job to be done. This way, the shell can re-run the program as many times as necessary to finish the job.</p>
<h2>Code</h2>
<pre><code>/* Exercise 1-18. Write a program to remove trailing blanks and tabs
* from each line of input, and to delete entirely blank lines.
*/
#include <stdio.h>
#include <stdbool.h>
#define BUFSIZE 10 // line buffer size
size_t getline(char line[], size_t sz);
void copy(char to[], char from[]);
size_t trimtrail(char line[]);
int main(void)
{
size_t len; // working length
size_t nlen; // peek length
size_t tlen; // trimmed length
char line[BUFSIZE]; // working buffer
char nline[BUFSIZE]; // peek buffer
bool istail = false;
bool ismore = false;
len = getline(line, BUFSIZE);
while (len > 0) {
if (line[len-1] == '\n') {
// proper termination can mean either a whole line, or end
// of one
tlen = trimtrail(line);
if (istail == false) {
// base case, whole line fits in the working buffer
// print only non-empty lines
if (line[0] != '\n') {
printf("%s", line);
}
}
else {
// long line case, only the tail in the working buffer
printf("%s", line);
if (len != tlen) {
// we couldn't keep the whole history so maybe more
// blanks were seen which could not be processed;
// run the program again to catch those
ismore = true;
}
}
// this always gets the [beginning of] next line
len = getline(line, BUFSIZE);
istail = 0;
}
else {
// if it was not properly terminated, peek ahead to
// determine whether there's more of the line or we reached
// EOF
nlen = getline(nline, BUFSIZE);
if (nlen > 0) {
if (nline[0]=='\n') {
// if next read got us just the '\n'
// we can safely trim the preceding buffer
tlen = trimtrail(line);
if (tlen > 0) {
printf("%s", line);
if (len != tlen)
ismore = 1;
}
}
else {
// if still no '\n', we don't know if safe to trim
// and can only print the preceding buffer here
printf("%s", line);
}
// we didn't yet process the 2nd buffer so copy it into
// 1st and run it through the loop above
len = nlen;
copy(line, nline);
istail = 1;
}
else {
// EOF reached, peek buffer empty
// means we can safely trim the preceding buffer
tlen = trimtrail(line);
if (tlen > 0) {
if (line[0]!='\n') {
printf("%s", line);
}
else {
ismore = 1;
}
}
if (len != tlen) {
ismore = 1;
}
// and we don't need to run the loop anymore, exit here
len = 0;
}
}
}
// if there were too long lines, we could not trim them all;
// signal to the environment that more runs could be required
return ismore;
}
/* getline: read a line into `s`, return string length;
* `sz` must be >1 to accomodate at least one character and string
* termination '\0'
*/
size_t getline(char s[], size_t sz)
{
int c;
size_t i = 0;
bool el = false;
while (i < sz-1 && el == false) {
c = getchar();
if (c == EOF) {
el = true;
}
else {
s[i] = (char) c;
++i;
if (c == '\n') {
el = true;
}
}
}
if (i < sz) {
s[i] = '\0';
}
return i;
}
/* copy: copy a '\0' terminated string `from` into `to`;
* assume `to` is big enough;
*/
void copy(char to[], char from[])
{
size_t i;
for (i = 0; from[i] != '\0'; ++i) {
to[i] = from[i];
}
to[i] = '\0';
}
/* trimtrail: trim trailing tabs and blanks, returns new length
*/
size_t trimtrail(char s[])
{
size_t lastnb;
size_t i;
// find the last non-blank char
for (i = 0, lastnb = 0; s[i] != '\0'; ++i) {
if (s[i] != ' ' && s[i] != '\t' && s[i] != '\n') {
lastnb = i;
}
}
// is it a non-empty string?
if (i > 0) {
--i;
// is there a non-blank char?
if (lastnb > 0 ||
(s[0] != ' ' && s[0] != '\t' && s[0] != '\n')) {
// has non-blanks, but is it properly terminated?
if (s[i] == '\n') {
++lastnb;
s[lastnb] = '\n';
}
}
else {
// blanks-only line, but is it properly terminated?
if (s[i] == '\n') {
s[lastnb] = '\n';
}
}
++lastnb;
s[lastnb] = '\0';
return lastnb;
}
else {
// empty string
return 0;
}
}
</code></pre>
<h2>Test</h2>
<h3>Input File</h3>
<pre><code>1
2
444 4
5555 5
66666 6 6
777777 7
8888888 8
99999999 9
000000000 0
1
</code></pre>
<h3>Test Script (Bash)</h3>
<pre><code>i=0
j=1
./ch1-ex-1-18-01 <test.txt >out1.txt
while [ $? -eq 1 ] && [ $j -lt 20 ]; do
let i+=1
let j+=1
./ch1-ex-1-18-01 <out${i}.txt >out${j}.txt
done
</code></pre>
| [] | [
{
"body": "<p>Review covers only minor stuff.</p>\n\n<p><strong>getline()</strong></p>\n\n<p>Avoid a technical exploit when size == 0. Although this code passes sizes more than 0, the function is hackable with size == 0.</p>\n\n<p>When <code>sz == 0</code>, as type <code>size_t</code>, <code>sz-1</code> is a h... | {
"AcceptedAnswerId": "206895",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T15:47:08.953",
"Id": "206811",
"Score": "5",
"Tags": [
"beginner",
"c",
"strings",
"io"
],
"Title": "K&R Exercise 1-18. Remove trailing blanks and tabs from each line"
} | 206811 |
<p>So, I've been reading about monads and I wanted to see if I could implement a system for asynchronous computation in a monadic way.<br>
I came up with two solutions:</p>
<p>The first one spawns a thread for each function bound, and this thread waits for the previous thread to finish. Should this bother me? These threads aren't doing anything until they have something to do so I'm not putting big loads on the computer.</p>
<pre><code>using System;
using System.Threading;
namespace Philistine
{
public static class Task
{
public static Task<T> Unit<T>(T value) => new Task<T>(value);
public static Task<T> Do<T>(Func<T> computation) => new Task<T>(computation);
}
public class Task<T>
{
private T result;
private readonly Thread thread;
public bool IsDone => thread == null || !thread.IsAlive;
public Task(T value)
{
result = value;
}
public Task(Func<T> computation)
{
thread = new Thread(() => result = computation());
thread.Start();
}
private void SetResult(T t)
{
result = t;
}
private T Wait()
{
if (!IsDone)
thread.Join();
return result;
}
public Task<TR> Bind<TR>(Func<T, Task<TR>> function)
{
if (IsDone)
{
return function(result);
}
else
{
return Task.Do(
() =>
{
var other = function(Wait());
return other.Wait();
});
}
}
public Task<TR> Bind<TR>(Func<T, TR> function)
{
return Task.Do(() => function(Wait()));
}
public void Bind(Action<T> action)
{
new Thread(() => action(Wait())).Start();
}
}
}
</code></pre>
<p>The alternative is to try and have linear task chains be executed on a single thread, and try to make use of a thread pool. What bothers me here is that the implementation is quite a bit more complex. The <code>Wait</code> method is implemented like it is because since I'm using <code>ThreadPool</code> I don't have access to <code>Thread.Join</code> and I felt that adding <code>EventWaitHandle</code>s would add more overhead than speedup.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Philistine
{
public static class Task
{
public static ITask<T> Unit<T>(T value) => new UnitTask<T>(value);
public static ITask<T> Do<T>(Func<T> computation) => new RootTask<T>(computation);
}
public interface ITaskIn<in TIn>
{
void Run(TIn parameter);
void Invoke(TIn parameter);
}
public interface ITask<out TOut>
{
bool IsDone { get; }
ITask<TOtherOut> Bind<TOtherOut>(Func<TOut, ITask<TOtherOut>> function);
ITask<TOtherOut> Bind<TOtherOut>(Func<TOut, TOtherOut> function);
void Bind(Action<TOut> action);
TOut Wait();
}
public class UnitTask<TOut> : ITask<TOut>
{
private readonly TOut result;
public bool IsDone => true;
public UnitTask(TOut value)
{
result = value;
}
public ITask<TOtherOut> Bind<TOtherOut>(Func<TOut, ITask<TOtherOut>> function)
{
return function(result);
}
public ITask<TOtherOut> Bind<TOtherOut>(Func<TOut, TOtherOut> function)
{
return Task.Do(() => function(result));
}
public void Bind(Action<TOut> action)
{
ThreadPool.QueueUserWorkItem(_ => action(result));
}
public TOut Wait() => result;
}
public class RootTask<TOut> : ITask<TOut>
{
protected TOut result;
private List<ITaskIn<TOut>> nextTasks;
public bool IsDone { get; private set; }
protected RootTask() { }
public RootTask(Func<TOut> computation)
{
ThreadPool.QueueUserWorkItem(
_ =>
{
result = computation();
Continue();
});
}
protected void Continue()
{
lock (this)
IsDone = true;
if (nextTasks != null)
{
foreach (var taskIn in nextTasks.Skip(1))
taskIn.Run(result);
nextTasks.First().Invoke(result);
}
}
public ITask<TOtherOut> Bind<TOtherOut>(Func<TOut, ITask<TOtherOut>> function)
{
Monitor.Enter(this);
if (IsDone)
{
Monitor.Exit(this);
return function(result);
}
else
{
var continuation = ContinueWith(function);
Monitor.Exit(this);
return continuation;
}
}
public ITask<TOtherOut> Bind<TOtherOut>(Func<TOut, TOtherOut> function)
{
Monitor.Enter(this);
if (IsDone)
{
Monitor.Exit(this);
return Task.Do(() => function(result));
}
else
{
var continuation = ContinueWith(function);
Monitor.Exit(this);
return continuation;
}
}
public void Bind(Action<TOut> action)
{
Monitor.Enter(this);
if (IsDone)
{
Monitor.Exit(this);
ThreadPool.QueueUserWorkItem(_ => action(result));
}
else
{
ContinueWith(action);
Monitor.Exit(this);
}
}
private ITask<TOtherOut> ContinueWith<TOtherOut>(Func<TOut, ITask<TOtherOut>> function)
{
TOtherOut Unwrapped(TOut tIn) => function(tIn).Wait();
var task = new Task<TOut, TOtherOut>(Unwrapped);
ContinueWithTask(task);
return task;
}
private ITask<TOtherOut> ContinueWith<TOtherOut>(Func<TOut, TOtherOut> function)
{
var task = new Task<TOut, TOtherOut>(function);
ContinueWithTask(task);
return task;
}
private void ContinueWith(Action<TOut> action)
{
var task = new EndTask<TOut>(action);
if (nextTasks == null)
nextTasks = new List<ITaskIn<TOut>>();
nextTasks.Add(task);
}
private void ContinueWithTask(ITaskIn<TOut> task)
{
if (nextTasks == null)
nextTasks = new List<ITaskIn<TOut>>();
nextTasks.Add(task);
}
public TOut Wait()
{
while (!IsDone)
Thread.Sleep(10);
return result;
}
}
public class EndTask<TIn> : ITaskIn<TIn>
{
private readonly Action<TIn> action;
public EndTask(Action<TIn> action)
{
this.action = action;
}
public void Run(TIn parameter)
{
ThreadPool.QueueUserWorkItem(_ => action(parameter));
}
public void Invoke(TIn parameter)
{
action(parameter);
}
}
public class Task<TIn, TOut> : RootTask<TOut>, ITaskIn<TIn>
{
private readonly Func<TIn, TOut> function;
public Task(Func<TIn, TOut> function)
{
this.function = function;
}
public void Run(TIn parameter)
{
ThreadPool.QueueUserWorkItem(
_ =>
{
result = function(parameter);
Continue();
});
}
public void Invoke(TIn parameter)
{
result = function(parameter);
Continue();
}
}
}
</code></pre>
<p>Both implementations are used like this:</p>
<pre><code>var five = Task.Do(
() =>
{
Thread.Sleep(2000);
return 5;
});
var seven = five.Bind(i => i + 2);
var fourteen = seven.Bind(
i =>
{
Thread.Sleep(2000);
return i * 2;
});
var treeFiddy = seven.Bind(
i =>
{
Thread.Sleep(2000);
return Task.Unit(i / 2.0);
});
fourteen.Bind(Console.Out.WriteLine);
treeFiddy.Bind(Console.Out.WriteLine);
</code></pre>
<p><strong>Actual question:</strong><br>
Since I don't have any realworld experience with heavily multi-threaded programs, and I don't have solid understanding of the inner workings of threads, I'd like some help in assessing the costs and benefits of both approaches (performance-wise). Would the ideal solution be some combination of both? The first solution, but with a pool? The second solution but without a pool? Better implementation of <code>Wait</code>? </p>
<p>P. S. Please let me know if some parts of the code could use documentation. I've been staring at it for a while now, so in my eyes it all makes sense and I don't like to add unnecessary comments (I think too much verbosity makes it harder to read).</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T18:41:10.963",
"Id": "398976",
"Score": "1",
"body": "Could you elaborate one what this code allows which the TPL and `System.Threading.Task<T>.ContinueWith` ([something like this](https://tio.run/##FcuxCsJADADQ@e4rYqcW1B/o6OKgUHDoI... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T15:58:07.477",
"Id": "206813",
"Score": "2",
"Tags": [
"c#",
"multithreading",
"functional-programming",
"monads"
],
"Title": "Monadic implementation of asynchronous tasks (hidden overhead of threads)"
} | 206813 |
<h3><a href="https://leetcode.com/problems/lru-cache/" rel="nofollow noreferrer">Problem Statement</a></h3>
<blockquote>
<p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. </p>
<p>get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.</p>
<p>put(key, value) - 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.</p>
<p>Follow up:
Could you do both operations in O(1) time complexity?</p>
<p>Example:</p>
<pre><code>LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
</code></pre>
</blockquote>
<h3>Solution</h3>
<p>This problem can be solved by implementing the Cache as a doubly linked list with head and tail pointers. This gives us constant time access to the head and tail of the Cache. For constant time access to all other nodes we can create a hashmap <code>processMap</code> which maps a key to its corresponding node in the Cache. Now, we can access any node in the linkedlist in constant time.</p>
<p><code>public void put(int key, int value)</code> - First we check if there already exists an entry with the same key in the Cache. If it does then we remove this old entry from the <code>processMap</code> and the linked list. After this we insert the new entry at the end of the linked list.</p>
<p><code>public int get(int key)</code> - We lookup the <code>processMap</code> and if there's an entry for the given key, we output the value of the node, remove the node from its current position and insert it at the end of the list. Otherwise, we return -1.</p>
<pre><code>class ProcessNode {
private int key, value;
private ProcessNode previous, next;
public ProcessNode(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
public void setNext(ProcessNode next) {
this.next = next;
}
public ProcessNode getNext() {
return next;
}
public void setPrevious(ProcessNode previous) {
this.previous = previous;
}
public ProcessNode getPrevious() {
return previous;
}
}
class LRUCache {
private int size = 0;
private int capacity;
private ProcessNode head = null;
private ProcessNode tail = null;
private Map<Integer, ProcessNode> processMap = new HashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
ProcessNode processNode = processMap.get(key);
if (processNode == null) {
return -1;
}
remove(processNode);
addLast(processNode);
return processNode.getValue();
}
private void remove(ProcessNode processNode) {
if (processNode == null) {
return;
}
if ((processNode != head) && (processNode != tail)) {
processNode.getPrevious().setNext(processNode.getNext());
processNode.getNext().setPrevious(processNode.getPrevious());
} else {
if (processNode == head) {
head = processNode.getNext();
if (head != null) {
head.setPrevious(null);
}
}
if (processNode == tail) {
tail = processNode.getPrevious();
if (tail != null) {
tail.setNext(null);
}
}
}
size--;
processMap.remove(processNode.getKey());
}
private void removeFirst() {
remove(head);
}
private void addLast(ProcessNode processNode) {
if (size == capacity) {
removeFirst();
}
if (tail != null) {
tail.setNext(processNode);
processNode.setPrevious(tail);
tail = processNode;
} else {
head = processNode;
tail = processNode;
}
size++;
processMap.put(processNode.getKey(), processNode);
}
public void put(int key, int value) {
ProcessNode existingNode = processMap.get(key);
if (existingNode != null) {
remove(existingNode);
}
ProcessNode newProcessNode = new ProcessNode(key, value);
addLast(newProcessNode);
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
</code></pre>
<p>Please review my code and let me know if there's room for improvement.</p>
| [] | [
{
"body": "<h3>Information hiding</h3>\n\n<p>If <code>ProcessNode</code> is only used by <code>LRUCache</code>,\nthen it's an implementation detail that's best hidden from other classes.\nInstead of a local class, it would be better as a <code>private static</code> inner class.</p>\n\n<h3>Encapsulation and sepa... | {
"AcceptedAnswerId": "207011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T17:56:05.097",
"Id": "206821",
"Score": "2",
"Tags": [
"java",
"programming-challenge",
"linked-list",
"interview-questions",
"cache"
],
"Title": "Leetcode #146. LRUCache solution in Java (Doubly Linked List + HashMap)"
} | 206821 |
<p>I like to unlist my old NuGet packages to keep my catalog clean. However, after a couple of uploads it's always a pain to remove each single package manually so I thought I write a utility for it in python.</p>
<p>It works like that:</p>
<ul>
<li>query the service index for the search url</li>
<li>find my packages by author</li>
<li>extract package id and all versions but the last one</li>
<li>unlist each package and wait one second before doing this (this is a purely magic number, I don't know if it's necessary at all but just in case...)</li>
</ul>
<p>The <code>ApiKey</code> is comming from a json file that has a single property:</p>
<pre class="lang-js prettyprint-override"><code>{
"apiKey": "..."
}
</code></pre>
<p>and here's my code:</p>
<pre><code>import time
import json
import requests
from pprint import pprint
from reusable import log_elapsed
DELETE_DELAY_IN_SECONDS = 1
SERVICE_INDEX_URL = "https://api.nuget.org/v3/index.json"
def load_config():
with open("config.json", "r") as f:
return json.load(f)
'''
Example:
{
"@context": {
"@vocab": "http://schema.nuget.org/services#",
"comment": "http://www.w3.org/2000/01/rdf-schema#comment"
},
"resources": [
{
"@id": "https://api-v2v3search-0.nuget.org/query",
"@type": "SearchQueryService",
"comment": "Query endpoint of NuGet Search service (primary)"
}
],
"version": "3.0.0"
}
'''
def get_resource_url(resources, type):
return [x for x in resources if x["@type"] == type][0]["@id"]
def get_search_url():
response = requests.get(SERVICE_INDEX_URL)
if response.status_code != 200:
raise Exception("Could not reach service index.")
resources = response.json()["resources"]
return get_resource_url(resources, "SearchQueryService")
'''
Example:
[
{
"@id": "https://api.nuget.org/v3/registration3/nuget.versioning/index.json",
"id": "NuGet.Versioning",
"versions": [
{
"@id": "https://api.nuget.org/v3/registration3/nuget.versioning/3.3.0.json"
"downloads": 147,
"version": "1.0.8"
}
]
}
]
Return: id and version from each version but the last one.
'''
def find_my_packages(search_url):
query = "author:me&take=100"
#GET {@id}?q={QUERY}&skip={SKIP}&take={TAKE}&prerelease={PRERELEASE}&semVerLevel={SEMVERLEVEL}"
response = requests.get(f"{search_url}?q={query}")
if response.status_code != 200:
raise Exception("Could not search for packages.")
#https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource
return response.json()["data"]
def get_obsolete_packages(data):
versions_to_unlist = [{"id": x["id"], "previous": [v["version"] for v in x["versions"][:-1]] } for x in data]
return versions_to_unlist
def unlist_packages(packages_to_unlist, apiKey, list_only=True):
headers = {"X-NuGet-ApiKey": apiKey}
for unlist in packages_to_unlist:
pprint(unlist["id"])
package_id = unlist["id"]
for version in unlist["previous"]:
url = f"https://www.nuget.org/api/v2/package/{package_id}/{version}"
if list_only == False:
# we don't want to remove them too fast
time.sleep(DELETE_DELAY_IN_SECONDS)
response = requests.delete(url, headers=headers)
print(f"\t{url} - {response.status_code}")
else:
print(f"\t{url} - this is just a test")
# --- --- ---
@log_elapsed
def main():
config = load_config()
search_url = get_search_url()
my_packages = find_my_packages(search_url)
obsolete_packages = get_obsolete_packages(my_packages)
unlist_packages(obsolete_packages, config["apiKey"], list_only=True)
if __name__ == '__main__':
main()
</code></pre>
<p>For completenes, this is the other module that I load here to measure the time:</p>
<pre><code>import time
def log_elapsed(func):
def measure(*args, **kw):
start = time.perf_counter()
func(*args, **kw)
end = time.perf_counter()
elapsed = round(end - start, 2)
print(f"'{func.__name__}' elapsed: {elapsed} sec")
return measure
</code></pre>
<hr>
<p>What do you think? Is my python code getting better? How would you improve it? </p>
<p>The part that I don't really like is the lengthy and nested comprehension used to extract the <code>id</code> and <code>version</code> of the package in <code>get_obsolete_packages</code>. I wasn't sure how to format it so it's good looking and left it a one-liner. Is this normal to write something like that or would you do it differently?</p>
<p>This script works and I successfuly unlisted several packages in debug mode. I haven't let it unlist all packages yet because I might need them for testing when I'm implementing your suggestions.</p>
| [] | [
{
"body": "<p>If you are making multiple requests to the same host, it is usually faster to open a <a href=\"http://docs.python-requests.org/en/master/api/#request-sessions\" rel=\"nofollow noreferrer\"><code>requests.Session</code></a>. This will re-use the connection to the server and you can even set headers... | {
"AcceptedAnswerId": "206866",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T18:15:04.917",
"Id": "206822",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"rest",
"https",
"nuget"
],
"Title": "Unlist all NuGet packages but the last version"
} | 206822 |
NuGet is the package manager for .NET. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T18:37:39.927",
"Id": "206824",
"Score": "0",
"Tags": null,
"Title": null
} | 206824 |
<p>My goal in this code review is to see if i can figure out how to optimize the Validate function takes up fewer lines of code. i know there must be a way to cut it down so that it doesnt span 300 lines of code.</p>
<p>The Validate function is designed to allow me to check all of the controls in an access form that have their tag field populated with the following tags. This list has grown over time, and the function was originally built a year and a half to two years ago. I figure i may as well get some opinions on this code before i go handing it to people like it is a good idea to use.</p>
<pre><code>'INSTRUCTIONS
'set the tag field under the "other" tab NOTE: you can have multiple letters
's - basic tag to indicate you want to save the value of the control
'x - non-manditory fields that you still wish to save overrides f
'r - specifically for radio buttons to parse the labels caption data
'o - radio buttons where you want the value of the radio button instead of text, also 0 is not a valid number to set the radio buttons to
'n - for float/double
'd - indicates that the value must be a date
'e - Read Only do not attempt to write to. This is more for loading data then saving data.
'l - checks a listbox to see if it has any item data(Validation Only)
'f - not manditory if control is disabled (ignore value if disabled)
'g - modifier to f to check if it has a value and if it does save it
'c - For AutoClearing
'i - For Integer
</code></pre>
<p>They are actually a part of a larger set of instructions, but i wanted to focus on one function in that module at a time. (as much as i can considering helper functions.)</p>
<p>The style of label creation really depends on if you can just use the actual field name as your description of the field (which isn't always feasible) or the caption of the label that is associated with the field. ive found that the field isnt always bound to the controls object of whatever the field is, so i use the name of the field plus lbl tacked on the front. I also support the use of the default named labels, since sometimes its just quicker to let access generate a form for you and just adjust it.</p>
<pre><code>Public Enum mscLabelDesc
msclblstyle = -1 'Label name like lblParentControlName
mscNone = 0 'No label used
msc_labelStyle = 1 'Label name like ParentControlName_label
End Enum
</code></pre>
<p>This is the actual validation function. it takes the name of the form, one of the enumeration options, or if you want to use a different base validation tag that isnt "s", you can set that. I have had this happen exactly once so far, where i needed to validate two different sets of data. Unfortunately when i went through and upgraded this function to handle that situation, it turned into me just grabbing the function doubling the size. </p>
<pre><code>Public Function Validate(ByVal argForm As String, Optional ByVal argLabelDesc As mscLabelDesc = mscNone, Optional ByVal argCustomTag As String = "") As String
'if this ouputs an empty string, everything properly validated.
'if argCustomTag is set then it will only validate controls that have that custom tag.
If Not BasicInclude.DebugMode Then On Error GoTo Error_Handler Else On Error GoTo 0
Dim ctrl As Control
Dim out As String: out = vbCrLf
Dim sourceForm As Form: Set sourceForm = Forms(argForm)
If Len(argCustomTag) > 1 Then
Err.Raise vbObjectError + 1, "Validate", "Custom tag can only be one character long"
End If
If argCustomTag = "" Then
For Each ctrl In sourceForm.Controls
If ctrl.Tag & "" <> "" Then
If ctrl.Tag Like "*f*" And ctrl.Enabled Then
If ctrl.Tag Like "*n*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*i*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Or CStr(ctrl.value & "") Like "*.*" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*d*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsDate(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*l*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.ListCount = 0 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
ElseIf ctrl.ColumnHeads And ctrl.ListCount = 1 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*r*" Or ctrl.Tag Like "*o*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.value = 0 Then
' if you want your radio button group to be not selected when you use this and catch the error, then set the default to 0 and start the valid value set at 1'
'considering changing this to check for -1 so a valid value set can be from 0 up.'
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*s*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Trim$(ctrl.value & "") = "" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
End If
ElseIf Not ctrl.Tag Like "*f*" Then
If ctrl.Tag Like "*n*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*i*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Or CStr(ctrl.value & "") & "" Like "*.*" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*d*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsDate(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*l*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.ListCount = 0 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
ElseIf ctrl.ColumnHeads And ctrl.ListCount = 1 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*r*" Or ctrl.Tag Like "*o*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.value = 0 Then
' if you want your radio button group to be not selected when you use this and catch the error, then set the default to 0 and start the valid value set at 1'
'considering changing this to check for -1 so a valid value set can be from 0 up.'
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*s*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Trim$(ctrl.value & "") = "" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
End If
End If
End If
Next
Else
For Each ctrl In sourceForm.Controls
If ctrl.Tag & "" Like "*" & argCustomTag & "*" Then
If ctrl.Tag Like "*f*" And ctrl.Enabled Then
If ctrl.Tag Like "*n*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*i*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Or CStr(ctrl.value & "") Like "*.*" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*d*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsDate(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*l*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.ListCount = 0 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
ElseIf ctrl.ColumnHeads And ctrl.ListCount = 1 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*r*" Or ctrl.Tag Like "*o*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.value = 0 Then
' if you want your radio button group to be not selected when you use this and catch the error, then set the default to 0 and start the valid value set at 1'
'considering changing this to check for -1 so a valid value set can be from 0 up.'
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*" & argCustomTag & "*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Trim$(ctrl.value & "") = "" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
End If
ElseIf Not ctrl.Tag Like "*f*" Then
If ctrl.Tag Like "*n*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*i*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsNumeric(ctrl.value) Or CStr(ctrl.value & "") & "" Like "*.*" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*d*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Not IsDate(ctrl.value) Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*l*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.ListCount = 0 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
ElseIf ctrl.ColumnHeads And ctrl.ListCount = 1 Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*r*" Or ctrl.Tag Like "*o*" Then
If ctrl.Tag Like "*x*" Then
ElseIf ctrl.value = 0 Then
' if you want your radio button group to be not selected when you use this and catch the error, then set the default to 0 and start the valid value set at 1'
'considering changing this to check for -1 so a valid value set can be from 0 up.'
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
ElseIf ctrl.Tag Like "*" & argCustomTag & "*" Then
If ctrl.Tag Like "*x*" And Trim$(ctrl.value & "") = "" Then
ElseIf Trim$(ctrl.value & "") = "" Then
If argLabelDesc = msclblstyle Then
out = out & sourceForm.Controls("lbl" & StripPrefix(ctrl.Name)).Caption & vbCrLf
ElseIf argLabelDesc = msc_labelStyle Then
out = out & sourceForm.Controls(StripPrefix(ctrl.Name) & "_Label").Caption & vbCrLf
Else
out = out & StripPrefix(ctrl.Name) & vbCrLf
End If
End If
End If
End If
End If
Next
End If
out = Left$(out, Len(out) - 2)
Error_Exit:
Validate = out
Exit Function
Error_Handler:
out = "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: Validate" & vbCrLf & _
"Error Description: " & Err.Description
Resume Error_Exit
End Function
</code></pre>
<p>I only use a limited set of prefixs and then i have to deal with some of other peoples code that i update, sometimes very quickly.</p>
<pre><code>Public Function StripPrefix(ByVal argIn As String) As String
Dim PrefixList() As String: PrefixList = Split("txt,cmb,cbo,chk,lst,rad,opt", ",")
Dim v As Variant
For Each v In PrefixList
If argIn Like v & "*" Then
StripPrefix = Right$(argIn, Len(argIn) - Len(v))
Exit Function
End If
Next
StripPrefix = argIn
End Function
</code></pre>
<p>A simple example usage of the Validate function is as follows:</p>
<pre><code>Public Sub Save()
Dim Out as string
Out = Validate(me.name,msclblstyle)
If Out = vbnullstring Then
'Do Save code here
Else
msgbox "Please check the following fields:" & vbCrLf & vbCrLf & out
End If
End Sub
</code></pre>
| [] | [
{
"body": "<p>Your <code>If-Then-Else-ElseIf-Then-ElseIf</code> construct is really hard to follow. A complex <code>If-Then</code> construct should always be a red flag that there is a better way to do it.</p>\n\n<h2>Simplify the calling</h2>\n\n<p>When you want to use a form in your function, pass the form, no... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T18:59:10.733",
"Id": "206825",
"Score": "1",
"Tags": [
"vba",
"validation",
"ms-access"
],
"Title": "A function to validate that an unbound form in Access has all required fields filled out"
} | 206825 |
<p>Inspired by exercise on HackerRank where I'm expected to implement binary heap with additional method that allows to remove any value from heap I decided to clean up and expand my code a little. Expansion is an ability to pass custom comparator to the heap, and method to remove first element from heap (which for some reason was missing from the exercise).</p>
<p>Heap takes integer values, like in original exercise, but all it needs to be done to change that is to change typing and pass right comparators. Original problem statement assumed that unique integers, but the heap should work also for repeated values.</p>
<p>I've passed my code through PyCharm and removed issues it detected, but I want to know if I'm following other best python practices. If my algorithm is flawed I would also like to know that. I know PEP8 suggests maximum line length of 80, but I'm more comfortable with PyCharm default limit of 120. (In my current workplace limit is even higher.)</p>
<pre><code>import unittest
import doctest
from typing import List, Optional, Callable
class Heap:
"""
Binary heap. Array implementation.
Additional function for erasing element of certain value
>>> heap = Heap()
>>> heap.add(4)
>>> heap.add(2)
>>> heap.add(3)
>>> heap.add(1)
>>> print(heap.erase_value(17))
False
>>> print(heap.erase_value(2))
True
>>> print(heap.pop_first())
1
>>> print(heap.pop_first())
3
>>> print(heap.peek_first())
4
>>> print(heap.pop_first())
4
>>> print(heap.pop_first())
None
"""
array: List[int]
comparator: Callable[[int, int], int]
def __init__(self, comparator: Callable[[int, int], int] = lambda a, b: -1 if a < b else 0 if a == b else 1):
"""
Array initiated with guard, so indexing starts with 1, which makes getting children/parent easier.
:param comparator: Comparator to use. Default results in min-heap.
"""
self.array = [None]
self.comparator = comparator
def _left_child_index(self, parent_index: int) -> Optional[int]:
"""
Give the index of the left child of the parent.
:param parent_index: Index of the parent.
:return: Index of the left child or None if parent does not have left child.
"""
child_index = parent_index * 2
if child_index < len(self.array):
return child_index
return None
def _right_child_index(self, parent_index: int) -> Optional[int]:
"""
Give the index of the right child of the parent.
:param parent_index: Index of the parent.
:return: Index of the right child or None if parent does not have right child.
"""
child_index = parent_index * 2 + 1
if child_index < len(self.array):
return child_index
return None
@staticmethod
def _parent_index(child_index: int) -> Optional[int]:
"""
Get the index of the parent of the child.
:param child_index: Index of the child.
:return: Index of the parent or None if child is root.
"""
if child_index <= 1:
return None
return child_index // 2
def _swap_indexes(self, index1: int, index2: int) -> None:
"""
Swap values from two indexes.
:param index1: Index of first element.
:param index2: Index of second element.
"""
tmp = self.array[index1]
self.array[index1] = self.array[index2]
self.array[index2] = tmp
def _heapify_up(self, index: int) -> None:
"""
Update heap tree by floating current element up till it's in the right place.
:param index: Current element index.
"""
parent_index = self._parent_index(index)
if parent_index is None:
return
if self.comparator(self.array[index], self.array[parent_index]) < 0:
self._swap_indexes(index, parent_index)
self._heapify_up(parent_index)
def _heapify_down(self, index: int) -> None:
"""
Update heap tree by dropping current element down till it's in the right place.
:param index: Current element index.
"""
if index >= len(self.array):
return
left_child = self._left_child_index(index)
right_child = self._right_child_index(index)
if left_child is None:
return
if self.comparator(self.array[left_child], self.array[index]) < 0:
if (right_child is not None) and self.comparator(self.array[right_child], self.array[left_child]) < 0:
self._swap_indexes(index, right_child)
self._heapify_down(right_child)
else:
self._swap_indexes(index, left_child)
self._heapify_down(left_child)
else:
if (right_child is not None) and self.comparator(self.array[right_child], self.array[index]) < 0:
self._swap_indexes(index, right_child)
self._heapify_down(right_child)
def add(self, val: int) -> None:
"""
Add value to the heap.
:param val: Value to add.
"""
self.array.append(val)
self._heapify_up(len(self.array) - 1)
def erase_value(self, val: int) -> bool:
"""
Erase first instance of value from the heap.
:param val: Value to erase.
:return: True if something was erased, false otherwise.
"""
try:
index = self.array.index(val)
except ValueError:
return False
self._swap_indexes(index, len(self.array) - 1)
self.array.pop()
parent_index = self._parent_index(index)
if index >= len(self.array):
return True
if (parent_index is None) or self.comparator(self.array[parent_index], self.array[index]):
self._heapify_down(index)
else:
self._heapify_up(index)
return True
def pop_first(self) -> Optional[int]:
"""
Erase and get the first element from the heap.
:return: The first element from the heap or None if heap is empty.
"""
first_element = self.peek_first()
if first_element is None:
return None
self.erase_value(first_element)
return first_element
def peek_first(self) -> Optional[int]:
"""
Get the first element from the heap.
:return: The first element from the heap or None if heap is empty.
"""
if len(self.array) <= 1:
return None
return self.array[1]
class TestHeap(unittest.TestCase):
heap_min: Heap
heap_max: Heap
def setUp(self):
self.heap_min = Heap()
self.heap_max = Heap(lambda a, b: -1 if a > b else 0 if a == b else 1)
def test_inserting_in_sorted_order(self):
for num in range(1, 16):
self.heap_min.add(num)
for num in range(1, 16):
self.assertEqual(self.heap_min.pop_first(), num)
assert self.heap_min.peek_first() is None
def test_inserting_in_reverse_order(self):
for num in range(15, 0, -1):
self.heap_min.add(num)
for num in range(1, 16):
self.assertEqual(self.heap_min.pop_first(), num)
assert self.heap_min.peek_first() is None
def test_removing_middle_first(self):
for num in range(1, 16):
self.heap_min.add(num)
for num in range(6, 11):
self.assertTrue(self.heap_min.erase_value(num))
for num in range(1, 6):
self.assertEqual(self.heap_min.pop_first(), num)
for num in range(11, 16):
self.assertEqual(self.heap_min.pop_first(), num)
assert self.heap_min.peek_first() is None
def test_erasing_nonexistent(self):
for num in range(1, 16):
self.heap_min.add(num)
self.assertFalse(self.heap_min.erase_value(17))
self.assertFalse(self.heap_min.erase_value(42))
self.assertFalse(self.heap_min.erase_value(-1))
self.assertTrue(self.heap_min.erase_value(2))
self.assertFalse(self.heap_min.erase_value(2))
def test_non_unique_values(self):
for num in range(1, 8):
self.heap_min.add(num)
for num in range(1, 8):
self.heap_min.add(num)
self.assertTrue(self.heap_min.erase_value(1))
self.assertTrue(self.heap_min.erase_value(1))
self.assertFalse(self.heap_min.erase_value(1))
self.assertTrue(self.heap_min.erase_value(4))
self.assertTrue(self.heap_min.erase_value(4))
for num in range(2, 8):
if num == 4:
continue
self.assertEqual(self.heap_min.pop_first(), num)
self.assertEqual(self.heap_min.pop_first(), num)
assert self.heap_min.peek_first() is None
def test_max_comparator(self):
for num in range(1, 16):
self.heap_max.add(num)
for num in range(15, 0, -1):
self.assertEqual(self.heap_max.pop_first(), num)
assert self.heap_max.peek_first() is None
if __name__ == '__main__':
doctest.testmod()
unittest.main()
</code></pre>
| [] | [
{
"body": "<h2>Excellent</h2>\n\n<ul>\n<li><strong>Type annotations</strong> help the IDE make sense of dynamically typed code.</li>\n<li><strong>Doctest examples</strong> show people how to use your code with theirs.</li>\n<li><strong>Unit tests</strong> ensure that future changes are less likely to break func... | {
"AcceptedAnswerId": "206837",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T19:14:55.787",
"Id": "206827",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"heap"
],
"Title": "Python 3 implementation of binary heap"
} | 206827 |
<p>I'm relatively new to JavaScript and wonder whether my code is 'acceptable' for a practice exercise. Essentially, the function (successfully) returns true or false if the provided string has a letter 'b' 3 characters after a letter 'a' - e.g.:</p>
<p>Input:"after badly" - Output:"false"
<br>Input:"Laura sobs" - Output:"true"</p>
<p>Could somebody advise me how it could be improved? Although it works, I wonder whether the best functions are used and whether its 'readability' could be improved (i.e. <code>return trueOrFalse.some(answer)</code> ).</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 bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any index is true
return el === true;
};
return trueOrFalse.some(answer); // return true/false
}</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T20:10:40.510",
"Id": "399083",
"Score": "1",
"body": "I believe that your code would fail with an input like 'axab'"
}
] | [
{
"body": "<p>Using a regular expression is definitely the way to go — that's exactly what they are good at doing. The following regex looks for <code>'a'</code>, followed by any number of spaces, followed by a non-space character, followed by any number of spaces, followed by a non-space character, followed b... | {
"AcceptedAnswerId": "206845",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T19:44:36.917",
"Id": "206831",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"strings"
],
"Title": "Detect whether a string has a letter 'b' 3 characters after 'a'"
} | 206831 |
<p>Inspired this guide: <a href="https://developer.android.com/jetpack/docs/guide" rel="nofollow noreferrer">https://developer.android.com/jetpack/docs/guide</a>
<a href="https://i.stack.imgur.com/YHVBH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YHVBH.png" alt="enter image description here"></a>
I try to build some app with similar architecture.</p>
<p>App interact with remote API via http protocol (json responses from server). For example, GET <code>/bonuses/:id</code> return <code>{status: true, bonus: {id: 1, name: "test bonus"}}</code></p>
<p>POST <code>/login</code> can return <code>{status: true, token: "dafadafadfadfadf"}</code> or <code>{status: false, message: "Password or phone incorrect"</code>}</p>
<p>For example, I post here my LoginFragment, LoginViewModel, UserRepository and RemoteDataSource.</p>
<p>Does my MVVM approach good? What is very bad in my code and how I can improve bad places? Possible memory leaks, etc...</p>
<p>One bad thing, what I see - repeating code in UserRepository, how I can improve it? </p>
<p>Other issue - naming some instance variables with m and other - without (I fix it later).</p>
<p>What is good in my code?</p>
<pre><code>public class LoginFragment extends Fragment implements View.OnClickListener {
public static String TAG = "LoginFragment";
private NavController mNavController;
private ApiService mApiService;
@BindView(R.id.btn_login)
Button mBtnLogin;
@BindView(R.id.et_phone)
EditText mEtPhone;
@BindView(R.id.et_password)
EditText mEtPassword;
@BindView(R.id.tv_forgot_password)
TextView mTvForgotPassword;
@BindView(R.id.tv_registration)
TextView mTvRegistration;
MainActivity mActivity;
private LoginViewModel mLoginViewModel;
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance(String param1, String param2) {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_login, container, false);
ButterKnife.bind(this, v);
mActivity = (MainActivity) getActivity();
mNavController = mActivity.getNavController();
mActivity.getSupportActionBar().setTitle(getString(R.string.login));
mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mActivity.getSupportActionBar().setDisplayUseLogoEnabled(false);
mApiService = RetrofitClient.getInstance().getApiService();
mBtnLogin.setOnClickListener(this);
mTvForgotPassword.setOnClickListener(this);
mTvRegistration.setOnClickListener(this);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
super.onActivityCreated(savedInstanceState);
mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login: {
mLoginViewModel.init(mEtPhone.getText().toString().replaceAll("\\D+", ""), mEtPassword.getText().toString());
mLoginViewModel.getNetworkState().observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer state) {
if(state == NetworkState.LOADED) {
Boolean status = mLoginViewModel.getRemoteDataSource().getStatus();
if(status) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString(User.TOKEN_NAME, mLoginViewModel.getToken());
editor.apply();
mNavController.navigate(R.id.action_loginFragment_to_bonusesFragment);
} else {
AlertDialogHelper.showDialog(mActivity, getString(R.string.warning), mLoginViewModel.getRemoteDataSource().getMessage());
}
} else if(state == NetworkState.FAILED) {
AlertDialogHelper.showDialog(mActivity, getString(R.string.warning), mLoginViewModel.getRemoteDataSource().getMessage());
}
}
});
break;
}
case R.id.tv_registration: {
mNavController.navigate(R.id.action_loginFragment_to_registrationFragment);
break;
}
case R.id.tv_forgot_password: {
mNavController.navigate(R.id.action_loginFragment_to_restorePasswordFragment);
break;
}
}
}
}
</code></pre>
<p>LoginViewModel:</p>
<pre><code>public class LoginViewModel extends ViewModel {
private UserRepository mUserRepository;
private RemoteDataSource<String> mLogin;
private String mPhone;
private String mPassword;
public LoginViewModel() {
}
public void init(String phone, String password) {
mUserRepository = new UserRepository();
mPassword = password;
mPhone = phone;
mLogin = mUserRepository.login(phone, password);
}
public LiveData<Integer> getNetworkState() {
return mLogin.getNetworkState();
}
public Boolean getStatus() {
return mLogin.getStatus();
}
public String getToken() {
return mLogin.getData();
}
public RemoteDataSource<String> getRemoteDataSource() {
return mLogin;
}
}
</code></pre>
<p>UserRepository:</p>
<pre><code>public class UserRepository {
public static String TAG = "UserRepository";
ApiService mApiService;
SharedPreferences mPrefs;
Context mContext;
RemoteDataSource<User> mUserInfo;
RemoteDataSource<String> mUserLogin;
RemoteDataSource<String> mUserSendCode;
public UserRepository() {
mApiService = new RetrofitClient().getApiService();
mContext = App.getAppContext();
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mUserInfo = new RemoteDataSource<>();
mUserLogin = new RemoteDataSource<>();
mUserSendCode = new RemoteDataSource<>();
}
public RemoteDataSource getUserInfo() {
mUserInfo.setIsLoading();
Call<ApiResponse> userCall = mApiService.getUserInfo(mPrefs.getString(User.TOKEN_NAME, null));
userCall.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
mUserInfo.setIsLoaded(response.body().getUser());
mUserInfo.setStatus(response.body().getStatus());
mUserInfo.setMessage(response.body().getMessage());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.e(TAG, t.getMessage());
mUserInfo.setFailed(t.getMessage());
}
});
return mUserInfo;
}
public RemoteDataSource login(String phone, String password) {
mUserLogin.setIsLoading();
Call<ApiResponse> loginCall = mApiService.login(phone, password);
loginCall.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
mUserLogin.setIsLoaded(response.body().getToken());
mUserLogin.setStatus(response.body().getStatus());
mUserLogin.setMessage(response.body().getMessage());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.e(TAG, t.getMessage());
mUserLogin.setFailed(t.getMessage());
}
});
return mUserLogin;
}
public RemoteDataSource sendCode(String phone) {
mUserSendCode.setIsLoading();
Call<ApiResponse> sendCodeCall = mApiService.sendCode(phone);
sendCodeCall.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
mUserSendCode.setIsLoaded(response.body().getToken());
mUserSendCode.setStatus(response.body().getStatus());
mUserSendCode.setMessage(response.body().getMessage());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.e(TAG, t.getMessage());
mUserLogin.setFailed(t.getMessage());
}
});
return mUserSendCode;
}
}
</code></pre>
<p>and RemoteDataSource:</p>
<pre><code>public class RemoteDataSource<T> {
private final MutableLiveData<Integer> networkState = new MutableLiveData<>();
private T data;
private String message;
private Boolean status;
private String code;
public RemoteDataSource() {
networkState.postValue(NetworkState.DEFAULT);
}
public MutableLiveData<Integer> getNetworkState() {
return networkState;
}
public void setIsLoading() {
networkState.postValue(NetworkState.LOADING);
}
public void setDefault() {
networkState.postValue(NetworkState.DEFAULT);
}
public void setIsLoaded(T data) {
networkState.postValue(NetworkState.LOADED);
this.data = data;
}
public void setFailed(@NonNull String errorMessage) {
this.message = errorMessage;
networkState.postValue(NetworkState.FAILED);
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public T getData() {
return data;
}
public String getCode() { return code;}
public void setCode(String code) {this.code = code;}
}
</code></pre>
<p>User - is simple pojo model:</p>
<pre><code>public class User {
public static String TOKEN_NAME="token";
private String token;
private Integer bonus;
private String name;
private String email;
private String phone;
public Integer getBonus() { return bonus;}
public void setBonus(Integer bonus) {this.bonus = bonus;}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
}
</code></pre>
<p>BonusRepository, BonusVieModel, Bonus model and BonusFragment looks like the very similar on upper code. </p>
<p>UPD: it will be great, if you answer cover, how I organize repository/mvvm patterns.</p>
| [] | [
{
"body": "<pre><code>if(state == NetworkState.LOADED) {\n Boolean status = mLoginViewModel.getRemoteDataSource().getStatus();\n</code></pre>\n\n<p>Instead of having two separate if statement checks, this can be combined to check the NetworkState as well as call and check getStatus(), che... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T21:09:28.557",
"Id": "206836",
"Score": "1",
"Tags": [
"java",
"android",
"mvvm"
],
"Title": "Android MVVM application architecture"
} | 206836 |
<p>For a hobby project, I am using openpyxl to export Excel workbooks as JSON. Part of this involves identifying the formatting applied to cells, and serializing this information (provided the format is not the default - no need to export that). To minimize the output JSON filesize, it is sensible to report the cells that use a given formatting scheme in the largest range notation possible, rather than individually listing cells:</p>
<pre><code>"format": { some format spec },
"ranges": [
"A1:Z3000",
"AB4"
]
</code></pre>
<p>instead of </p>
<pre><code>"format": { some format spec },
"ranges": [
"A1",
"A2",
...
"Z3000",
"AB4"
]
</code></pre>
<p>The code I wrote to do this is as follows:</p>
<pre><code>def collapse_cellranges(ranges: list):
'''Attempt to combine the given CellRanges. Recursive, since a grown range
may not be combinable with the constituents of the next range until that
range has been processed too'''
start_count = len(ranges)
i = 0
working_count = start_count
while i < working_count:
rg = ranges[i]
j = 1
reassign = False
# Iterate a slice (as we modify the original)
for other in ranges[i + 1:]:
if range_is_adjacent(rg, other):
rg = rg.union(other)
reassign = True
ranges.pop(i + j)
working_count -= 1
else:
j += 1
# Reassign only once per range, no matter how many were joined.
if reassign:
ranges[i] = rg
i += 1
if working_count < start_count and working_count > 1:
collapse_cellranges(ranges)
else:
return
</code></pre>
<p>The adjacency calculation:</p>
<pre><code>def range_is_adjacent(range, other: CellRange):
'''Determine if the given range is adjacent to the given CellRange.
Returns True if joining the range with the CellRange would increase
only its row span or column span.'''
if isinstance(range, CellRange):
if other.issuperset(range):
return False
min_col, min_row, max_col, max_row = range.bounds
else:
if isinstance(range, Cell):
min_col = max_col = range.col_idx
min_row = max_row = range.row
elif isinstance(range, str):
min_col, min_row, max_col, max_row = range_boundaries(range)
if other.issuperset(CellRange(None, min_col, min_row, max_col, max_row)):
return False
r_min_col, r_min_row, r_max_col, r_max_row = other.bounds
if min_col == r_min_col and max_col == r_max_col:
# Columns aligned, require bordering maxs to mins
return (max_row + 1 == r_min_row
or min_row - 1 == r_max_row)
elif min_row == r_min_row and max_row == r_max_row:
# Rows aligned, require bordering maxs to mins
return (max_col + 1 == r_min_col
or min_col - 1 == r_max_col)
return False
</code></pre>
<p>Definitions for <a href="https://openpyxl.readthedocs.io/en/2.5/_modules/openpyxl/worksheet/cell_range.html" rel="nofollow noreferrer"><code>bounds</code></a>, <a href="https://openpyxl.readthedocs.io/en/2.5/_modules/openpyxl/worksheet/cell_range.html#CellRange.union" rel="nofollow noreferrer"><code>union</code></a>, and <a href="https://openpyxl.readthedocs.io/en/2.5/_modules/openpyxl/worksheet/cell_range.html#CellRange.issuperset" rel="nofollow noreferrer"><code>issuperset</code></a> are available in the openpyxl source - they're pretty cheap computationally.</p>
<p>For smaller ranges, it works very well. However, on larger ranges where a lot of the ranges are contiguous (i.e. unionable), the performance is atrocious:</p>
<pre class="lang-none prettyprint-override"><code>2018-11-02 10:55:13,943 Collapsing 1793 ranges for number_format: Accounting
2018-11-02 10:55:14,381 Combined 1793 ranges into 212, recursing to try again
2018-11-02 10:55:14,391 Combined 212 ranges into 24, recursing to try again
2018-11-02 10:57:28,691 Collapsing 510998 ranges for number_format: Accounting
2018-11-02 15:23:09,622 Combined 510998 ranges into 30069, recursing to try again
2018-11-02 15:23:10,711 Combined 30069 ranges into 5, recursing to try again
</code></pre>
<p>I logged the progress:</p>
<p><a href="https://i.stack.imgur.com/1KSOh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1KSOh.png" alt="enter image description here"></a></p>
<p>Is there some algorithmic improvement I can use here? 4 hours for just one of these larger regions is not desirable. My first thought is to work backwards through the list, so that there are fewer elements being reindexed with each <code>pop(*some_index*)</code>. I could additionally sort the input to ensure ranges with similar starting row (or column) are near other, which would mean the <code>for</code> loop over the slice could exit early (once the top left cells of compared ranges are no longer in the same row or column)</p>
<hr>
<p>Background</p>
<p>Since formatting information is only available as a cell-level parameter in openpyxl (each cell stores an index that points to an instance of the particular formatting object), I iterate through cell regions marked for export (the <code>a1</code>s below) and store the cell address in a dict whose keys are the hashed formatting object. A formatting specifier used in one of the <code>a1</code>s may be used in a different <code>a1</code> as well, so contents of the list <code>multi_cell_range</code> are not guaranteed to be contiguous. (They are guaranteed to be unique.)</p>
<pre class="lang-py prettyprint-override"><code>COORD = '{}{}'
result = {}
for a1, params in cell_styles.items(): # params is (dict{str: 2d sequence(str / object)})
min_c, min_r, _, _ = range_boundaries(a1)
for style_attr, rg in params.items():
style_dict = result.setdefault(style_attr, {})
for r, row in enumerate(rg):
for c, attr in enumerate(row):
val = attr if isinstance(attr, str) else attr._StyleProxy__target
multi_cell_range = style_dict.setdefault(val, [])
multi_cell_range.append(COORD.format(get_column_letter(c + min_c), r + min_r))
</code></pre>
<p>So the above would produce a <code>result</code> dict like </p>
<pre><code>{
"font": {
<Font1>: [
"A1", "B1", "C1", "D1", ...
"A2", "B2", "C2", "D2", ...
...
],
<Font2>: [
...
]
},
"alignment": {
<Alignment1>: [
"A1", "A2", "A3" ...
],
<Alignment2>: [
"B1", "B2", ...
]
...
}
</code></pre>
<p>I then convert each simple multi-cell range list into the <a href="https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.cell_range.html#openpyxl.worksheet.cell_range.MultiCellRange" rel="nofollow noreferrer"><code>MultiCellRange</code></a> class and "agglomerate" the A1 notations:</p>
<pre><code>for style_attr, style_dict in result.items():
for key in style_dict:
mcr = MultiCellRange(style_dict[key])
collapse_cellranges(mcr.ranges)
style_dict[key] = mcr
</code></pre>
| [] | [
{
"body": "<p>I was able to massively improve the performance by incorporating two changes:</p>\n\n<ol>\n<li>Work backwards, to avoid calling <code>pop(some_index)</code> mid-list. For a large <code>list</code>, mid-list pops are nasty.</li>\n<li>Create a lookup table with the relevant <code>CellRanges</code> t... | {
"AcceptedAnswerId": "207023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T21:44:43.930",
"Id": "206840",
"Score": "1",
"Tags": [
"python",
"array",
"excel",
"time-limit-exceeded"
],
"Title": "Combine contiguous spreadsheet cell references into larger ranges"
} | 206840 |
<p>Is there something terribly wrong with this implementation?</p>
<pre><code>template <class T>
constexpr inline std::size_t hash_combine(T const& v,
std::size_t const seed = {}) noexcept
{
return seed ^ (std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
}
template <typename T> struct hash;
template <typename ...T>
struct hash<std::tuple<T...>>
{
template <typename A1, typename ...A, std::size_t ...I>
static auto apply_tuple(std::tuple<A1, A...> const& t,
std::index_sequence<I...>) noexcept
{
if constexpr(sizeof...(A))
{
return hash_combine(std::get<0>(t),
hash<std::tuple<A const&...>>()({std::get<I + 1>(t)...})
);
}
else
{
return std::hash<std::remove_cv_t<std::remove_reference_t<A1>>>()(
std::get<0>(t));
}
}
auto operator()(std::tuple<T...> const& t) const noexcept
{
return apply_tuple(t,
std::make_index_sequence<sizeof...(T) - 1>()
);
}
};
</code></pre>
<p>EDIT: This is better, I think:</p>
<pre><code>template <typename ...T>
struct hash<std::tuple<T...>>
{
template <std::size_t ...I>
static auto apply_tuple(std::tuple<T...> const& t,
std::index_sequence<I...>)
{
std::size_t seed{};
return ((seed = hash_combine(std::get<I>(t), seed)), ...);
}
auto operator()(std::tuple<T...> const& t) const
{
return apply_tuple(t, std::make_index_sequence<sizeof...(T)>());
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T19:37:10.420",
"Id": "399210",
"Score": "0",
"body": "Care about editing code in your question. Otherwise, I didn't notice something wrong in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-0... | [
{
"body": "<p>Your code doesn't handle empty tuples gracefully. The first version generates a compilation error, and the second version returns <code>void</code>. For the first version, you can add an <code>apply_tuple</code> overload for empty tuples. For the second version, you can change</p>\n\n<pre><code... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T22:50:58.870",
"Id": "206844",
"Score": "2",
"Tags": [
"c++",
"c++17",
"hashcode"
],
"Title": "Yet another hash tuple in C++17"
} | 206844 |
<h2>Purpose</h2>
<p>The point of this mini project is to quickly gather data from a website's API and combine the collected DataFrames into a "master" DataFrame with all of the stocks I am interested in looking at. I do this using the <code>iexfinance</code> module. If needed, <a href="https://github.com/addisonlynch/iexfinance" rel="nofollow noreferrer">here is the code</a> behind <code>iexfinance</code>.</p>
<h2>Improvements?</h2>
<p>While this module does a great job of dealing with the API, I'm not sure my code is as fast as it could be. Because the <code>iexfinance</code> module uses <code>requests</code> to make GET requests, I believe there should be a faster way to asynchronously send GET requests instead of having to use <code>multiprocessing</code>. Below is my code:</p>
<pre><code>import pandas as pd
import numpy as np
from iexfinance import Stock
from multiprocessing import Pool
import os
def iex_get_stat(batch):
"""
:param batch: batch is a list of stock tickers (ex: ["AAPL", "MSFT", "TSLA"]
Gets and returns DataFrames of stats on a list of stocks
"""
frame = Stock(batch, output_format="pandas").get_key_stats().T
return frame
def get_stats(symbols):
"""
:param symbols: List of symbols (can only send 100 at a time,
so these may need to be broken up)
:return: Pandas DataFrame with stats
"""
symbols = [symbols[i : i + 99] for i in range(0, len(symbols), 99)]
frames = []
pool = Pool(processes=os.cpu_count())
frames.append(pool.starmap(iex_get_stat, [[batch] for batch in symbols]))
pool.close()
pool.join()
stats = pd.concat(frames[0])
return stats
if __name__ == "__main__":
symbols = ["AAPL", "TSLA", "MSFT"]
stats = get_stats(symbols)
print(stats)
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Your docstrings look a bit weird to me. The first line is usually a summary of what the function does. In your first function that line comes after the parameters and in the second one it does not exist at all. In <code>get_stats</code> when describing the parameter <code>symbols</code> ... | {
"AcceptedAnswerId": "206861",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T23:40:36.860",
"Id": "206847",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"multiprocessing"
],
"Title": "GET multiple data frames using external module's function that uses requests"
} | 206847 |
<p>Usually people recommend to never implement cryptographic algorithms yourself unless you are an expert in the field. This of course makes a lot of sense mainly because there are numerous things that can go wrong, resulting in a vulnerable implementation.</p>
<p>However, for learning purposes I decided to write an implementation of the <a href="https://en.wikipedia.org/wiki/XTEA" rel="noreferrer">XTEA block cipher</a> myself nonetheless. XTEA is a 64-bit block feistel cipher with a 128-bit key.</p>
<p>What can be improved in my implementation? Are there any major flaws?</p>
<p><strong>ISymmetricEncryptionProvider.cs</strong></p>
<pre><code>namespace Crypto
{
/// <summary>
/// Provides a base for symmetric encryption algorithms
/// </summary>
public interface ISymmetricEncryptionProvider
{
/// <summary>
/// Symmetric encryption routine
/// </summary>
/// <param name="data">The data that should get encrypted</param>
/// <returns>The encrypted data</returns>
byte[] Encrypt(byte[] data);
/// <summary>
/// Symmetric decryption routine
/// </summary>
/// <param name="data">The data that should get decrypted</param>
/// <returns>The decrypted data</returns>
byte[] Decrypt(byte[] data);
}
}
</code></pre>
<p><strong>XTEA.cs</strong></p>
<pre><code>using System;
using System.IO;
namespace Crypto
{
/// <summary>
/// Like TEA, XTEA is a 64-bit block Feistel cipher with a 128-bit key and a suggested
/// 64 rounds. Several differences from TEA are apparent, including a somewhat
/// more complex key-schedule and a rearrangement of the shifts, XORs, and additions.
///
/// More information can be found here:
/// + https://en.wikipedia.org/wiki/XTEA
/// + http://www.tayloredge.com/reference/Mathematics/TEA-XTEA.pdf
/// </summary>
public class XTEA : ISymmetricEncryptionProvider
{
/// <summary>
/// The 128 bit key used for encryption and decryption
/// </summary>
private readonly uint[] _key;
/// <summary>
/// The number of rounds, default is 32 because each iteration performs two Feistel-cipher rounds.
/// </summary>
private readonly uint _cycles;
/// <summary>
/// XTEA operates with a block size of 8 bytes
/// </summary>
private readonly uint _blockSize = 8;
/// <summary>
/// The delta is derived from the golden ratio where delta = (sqrt(2) - 1) * 2^31
/// A different multiple of delta is used in each round so that no bit of
/// the multiple will not change frequently
/// </summary>
private const uint Delta = 0x9E3779B9;
/// <summary>
/// Instantiate new XTEA object for encryption/decryption
/// </summary>
/// <param name="key">The encryption/decryption key</param>
/// <param name="cycles">Number of cycles performed, default is 32</param>
public XTEA(byte[] key, uint cycles = 32)
{
_key = GenerateKey(key);
_cycles = cycles;
}
/// <summary>
/// Calculates the next multiple of the block size of the input data because
/// XTEA is a 64-bit cipher.
/// </summary>
/// <param name="length">Input data size</param>
/// <returns>Input data extended to the next multiple of the block size.</returns>
private uint NextMultipleOfBlockSize(uint length)
{
return (length + 7) / _blockSize * _blockSize;
}
/// <summary>
/// Encrypts the provided data with XTEA
/// </summary>
/// <param name="data">The data to encrypt</param>
/// <returns>Encrypted data as byte array</returns>
public byte[] Encrypt(byte[] data)
{
var blockBuffer = new uint[2];
var dataBuffer = new byte[NextMultipleOfBlockSize((uint)data.Length + 4)];
var lengthBuffer = BitConverter.GetBytes(data.Length);
Buffer.BlockCopy(lengthBuffer, 0, dataBuffer, 0, lengthBuffer.Length);
Buffer.BlockCopy(data, 0, dataBuffer, lengthBuffer.Length, data.Length);
using (var memoryStream = new MemoryStream(dataBuffer))
using (var binaryWriter = new BinaryWriter(memoryStream))
for (uint i = 0; i < dataBuffer.Length; i += _blockSize)
{
blockBuffer[0] = BitConverter.ToUInt32(dataBuffer, (int) i);
blockBuffer[1] = BitConverter.ToUInt32(dataBuffer, (int) i + 4);
Encode(_cycles, blockBuffer, _key);
binaryWriter.Write(blockBuffer[0]);
binaryWriter.Write(blockBuffer[1]);
}
return dataBuffer;
}
/// <summary>
/// Decrypts the provided data with XTEA
/// </summary>
/// <param name="data">The data to decrypt</param>
/// <returns>The decrypted data as byte array</returns>
public byte[] Decrypt(byte[] data)
{
// Encrypted data size must be a multiple of the block size
if (data.Length % _blockSize != 0)
throw new ArgumentOutOfRangeException(nameof(data));
var blockBuffer = new uint[2];
var buffer = new byte[data.Length];
Buffer.BlockCopy(data, 0, buffer, 0, data.Length);
using (var memoryStream = new MemoryStream(buffer))
using (var binaryWriter = new BinaryWriter(memoryStream))
{
for (uint i = 0; i < buffer.Length; i += _blockSize)
{
blockBuffer[0] = BitConverter.ToUInt32(buffer, (int) i);
blockBuffer[1] = BitConverter.ToUInt32(buffer, (int) i + 4);
Decode(_cycles, blockBuffer, _key);
binaryWriter.Write(blockBuffer[0]);
binaryWriter.Write(blockBuffer[1]);
}
}
// Verify if length of output data is valid
var length = BitConverter.ToUInt32(buffer, 0);
VerifyDataLength(length, buffer.Length, 4);
// Trim first 4 bytes of output data
return TrimOutputData(length, buffer, 4);
}
/// <summary>
/// Removes the first n bytes from the buffer
/// </summary>
/// <param name="length">Length of the output buffer</param>
/// <param name="buffer">The output buffer</param>
/// <param name="trimSize">Number of bytes to trim from the start of the buffer</param>
/// <returns>Trimmed output buffer array</returns>
private byte[] TrimOutputData(uint length, byte[] buffer, int trimSize)
{
var result = new byte[length];
Buffer.BlockCopy(buffer, trimSize, result, 0, (int) length);
return result;
}
/// <summary>
/// Compares the length of the output data from a specified offset to the length of the buffer
/// </summary>
/// <param name="dataLength">Length of the output data</param>
/// <param name="bufferLength">Length of the buffer</param>
/// <param name="offset">The offset</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if buffer data is corrupted</exception>
private void VerifyDataLength(uint dataLength, int bufferLength, uint offset)
{
if (dataLength > bufferLength - offset)
throw new ArgumentOutOfRangeException(nameof(bufferLength));
}
/// <summary>
/// Transforms the key to uint[]
/// </summary>
/// <returns>Transformed key</returns>
private uint[] GenerateKey(byte[] key)
{
if (key.Length != 16)
throw new ArgumentOutOfRangeException(nameof(key));
return new[]
{
BitConverter.ToUInt32(key, 0), BitConverter.ToUInt32(key, 4),
BitConverter.ToUInt32(key, 8), BitConverter.ToUInt32(key, 12)
};
}
/// <summary>
/// TEA inplace encoding routine of the provided data array.
/// </summary>
/// <param name="rounds">The number of encryption rounds, default is 32.</param>
/// <param name="v">The data array containing two values.</param>
/// <param name="k">The key array containing 4 values.</param>
private void Encode(uint rounds, uint[] v, uint[] k)
{
uint sum = 0;
uint v0 = v[0], v1 = v[1];
for (int i = 0; i < rounds; i++)
{
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += Delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
}
v[0] = v0;
v[1] = v1;
}
/// <summary>
/// TEA inplace decoding routine of the provided data array.
/// </summary>
/// <param name="rounds">The number of encryption rounds, default is 32.</param>
/// <param name="v">The data array containing two values.</param>
/// <param name="k">The key array containing 4 values.</param>
private void Decode(uint rounds, uint[] v, uint[] k)
{
uint sum = Delta * rounds;
uint v0 = v[0], v1 = v[1];
for (int i = 0; i < rounds; i++)
{
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
sum -= Delta;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
}
v[0] = v0;
v[1] = v1;
}
}
}
</code></pre>
<p>Here is an example usage of the class:</p>
<pre><code>public static void Main(string[] args)
{
byte[] key = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
byte[] data = Encoding.UTF8.GetBytes("This is a message which will be encrypted with XTEA!");
var xtea = new XTEA(key);
var enc = xtea.Encrypt(data);
var dec = xtea.Decrypt(enc);
Console.WriteLine(Encoding.UTF8.GetString(dec));
Console.ReadKey();
}
</code></pre>
<p><strong>References</strong></p>
<p>Credit where credit belongs. During the writing of this class used the following websites/books as a guideline:</p>
<p><a href="http://www.tayloredge.com/reference/Mathematics/TEA-XTEA.pdf" rel="noreferrer">The Tiny Encryption Algorithm (TEA)</a></p>
<p><a href="https://gist.github.com/InfectedBytes/ff8d5de8592bfc711380801cb29b3915" rel="noreferrer">C# implementation of XTEA</a></p>
<p><a href="https://github.com/ercsoftworks/CarestiaXTEA" rel="noreferrer">C# CarestiaXTEA</a></p>
<p><a href="https://github.com/IU5HKU/XTEA" rel="noreferrer">C++ XTEA Implementation</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T12:40:40.987",
"Id": "399042",
"Score": "1",
"body": "I would add a method to fold/spindle/mutilate and generally munge up the key before deleting it. You might also automatically call that method when closing the class (if C# allo... | [
{
"body": "<p>The function you call <code>Encode</code> really seems to be your block encryption function, I would name it something more suggestive of that. As noted in the comments, it would be great it you offered modes other than ECB, it would be a good exercise to design that well. My main complaint is t... | {
"AcceptedAnswerId": "211360",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T00:39:02.137",
"Id": "206851",
"Score": "10",
"Tags": [
"c#",
"security",
"cryptography"
],
"Title": "XTEA Block Cipher"
} | 206851 |
<p>This is my first matrix class which I updated after already asking <a href="https://codereview.stackexchange.com/questions/206447/first-template-class-matrix-functions/206705#206705">here</a> already. </p>
<p>The updated code is below. </p>
<ul>
<li>Are there any suggestions regarding member function parameters?</li>
<li>Is there a convenient way to get a single function that allows to set/get with a single function? </li>
</ul>
<p>I considered returning a reference to the vector data member, but ultimately decided that is a terrible idea. </p>
<p>There are also a driver and a data file needed. </p>
<p><strong>#Matrix.h</strong></p>
<pre><code>#ifndef __MATRIX_H__
#define __MATRIX_H__
#include <vector>
#include <iostream>
template <typename T> class Matrix;
template <typename T> std::ostream& operator<<(std::ostream& os, const Matrix<T>& rhs);
template<typename T>
class Matrix {
private:
std::vector<T> data;
std::size_t rows;
std::size_t cols;
public:
Matrix();
Matrix(const std::vector<T> &, std::size_t rows, std::size_t cols);
void set(const std::vector<T> &, std::size_t rows, std::size_t cols);
//Matrix(const Matrix<T>&);
std::size_t getRows() const;
std::size_t getCols() const;
T at(const std::size_t &, const std::size_t &) const;
void at(const std::size_t &, const std::size_t &, const T &);
Matrix row(const std::size_t &) const;
Matrix col(const std::size_t &) const;
void print() const;
friend std::ostream& operator<< <>(std::ostream&, const Matrix<T> &);
Matrix mult(const Matrix<T> &) const;
Matrix concat(const Matrix<T> &) const;
Matrix stack(const Matrix<T> &) const;
Matrix kronecker(const Matrix<T> &) const;
T sum() const;
Matrix operator~() const; // transpose
Matrix operator*(const Matrix<T> &) const; // Dot product
//Matrix operator+() const; // not useful?
//elementwise operators
// (No multiplication. Reserved for dot product)
Matrix operator-() const; // negation of all elements
Matrix operator+(const Matrix<T> &) const; //
Matrix& operator+=(const Matrix<T> &); //
Matrix operator-(const Matrix<T> &) const; //
Matrix& operator-=(const Matrix<T> &); //
Matrix operator/(const Matrix<T> &) const; //
Matrix& operator/=(const Matrix<T> &); //
//Matrix& operator*=(const Matrix<T> &); //
//Scalar Operators
Matrix operator+(const T &) const; //
Matrix& operator+=(const T &); //
Matrix operator-(const T &) const; //
Matrix& operator-=(const T &); //
Matrix operator*(const T &) const; //
Matrix& operator*=(const T &); //
Matrix operator/(const T &) const; //
Matrix& operator/=(const T &); //
//logical Logical operators
bool operator==(const Matrix<T> &) const;
bool operator!=(const Matrix<T> &) const; //
};
/** Default Constructor
creates an empty matrix
*/
template <typename T>
Matrix<T>::Matrix() :
data(), rows(0), cols(0) {
}
/** Constructor
creates the matrix as the following:
@params elements, - the elements of the matrix in Row-major form
numRows, - the number of rows in the matrix
numCols; - the number of coumns in the matrix
*/
template <typename T>
Matrix<T>::Matrix(const std::vector<T> & elements, std::size_t numRows, std::size_t numCols) :
data(elements), rows(numRows), cols(numCols) {
if(data.size() != numRows * numCols)
throw std::invalid_argument("matrix dimensions and elments must be equal");
}
/** set
resets the matrix to the input
@params elements, - the elements of the matrix in Row-major form
numRows, - the number of rows in the matrix
numCols; - the number of coumns in the matrix
@return void; nothing to return
*/
template <typename T>
void Matrix<T>::set(const std::vector<T> & elements, std::size_t numRows, std::size_t numCols) {
rows = numRows;
cols = numCols;
data.clear();
for(unsigned int i = 0; i < elements.size(); i++) {
data.push_back(elements[i]);
}
}
/** transpose
Calculate transpose of matrix
@return matrix; the transpose of this matrix
*/
template <typename T>
Matrix<T> Matrix<T>::operator~() const {
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[(cols*(i%rows)+i/rows)]);
}
return Matrix<T>(vec, cols, rows);
}
/** operator(*) dot product
lhs * rhs;
https://en.wikipedia.org/wiki/Matrix_multiplication
calculate dot product of a matrix
@params rhs; the second matrix
@return matrix; the transformed product matrix
*/
template <typename T>
Matrix<T> Matrix<T>::operator*(const Matrix<T> & rhs) const {
if(cols != rhs.rows) {
throw std::invalid_argument("can not resolve dot product with operands");
}
std::vector<T> vec;
T sum = 0;
for(unsigned int j = 0; j < rows; j++) {
for(unsigned int k = 0; k < rhs.cols; k++) {
for(unsigned int i = 0; i < cols; i++) {
sum += data[i+j*cols] * rhs.data[k+i*rhs.cols];
}
vec.push_back(sum);
sum = 0;
}
}
return Matrix(vec,rows,rhs.cols);
}
/** uniary negation operator
calculate the matrix with all elements negated
@return matrix; the negated matrix
*/
template <typename T>
Matrix<T> Matrix<T>::operator-() const {
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(-data[i]);
}
return Matrix<T>(vec,rows,cols);
}
/** operator+ (add)
lhs + rhs;
elementwise adition of rhs to lhs
@params rhs; the matrix to add
@return matrix; the sum
*/
template <typename T>
Matrix<T> Matrix<T>::operator+(const Matrix<T> & rhs) const {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] + rhs.data[i]);
}
return Matrix<T>(vec,rows,cols);
}
/** operator- (subtract)
lhs - rhs;
elementwise subtraction of rhs from lhs
@params rhs; the matrix to subtract
@return matrix; the difference
*/
template <typename T>
Matrix<T> Matrix<T>::operator-(const Matrix<T> & rhs) const {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] - rhs.data[i]);
}
return Matrix<T>(vec,rows,cols);
}
/** operator+=
lhs + rhs;
elementwise adition of rhs to lhs
@params rhs; the matrix to add
@return matrix; the reference to this matrix
*/
template <typename T>
Matrix<T>& Matrix<T>::operator+=(const Matrix<T> & rhs) {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
data[i] += rhs.data[i];
}
return *this;
}
/** operator-=
lhs - rhs;
elementwise subtraction of rhs from lhs
@params rhs; the matrix to subtract
@return matrix; the reference to this matrix
*/
template <typename T>
Matrix<T>& Matrix<T>::operator-=(const Matrix<T> & rhs) {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
data[i] -= rhs.data[i];
}
return *this;
}
template <typename T>
Matrix<T> Matrix<T>::operator/(const Matrix<T> & rhs) const {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] / rhs.data[i]);
}
return Matrix<T>(vec,rows,cols);
}
template <typename T>
Matrix<T>& Matrix<T>::operator/=(const Matrix<T> & rhs) {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
data[i] /= rhs.data[i];
}
return *this;
}
template <typename T>
Matrix<T> Matrix<T>::operator+(const T & t) const {
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] + t);
}
return Matrix<T>(vec,rows,cols);
}
template <typename T>
Matrix<T>& Matrix<T>::operator+=(const T & t) {
for(unsigned int i = 0; i < data.size(); i++) {
data[i] += t;
}
return *this;
}
template <typename T>
Matrix<T> Matrix<T>::operator-(const T & t) const {
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] - t);
}
return Matrix<T>(vec,rows,cols);
}
template <typename T>
Matrix<T>& Matrix<T>::operator-=(const T & t) {
for(unsigned int i = 0; i < data.size(); i++) {
data[i] -= t;
}
return *this;
}
/** operator* (scalar multiplication)
M<T> * T;
calculate scalar product of a matrix
@params rhs; the scalar;
@return matrix; the transformed product matrix
*/
template <typename T>
Matrix<T> Matrix<T>::operator*(const T & t) const {
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] * t);
}
return Matrix<T>(vec,rows,cols);
}
template <typename T>
Matrix<T>& Matrix<T>::operator*=(const T & t) {
for(unsigned int i = 0; i < data.size(); i++) {
data[i] *= t;
}
return *this;
}
template <typename T>
Matrix<T> Matrix<T>::operator/(const T & t) const {
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] / t);
}
return Matrix<T>(vec,rows,cols);
}
template <typename T>
Matrix<T>& Matrix<T>::operator/=(const T & t) {
for(unsigned int i = 0; i < data.size(); i++) {
data[i] /= t;
}
return *this;
}
/** operator ==
elemetnwise comparison of two matrices of equal size
@params rhs; the second matrix
@return bool; true if same size and elements all equal
*/
template <typename T>
bool Matrix<T>::operator==(const Matrix<T> & rhs) const {
if(rows != rhs.rows || cols != rhs.cols) {
return false;
}
for(unsigned int i = 0; i < data.size(); i++) {
if(data[i] != rhs.data[i])
return false;
}
return true;
}
/** operator !=
elemetnwise comparison of two matrices of equal size
@params rhs; the second matrix
@return bool; false if same size and elements all equal
*/
template <typename T>
bool Matrix<T>::operator!=(const Matrix<T> & rhs) const {
if(rows != rhs.rows || cols != rhs.cols) {
return true;
}
for(unsigned int i = 0; i < data.size(); i++) {
if(data[i] != rhs.data[i])
return true;
}
return false;
}
/** ostream operator
adds elements to output stream
formatted
e11, e12
e21, e22
@params os, rhs; ostream refernece and matrix to output
@return os, ostream reference
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const Matrix<T> & rhs) {
for(unsigned int i = 0; i < rhs.data.size(); i++) {
os << rhs.data[i] << " ";
if((i+1)%rhs.cols == 0)
os << std::endl;
}
return os;
}
template <typename T>
void Matrix<T>::print() const {
for(unsigned int i = 0; i < data.size(); i++) {
std::cout << data[i] << ", ";
if((i+1) % cols == 0)
std::cout << std::endl;
}
}
template <typename T>
T Matrix<T>::sum() const {
T t = 0;
for(unsigned int i = 0; i < data.size(); i++) {
t += data[i];
}
return t;
}
/** multiplication (Hardamard Product)
https://en.wikipedia.org/wiki/Hadamard_product_(matrices)
calculate elemetnwise product of a matrix
@params rhs; the second matrix
@return matrix; the transformed product matrix
*/
template <typename T>
Matrix<T> Matrix<T>::mult(const Matrix<T> & rhs) const {
if(rows != rhs.rows || cols != rhs.cols) {
throw std::invalid_argument("matrices of unequal dimension!");
}
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i] * rhs.data[i]);
}
return Matrix<T>(vec,rows,cols);
}
/** Concat
append two matrices of equal row count
@params rhs; the matrix to concatanate
@return matrix; the contanated matrix
*/
template <typename T>
Matrix<T> Matrix<T>::concat(const Matrix<T> & rhs) const {
if(rows != rhs.rows)
return Matrix<T>(*this);
std::vector<T> vec;
for(unsigned int i = 0; i < rows; i++) {
for(unsigned int j = 0; j < cols; j++) {
vec.push_back(data[i*cols + j]);
}
for(unsigned int j = 0; j < rhs.cols; j++) {
vec.push_back(rhs.data[i*rhs.cols + j]);
}
}
return Matrix<T>(vec,rows,cols+rhs.cols);
}
/** stack
append two matrices of equal column count
@params rhs; the matrix to stack below
@return matrix; the lhs stacked ontop of rhs matrix
*/
template <typename T>
Matrix<T> Matrix<T>::stack(const Matrix<T> & rhs) const {
if(cols != rhs.cols)
return Matrix<T>(*this);
std::vector<T> vec;
for(unsigned int i = 0; i < data.size(); i++) {
vec.push_back(data[i]);
}
for(unsigned int i = 0; i < rhs.data.size(); i++) {
vec.push_back(rhs.data[i]);
}
return Matrix<T>(vec,rows+rhs.rows,cols);
}
/** Kronecker
https://en.wikipedia.org/wiki/Kronecker_product
calculate kroncker product of two matrices
@params rhs; the matrix operand
@return matrix; the Kronecker product matrix
*/
template <typename T>
Matrix<T> Matrix<T>::kronecker(const Matrix<T> & rhs) const {
std::vector<T> vec;
for(unsigned int i = 0; i < (rows*cols*rhs.rows*rhs.cols); i++) {
unsigned int j = (i/rhs.cols)%cols + (i/(cols*rhs.rows*rhs.cols))*cols; //iterate lhs in proper order
unsigned int k = (i%rhs.cols) + ((i / (cols * rhs.cols))%rhs.rows)*rhs.cols; //iterate rhs in proper order
//can use scalar multiplactions, matrix concat and stacking, but this is a single iteration through the vector.
//Kronecker iterates both matrices in a pattern relative to the large product matrix.
//std::cout << i << " : " << j << " : " << k << std::endl;
//std::cout << i << " : " << j << " : " << k << " : " << l << std::endl;
vec.push_back(data[j]*rhs.data[k]);
}
return Matrix<T>(vec,rows*rhs.rows,cols*rhs.cols);
}
template <typename T>
std::size_t Matrix<T>::getRows() const {
return rows;
}
template <typename T>
std::size_t Matrix<T>::getCols() const {
return cols;
}
template <typename T>
T Matrix<T>::at(const std::size_t & row,const std::size_t & col) const {
if(row > rows || col > cols) {
throw std::invalid_argument("Indices out of bounds!");
}
return data[row*cols+col];
}
template <typename T>
void Matrix<T>::at(const std::size_t & row,const std::size_t & col, const T & t) {
if(row > rows || col > cols) {
throw std::invalid_argument("Indices out of bounds!");
}
data[row*cols+col] = t;
}
template <typename T>
Matrix<T> Matrix<T>::row(const std::size_t & r) const {
if(r > rows)
throw std::invalid_argument("indices out of bounds!");
std::vector<T> subVec;
for(unsigned int i = r * cols; i < (r+1) * cols; i++) {
subVec.push_back(data[i]);
}
return Matrix<T>(subVec, 1, cols);
}
template <typename T>
Matrix<T> Matrix<T>::col(const std::size_t & c) const {
if(c > cols)
throw std::invalid_argument("indices out of bounds!");
std::vector<T> subVec;
for(unsigned int i = c; i < data.size(); i+=cols ) {
subVec.push_back(data[i]);
}
return Matrix<T>(subVec, rows, 1);
}
#endif
</code></pre>
<p><strong>Source.cpp</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include "Matrix.h"
#include "NeuralNet.h"
#include <string>
#include <fstream>
#include <sstream>
Matrix<float> loadData(std::string);
//bool saveData(Matrix, std::string); //Not implemented yet
void testMatrixClass(std::vector<Matrix<float>> &, std::vector<Matrix<int>> &);
bool loadTestData(std::string, std::vector<Matrix<float>> &, std::vector<Matrix<int>> &, std::vector<std::string> &); //for use with my test implementaiton
int main() {
std::vector<Matrix<float>> fMats;
std::vector<Matrix<int>> iMats;
std::vector<std::string> names;
if (!loadTestData("testData.data", fMats, iMats, names)) {
std::cout << "Error Loading Data";
return 0;
}
try {
testMatrixClass(fMats,iMats);
} catch (std::exception e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
//
Matrix<float> loadData(std::string fileName) {
//TODO: Implement file loading and data parsing
std::vector<float> vec;
std::ifstream inFile(fileName);
if(!inFile.is_open()) {
Matrix<float> matrix;
return matrix;
}
std::string row;
std::stringstream ss;
int rowCnt = 0;
int colCnt = 0;
while(inFile.good() && std::getline(inFile, row)) {
ss << row;
rowCnt++;
float temp;
while( ss >> temp ) {
colCnt++;
vec.push_back(temp);
}
ss.clear();
}
colCnt = colCnt / rowCnt;
return Matrix<float>(vec,rowCnt,colCnt);
}
//bool saveData(Matrix, std::string) {
//
// return true;
//}
bool loadTestData(std::string fileName, std::vector<Matrix<float>> & floatMat, std::vector<Matrix<int>> & intMat, std::vector<std::string> & description) {
std::vector<float> vec;
std::vector<int> intVec;
std::ifstream inFile(fileName);
if(!inFile.is_open()) {
return false;
}
std::string row;
std::stringstream ss;
int rowCnt = 0;
int colCnt = 0;
while(inFile.good() && std::getline(inFile, row)) {
if(row.find('=',0) != std::string::npos) {
colCnt = colCnt / rowCnt;
floatMat.push_back(Matrix<float>(vec,rowCnt,colCnt));
intMat.push_back(Matrix<int>(intVec,rowCnt,colCnt));
intVec.clear();
vec.clear();
rowCnt = 0;
colCnt = 0;
} else if(row.find("#",0) != std::string::npos) {
description.push_back(row.substr(1));
} else {
ss << row;
rowCnt++;
float temp;
while( ss >> temp ) {
colCnt++;
vec.push_back(temp);
intVec.push_back((int)temp);
}
}
ss.clear();
}
inFile.close();
return true;
}
void testMatrixClass(std::vector<Matrix<float>> & fmats, std::vector<Matrix<int>> & imats) {
std::vector<std::string> floatTest;
std::vector<bool> floatResults;
std::vector<std::string> intTest;
std::vector<bool> intResults;
floatTest.push_back("Constructor Test");
bool flag = true;
for(int i = 0; i < 12; i++) {
if((i+1) != fmats[0].at( i / fmats[0].getCols(), i % fmats[0].getCols()))
flag = false;
}
floatResults.push_back(flag);
floatTest.push_back("Copy Constructor Test");
floatResults.push_back(Matrix<float>(fmats[0]) == fmats[0]);
floatTest.push_back("Transpose test");
floatResults.push_back(fmats[1] == ~fmats[0]);
floatTest.push_back("Dot Product");
floatResults.push_back(fmats[2] * fmats[3] == fmats[4]);
floatTest.push_back("Dot Product");
floatResults.push_back(~fmats[3] * ~fmats[2] == ~fmats[4]);
floatTest.push_back("add");
floatTest.push_back("sub");
floatTest.push_back("mult");
floatTest.push_back("div");
floatResults.push_back(fmats[5] + fmats[6] == fmats[7]);
floatResults.push_back(fmats[5] - fmats[6] == fmats[8]);
floatResults.push_back(fmats[5].mult(fmats[6]) == fmats[9]); //hadamard multiplcation (elementwise)
floatResults.push_back(fmats[5] / fmats[6] == fmats[10]);
floatTest.push_back("scalar add");
floatTest.push_back("scalar sub");
floatTest.push_back("scalar mult");
floatTest.push_back("scalar div");
floatResults.push_back(fmats[5] + 2 == fmats[11]);
floatResults.push_back(fmats[5] - 2 == fmats[12]);
floatResults.push_back(fmats[5] * 2 == fmats[13]);
floatResults.push_back(fmats[5] / 2 == fmats[14]);
floatTest.push_back("== fail test");
floatTest.push_back("!= test");
floatTest.push_back("!= fail test");
floatResults.push_back(!(fmats[0] == fmats[1]));
floatResults.push_back(fmats[0] != fmats[1]);
floatResults.push_back(!(fmats[1] != fmats[1]));
floatTest.push_back("element read");
floatResults.push_back(fmats[15].at(0,2) == 2 && fmats[15].at(1,0) == 2 && fmats[15].at(3,1) == fmats[15].at(2,3));
fmats[15].at(0, 2, 0.0f);
fmats[15].at(1, 0, 0.0f);
fmats[15].at(3, 1, 0.0f);
fmats[15].at(2, 3, 0.0f);
floatTest.push_back("element access");
floatResults.push_back(fmats[15].at(0,2) == 0);
floatTest.push_back("element access");
floatResults.push_back(fmats[16] == fmats[15]);
floatTest.push_back("negation");
floatResults.push_back(-fmats[16] == fmats[17]);
floatTest.push_back("Fun");
floatResults.push_back(fmats[16] * fmats[18] == fmats[18]);
floatTest.push_back("+= return ref");
fmats[5] += fmats[5];
floatResults.push_back(fmats[13] == fmats[5]);
intTest.push_back("Constructor Test");
flag = true;
for(int i = 0; i < 12; i++) {
if((i+1) != imats[0].at( i / imats[0].getCols(), i % imats[0].getCols()))
flag = false;
}
intResults.push_back(flag);
intTest.push_back("Copy Constructor Test");
intResults.push_back(Matrix<int>(imats[0]) == imats[0]);
intTest.push_back("Transpose test");
intResults.push_back(imats[1] == ~imats[0]);
intTest.push_back("Dot Product");
intResults.push_back(imats[2] * imats[3] == imats[4]);
intTest.push_back("Dot Product");
intResults.push_back(~imats[3] * ~imats[2] == ~imats[4]);
intTest.push_back("Matrix add");
intTest.push_back("Matrix sub");
intTest.push_back("Matrix mult (Hadamard)");
intTest.push_back("Matrix div");
intResults.push_back(imats[5] + imats[6] == imats[7]);
intResults.push_back(imats[5] - imats[6] == imats[8]);
intResults.push_back(imats[5].mult(imats[6]) == imats[9]); //hadamard multiplcation (elementwise)
intResults.push_back(imats[5] / imats[6] == imats[10]);
intTest.push_back("scalar add");
intTest.push_back("scalar sub");
intTest.push_back("scalar mult");
intTest.push_back("scalar div");
intResults.push_back(imats[5] + 2 == imats[11]);
intResults.push_back(imats[5] - 2 == imats[12]);
intResults.push_back(imats[5] * 2 == imats[13]);
intResults.push_back(imats[5] / 2 == imats[14]);
intTest.push_back("== fail test");
intTest.push_back("!= test");
intTest.push_back("!= fail test");
intResults.push_back(!(imats[0] == imats[1]));
intResults.push_back(imats[0] != imats[1]);
intResults.push_back(!(imats[1] != imats[1]));
intTest.push_back("element read");
intResults.push_back(imats[15].at(0,2) == 2 && imats[15].at(1,0) == 2 && imats[15].at(3,1) == imats[15].at(2,3));
imats[15].at(0, 2, 0);
imats[15].at(1, 0, 0);
imats[15].at(3, 1, 0);
imats[15].at(2, 3, 0);
intTest.push_back("element access");
intResults.push_back(imats[15].at(0,2) == 0);
intTest.push_back("element access");
intResults.push_back(imats[16] == imats[15]);
intTest.push_back("negation");
intResults.push_back(-imats[16] == imats[17]);
intTest.push_back("Fun");
intResults.push_back(imats[16] * imats[18] == imats[18]);
intTest.push_back("+= return ref");
imats[5] += imats[5];
intResults.push_back(imats[13] == imats[5]);
std::cout << std::endl << std::string(10,' ') << "Integers" << std::string(30,' ') << "Floats" << std::endl;
for(unsigned int i = 0; i < intTest.size(); i++) {
std::cout << intTest[i] << std::string(24 - intTest[i].length(),'_') << ": ";
if(intResults[i])
std::cout << "passed. ";
else
std::cout << "failed. ";
std::cout << floatTest[i] << std::string(24 - floatTest[i].length(),'_') << ": ";
if(floatResults[i])
std::cout << "passed." << std::endl;
else
std::cout << "failed." << std::endl;
}
std::cout << std::endl << "Thanks mang!" << std::endl;
return;
}
</code></pre>
<p><strong>testData.data</strong></p>
<pre><code>#Con
1 2 3 4
5 6 7 8
9 10 11 12
=
#~Con (transpose)
1 5 9
2 6 10
3 7 11
4 8 12
=
#dLHS
2 1
1 2
=
#dRHS
1 2 2 1
2 1 1 2
=
#dLHS * dRHS (dot)
4 5 5 4
5 4 4 5
=
#LHS
1 2 3
3 2 1
1 3 1
=
#RHS
1 1 2
2 1 1
1 1 1
=
#LHS + RHS
2 3 5
5 3 2
2 4 2
=
#LHS - RHS
0 1 1
1 1 0
0 2 0
=
#LHS o RHS (Hadamard)
1 2 6
6 2 1
1 3 1
=
#LHS / RHS
1 2 1.5
1.5 2 1
1 3 1
=
#LHS + 2
3 4 5
5 4 3
3 5 3
=
#LHS - 2
-1 0 1
1 0 -1
-1 1 -1
=
#LHS * 2
2 4 6
6 4 2
2 6 2
=
#LHS / 2
0.5 1 1.5
1.5 1 0.5
0.5 1.5 0.5
=
#Element Access
1 0 2 0
2 1 0 2
0 0 1 2
0 2 0 1
=
#ResMat
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
=
#-ResMat
-1 0 0 0
0 -1 0 0
0 0 -1 0
0 0 0 -1
=
#Fun
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
=
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T20:44:15.287",
"Id": "399085",
"Score": "0",
"body": "“I considered returning a reference to the vector data member, but ultimately decided that is a terrible idea.” Why? This is what `std::vector` does, and many other standard cont... | [
{
"body": "<p>There's a lot of code here to review, so this is likely not going to be a complete review.</p>\n\n<h1>Data access</h1>\n\n<p>I'll start with one of your questions:</p>\n\n<blockquote>\n <p>Is there a convenient way to get a single function that allows to set/get with a single function?</p>\n</blo... | {
"AcceptedAnswerId": "206915",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T02:18:48.297",
"Id": "206852",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"matrix",
"template"
],
"Title": "Template matrix class, second version"
} | 206852 |
<p>I made this to-do list since I never seriously used jQuery (in particular way AJAX) and I need this kind of script for a project that I'm working on. Principal features:</p>
<ul>
<li>Use of a database to manage to-do list values (using PDO).</li>
<li>Possibility to add/delete to-do list values.</li>
<li>Possibility to edit to-do list value dblclicking on the text value.</li>
<li>Possibility to set a "status" for a specific value (completed and tested).</li>
<li>To-do list values can be separeted for category/type.</li>
<li>AJAX functionality.</li>
</ul>
<p>I want to know if all my methods applied to achieve this result are right and mostly well written, particularly for the jQuery/AJAX part. Could I write better some logic of the PHP code? Could I avoid some useless code in the jQuery/AJAX part? Every comment on the code would be appreciated.</p>
<p><strong>load.initialize.php</strong></p>
<pre><code><?php
$database = [
'name' => "name",
'user' => "user",
'pass' => "idk",
];
try
{
$dsn = "mysql:host=127.0.0.1;dbname={$database['name']};";
$dbh = new PDO($dsn, $database['user'], $database['pass']);
# Disable emulation of prepared statements, use REAL prepared statements instead.
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
# Set charset to uf8 (using query, that's the only way that make work SET NAMES).
$dbh->query("SET NAMES utf8mb4");
}
catch (PDOException $e)
{
echo 'An error occured: ' . $e->getMessage();
}
</code></pre>
<p><strong>index.php</strong> [top of the file]</p>
<pre><code><?php
require_once('load.initialize.php');
// Delete to-do list value.
if (isset($_POST['delete']) && is_numeric($_POST['delete']))
{
$stmt = $dbh->query("DELETE FROM tl_main WHERE id = {$_POST['delete']}");
if ($stmt)
{
$json_data['action'] = true; # true;
}
}
// Edit to-do list value.
if (isset($_POST['edited_text']) && isset($_POST['value']) && is_numeric($_POST['value']))
{
$stmt = $dbh->prepare("UPDATE tl_main SET text = :text, edit_date = NOW() WHERE id = {$_POST['value']}");
$stmt->bindParam(':text', $_POST['edited_text'], PDO::PARAM_STR);
if ($stmt->execute())
{
$stmt = $dbh->query("SELECT edit_date FROM tl_main WHERE id = {$_POST['value']} LIMIT 1");
$json_data['action'] = true; # true;
$json_data['edit_date'] = date("d/m/y H:i", strtotime($stmt->fetchColumn())); # Send it directly formatted as we setted in the page (instead of formatting it in jQuery)
}
}
// Add value to the to-do list
if (isset($_POST['value_text']) && !empty($_POST['value_text']) && isset($_POST['type']) && is_numeric($_POST['type']))
{
$stmt = $dbh->prepare("INSERT INTO tl_main (type, text, added_date) VALUES({$_POST['type']}, :text, NOW())");
$stmt->bindParam(':text', $_POST['value_text'], PDO::PARAM_STR);
if ($stmt->execute())
{
$json_data['action'] = true; # true;
}
}
// Set to-do list status to specific value.
if (isset($_POST['status']) && isset($_POST['value']) && is_numeric($_POST['value']))
{
switch ($_POST['status'])
{
case "completed":
$column_date = "completed_date";
$status = "completed = 1, tested = 0, completed_date = NOW()";
break;
case "tested":
$column_date = "tested_date";
$status = "completed = 0, tested = 1, tested_date = NOW()";
break;
case "indev":
$status = "completed = 0, tested = 0, completed_date = DEFAULT, tested_date = DEFAULT";
}
if ($status) {
$stmt = $dbh->query("UPDATE tl_main SET {$status} WHERE id = {$_POST['value']}");
if ($stmt)
{
if (isset($column_date))
{
$stmt = $dbh->query("SELECT {$column_date} FROM tl_main WHERE id = {$_POST['value']} LIMIT 1");
$json_data[$column_date] = date("d/m/y H:i", strtotime($stmt->fetchColumn())); # Send it directly formatted as we setted in the page (instead of formatting it in jQuery)
}
$json_data['action'] = true; # true;
}
}
}
// Display json infos for AJAX call for to-do list actions (delete, edit, add, status).
if (isset($_POST['delete']) || isset($_POST['edited_text']) || isset($_POST['value_text']) || isset($_POST['status']))
{
if (!isset($json_data))
$json_data['action'] = false;
header('Content-type: application/json');
echo json_encode($json_data);
exit;
}
// Fetch to-do list types.
$sql = "SELECT * FROM tl_types";
$types = $dbh->query($sql)->fetchAll();
// Fetch to-do list content.
$sql = "SELECT * FROM tl_main ORDER BY added_date DESC";
$todolist = $dbh->query($sql)->fetchAll();
// Apply/Fetch some operations to the todolist array.
foreach ($todolist as &$value)
{
// Formatting the text content.
// Catching http/https links.
$pattern = "@(http(s)?)?(://)+(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,).\s])@";
$value['text'] = preg_replace($pattern, '<a href="$0" target="_blank">$0</a>', $value['text']);
// Formatting datetimes.
$datetimes = [
'added_date' => $value['added_date'],
'edit_date' => $value['edit_date'],
'completed_date' => $value['completed_date'],
'tested_date' => $value['tested_date']
];
foreach ($datetimes as $key => $datetime)
{
$value[$key] = strtotime($value[$key]);
}
// Build an array with type => array(edit_dates).
// Needed after for get the highest last edit for each type.
$type_edits[$value['type']][] = $value['edit_date'];
}
// Get in an array the highest edit date of the to-do list for every type in order to determine the last edit for each type.
ksort($type_edits); # A whim just to have the array with edit dates ordered by type id.
foreach ($type_edits as $type => $edits)
{
$last_edit[$type] = date("d F H:i", max($edits));
}
// Check if last_edit array have missing types due to no content for the specific type (and so couldn't catch the last edit).
foreach ($types as $type)
{
if (!array_key_exists($type['id'], $last_edit))
{
$last_edit[$type['id']] = "foo";
}
}
</code></pre>
<p><strong>index.php</strong> [bottom of the file]</p>
<pre><code><body>
<div class="background"></div>
<div id="container">
<ul id="menu">
<?php foreach ($types as $type): ?>
<li><a href="#<?= $type['name'] ?>"><?= $type['name'] ?></a></li>
<?php endforeach; ?>
<li id="special">[ <a class="toggle_all" style="cursor:pointer">toggle all</a> ]</li>
</ul>
<fieldset id="legend">
<legend>Legend</legend>
<div id="completed" class="row">
<span class="appearance"></span>
<span class="explanation">Completed</span>
</div>
<div id="tested" class="row">
<span class="appearance"></span>
<span class="explanation">Tested</span>
</div>
<div id="indev" class="row">
<span class="appearance"></span>
<span class="explanation">In development</span>
</div>
<div id="edited" class="row">
<span class="explanation">edited recently <span style="font-size:12px">(2 days)</span></span>
</div>
</fieldset>
<?php foreach ($types as $type): ?>
<div id="<?= $type['name'] ?>" class="tab">
<div class="title group">
<div class="float_left">
<span class="main"><?= $type['name'] ?></span>
<span class="link">[ <a class="toggle" style="cursor:pointer">toggle</a> ]</span>
<span class="link">[ <a href="#<?= $type['name'] ?>">redirect</a> ]</span>
</div>
<div class="float_right">
<span class="last_edit">Last edit: <?= $last_edit[$type['id']] ?></span>
</div>
</div>
<table>
<tr>
<th class="subject"><span>Subject</span></th>
<th>Added</th>
<th>Mod</th>
</tr>
<tr>
<td class="subject"><textarea placeholder="Add new value..."></textarea></td>
<td class="date">00/00/00 00:00</td>
<td class="mod"><a id="add" data-type="<?= $type['id'] ?>"><i class="fas fa-plus"></i></a></td>
</tr>
<?php foreach ($todolist as $content): ?>
<?php if ($content['type'] === $type['id']): ?>
<?php if ($content['completed']): ?>
<tr class="completed">
<?php elseif ($content['tested']): ?>
<tr class="tested">
<?php else: ?>
<tr>
<?php endif; ?>
<td class="subject">
<div<?= ($content['edit_date'] > strtotime('-2 days')) ? ' style="font-style:italic"' : "" ?> data-value="<?= $content['id'] ?>" data-editable><?= $content['text'] ?></div>
</td>
<td class="date">
<span class="showhim"><?= date("d/m/y H:i", $content['added_date']) ?></span>
<div class="showme">
<ul>
<li><i class="fas fa-pencil-alt"></i> <span id="edit_date"><?= date("d/m/y H:i", $content['edit_date']) ?></span></li>
<li><i class="far fa-thumbs-up"></i> <span id="completed_date"><?= date("d/m/y H:i", $content['completed_date']) ?></span></li>
<li><i class="fas fa-check"></i> <span id="tested_date"><?= date("d/m/y H:i", $content['tested_date']) ?></span></li>
</ul>
</div>
</td>
<td class="mod">
<?php if ($content['completed']): ?>
<a id="status" data-status="tested" data-value="<?= $content['id'] ?>"><i class="fas fa-check"></i></a>
<?php elseif ($content['tested']): ?>
<a id="status" data-status="indev" data-value="<?= $content['id'] ?>"><i class="fas fa-undo-alt"></i></a>
<?php else: ?>
<a id="status" data-status="completed" data-value="<?= $content['id'] ?>"><i class="far fa-thumbs-up"></i></a>
<?php endif; ?>
<a id="delete" data-value="<?= $content['id'] ?>"><i class="far fa-trash-alt"></i></a>
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</table>
</div>
<?php endforeach; ?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="assets/general.js"></script>
</body>
</code></pre>
<p><strong>general.js</strong> [all AJAX requests]</p>
<pre><code>// Return window confirm() method for ajax requests.
function ajax_confirm(request) {
return confirm("Are you sure?!\nAJAX request: " + request);
}
// Toggle specific table.
$('.toggle').on('click', function() {
$(this).closest('.title').next('table').toggle();
});
// Toggle all tables.
$('.toggle_all').on('click', function() {
$('table').toggle();
});
// AJAX POST request in order to delete a specific value.
$('td.mod #delete').on('click', function() {
// Denied confirm alert doesn't run the script.
if (!ajax_confirm('delete')) return;
var $this = $(this);
var request = {
'delete': $this.data('value')
};
var posting = $.post(window.location, request, 'json');
posting.done(function(data) {
// Check if error query occurs.
if (!data.action) return;
$this.closest('tr').hide('fast', function() {
$this.closest('tr').remove();
});
})
});
// AJAX POST request in order to edit a specific value.
$('table').on('dblclick', 'td div[data-editable]', function() {
var $this = $(this);
var $textarea = $('<textarea />').height($this.height()).val($this.text());
$this.replaceWith($textarea);
var save = function() {
// Denied confirm alert doesn't send the AJAX POST request.
// Text has not changed doesn't send the AJAX POST request.
if (!ajax_confirm('edit') || $textarea.val() == $this.text()) {
$textarea.replaceWith($this);
return;
}
var request = {
'edited_text': $textarea.val(),
'value': $this.data('value')
};
var posting = $.post(window.location, request, 'json');
posting.done(function(data) {
// Check if error query occurs.
if (!data.action) {
alert(data);
$textarea.replaceWith($this);
return;
}
$div = $this.text($textarea.val()).css('font-style', 'italic')
$textarea.replaceWith($div);
$this.closest('tr').find('span#edit_date').text(data.edit_date);
});
};
/**
We're defining the callback with `one`, because we know that
the element will be gone just after that, and we don't want
any callbacks leftovers take memory.
Next time `div` turns into `textarea` this single callback
will be applied again.
*/
$textarea.one('blur', save).focus();
});
// AJAX POST request in order to add a value.
$('td.mod #add').on('click', function() {
// Denied confirm alert doesn't run the script.
if (!ajax_confirm('add')) return;
var $this = $(this);
var $textarea = $this.closest('tr').find('textarea');
// Check if textarea is empty
if (!$.trim($textarea.val())) {
$this.closest('table').before('<div id="error" class="notice" style="display:none">Please fill out the textarea value.</div>');
$('#error').stop(true).fadeIn().delay(5000).fadeOut(function() {
$('#error').remove();
});
return;
}
var request = {
'value_text': $textarea.val(),
'type': $this.data('type')
};
var posting = $.post(window.location, request, 'json');
posting.done(function(data) {
// Check if error query occurs.
if (!data.action) return;
$this.closest('table').before('<div id="success" class="notice" style="display:none">Value added succesfully, refresh the page to view it.</div>');
$('#success').stop(true).fadeIn().delay(5000).fadeOut(function() {
$('#success').remove();
});
// Reset textarea value
$textarea.val('');
});
});
// AJAX POST request in order to set the status of a specific value.
$('td.mod #status').on('click', function() {
// Denied confirm alert doesn't run the script.
if (!ajax_confirm('status')) return;
var $this = $(this);
var request = {
'status': $this.data('status'),
'value': $this.data('value')
};
var posting = $.post(window.location, request, 'json');
posting.done(function(data) {
// Check if error query occurs.
if (!data.action) return;
switch (request.status) {
case "completed":
/*
* If completed:
* Add completed class to tr.
* Update data-status to the next status (tested).
* Update icon class to the next status (tested) icon.
* Update completed datetime.
*/
$this.closest('tr').addClass('completed');
$this.data('status', 'tested');
$this.children('svg').attr('data-prefix', 'fas').attr('data-icon', 'check');
$this.closest('tr').find('span#completed_date').text(data.completed_date);
break;
case "tested":
/*
* If tested:
* Remove completed class from tr. / Add tested class to tr.
* Update data-status to the next status (indev).
* Update icon class to the next status (indev) icon.
* Update tested datetime.
*/
$this.closest('tr').removeClass('completed');
$this.closest('tr').addClass('tested');
$this.data('status', 'indev');
$this.children('svg').attr('data-prefix', 'fas').attr('data-icon', 'undo-alt');
$this.closest('tr').find('span#tested_date').text(data.tested_date);
break;
case "indev":
/*
* If in-dev:
* Remove tested class from tr. / No need to add class since indev take default background-color.
* Update data-status to the next status (completed).
* Update icon class to the next status (completed) icon.
* Remove completed and tested datetime.
*/
$this.closest('tr').removeClass('tested');
$this.data('status', 'completed');
$this.children('svg').attr('data-prefix', 'far').attr('data-icon', 'thumbs-up');
$this.closest('tr').find('span#completed_date').text("foo");
$this.closest('tr').find('span#tested_date').text("foo");
break;
}
})
});
</code></pre>
<p>If can be useful, the two tables that I used.
tl_main to store all the values, tl_types to list the categories.</p>
<pre><code>CREATE TABLE IF NOT EXISTS `tl_main` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type` tinyint(3) unsigned NOT NULL,
`text` mediumtext CHARACTER SET utf8 NOT NULL,
`added_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`edit_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`completed_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`tested_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`completed` tinyint(1) NOT NULL DEFAULT '0',
`tested` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=87 ;
CREATE TABLE IF NOT EXISTS `tl_types` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
</code></pre>
| [] | [
{
"body": "<h2>General feedback</h2>\n\n<p>Overall this code looks a bit repetitive - especially the PHP in <strong>index.php</strong> [top of the file] and the Javascript in general.js. Common lines could be abstracted into functions, and OOP approaches might make things easier to clean up, as well as allow fo... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T02:19:28.457",
"Id": "206853",
"Score": "4",
"Tags": [
"javascript",
"php",
"jquery",
"ajax",
"to-do-list"
],
"Title": "Effective to-do list in PHP and jQuery AJAX"
} | 206853 |
<p>I am working on an interview question where I need to return the k most frequent elements given a non-empty array of integers.</p>
<p>Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]</p>
<p>Here is my code:</p>
<pre><code> public static void main(String[] args) {
System.out.println(topKFrequent(new int[] {1, 1, 1, 2, 2, 3, 3}, 1));
}
private static List<Integer> topKFrequent(int[] nums, int k) {
// freq map
Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
for (int n : nums) {
freq.put(n, freq.getOrDefault(n, 0) + 1);
}
// bucket sort on freq
List<Integer>[] bucket = new ArrayList[nums.length + 1];
for (int i = 0; i < bucket.length; i++)
bucket[i] = new ArrayList<>();
for (int key : freq.keySet()) {
bucket[freq.get(key)].add(key);
}
// gather result
List<Integer> res = new ArrayList<>();
for (int i = bucket.length - 1; i >= 0; i--) {
res.addAll(bucket[i]);
if (res.size() >= k)
break;
}
return res;
}
</code></pre>
<p>I wanted to check whether there is any improvement/optimization can be made in this code?</p>
| [] | [
{
"body": "<p>Instead of looping over the <code>freq.keySet</code>, I recommend using <code>freq.forEach((k, v) -> bucket[v].add(k))</code>. This avoids the map lookups. In your current code, for each key you do a search in the map, which takes time. By using <code>forEach</code>, this additional search is a... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T06:46:11.183",
"Id": "206855",
"Score": "2",
"Tags": [
"java",
"algorithm",
"interview-questions",
"statistics"
],
"Title": "Top K frequent elements"
} | 206855 |
<p>I was trying to wrap a Logback logger in order to provide some handy methods and already defined default keys of the logged json output and I came up with something like this. </p>
<p>Do you spot any problem with it, or do you have any suggestion?</p>
<pre><code>public class Log {
private Logger logger = LoggerFactory.getLogger("jsonLogger");
private String msg;
private long start;
private Map<String, Object> kvs;
private Log(String msg) {
this.msg = msg;
this.start = System.currentTimeMillis();
this.kvs = new HashMap<>();
}
public static Log msg(String msg) {
return new Log(msg);
}
public Log kv(String key, Object value) {
kvs.put(key, value);
return this;
}
public void log() {
kvs.put("elapsed", System.currentTimeMillis() - start);
List<StructuredArgument> args = new ArrayList<>();
for (String k : kvs.keySet()) {
args.add(StructuredArguments.kv(k, kvs.get(k)));
}
logger.info(msg, args.toArray());
}
}
</code></pre>
<p>In this way you can log just a message, custom key-values and have a way to keep track of the execution between a function:</p>
<pre><code>// just a message
Log.msg("my message").log();
// message with custom kv or complex objects
Log.msg("my message").kv("foo", "bar").kv("arr", new String[]{"a", "b", "c"}).log();
// elapsed time
Log logger = Log.msg("my message").kv("foo", "bar");
Thread.sleep(1240);
logger.log();
</code></pre>
| [] | [
{
"body": "<p>i do not think this is really a good idea (sorry to say that)...</p>\n\n<p>why is is not a good idea? it's breaking the concept of segregaton of concerns:</p>\n\n<ol>\n<li>a Logger is responsible for logging</li>\n<li>a Profiler is responsible for measuring execution time</li>\n<li>a Logger is NOT... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T09:56:57.093",
"Id": "206860",
"Score": "0",
"Tags": [
"java",
"logging",
"fluent-interface",
"logback"
],
"Title": "Fluent interface for Logger"
} | 206860 |
<p>I am designing a website on which users can configure (CRUD) various objects which are mutually dependent upon other types. I am preventing a cascade delete, so let's say a <code>Team</code> is created in the database and some <code>Players</code> are created associated with that team (by ForeignKey) then the team can't be deleted.</p>
<p>For a user experience my plan is the following:</p>
<ol>
<li><p>Have a validator on the javascript client side as pre screening so the user doesnt expect to be able to delete objects that they shouldnt be allowed to.</p></li>
<li><p>Have code on the server side that returns a result even if JS fails and database integrity is compromised.</p></li>
</ol>
<p>The Javascript pre-screening looks like this, consider a delete button that is only visible and actionable if certain conditions are met:</p>
<pre><code><button class="btn" v-on:click="delete_()"
v-bind:class="{'btn-inactive': selected_team.id == '' || selected_team.members != 0}"
>Delete</button>
// in script..
delete_: function() {
var cb = function(data) {
this.$emit('refresh','');
};
this.ajax_($API_SCRIPT_ROOT + '/team', 'delete', this.selected_team, cb);
this.display = 'main';
},
</code></pre>
<p>AJAX will refresh the data on success, or on fail update an error message returned by the API.</p>
<p>The server side looks like this:</p>
<pre><code>def delete_user_resource(kind, user_id, resource_id):
"""
Deletes an existing resource
Args:
kind (str): the class of resource to be created, must be permissible for the specific ``User`` subclass.
(internal)
user_id (int): the primary key of the ``User`` creating the resource. (internal)
resource_id (int): the primary key of the resource class. (internal)
**kwargs: all required additional args for creation are specified in the docstring for underlying resource
class. (external)
Returns:
tuple: success boolean, string representation of state.
"""
resource = read_user_resource(kind, user_id, resource_id)
db.session.delete(resource)
try:
db.session.commit()
return True, resource.__repr__()
except IntegrityError as e:
db.session.rollback()
return False, e.statement
@api_0.route('/team', methods=['DELETE'])
@login_required
def team_delete():
user_args = {
"id": fields.Int(required=True),
}
kwargs = flaskparser.parser.parse(user_args, request)
result = delete_user_resource(kind='team', user_id=current_user.id, resource_id=kwargs['id'])
if result[0]:
return jsonify({'result': 'SUCCESS', 'description': result[1]}), 201
else:
return jsonify({'result': 'FAILED', 'description': result[1]}), 400
</code></pre>
<p>Here is the function that performs a security check for read access to a resource:</p>
<pre><code>def read_user_resource(kind, user_id, resource_id):
"""
Read a resource specific to the given ``User``.
Args:
kind (str): the class of resource to be created, must be permissible for the specific ``User`` subclass.
(internal)
user_id (int): the primary key of the ``User`` creating the resource. (internal)
resource_id (int): the primary key of the resource class specifed by kind. (internal)
Returns:
object: specific resource identified by unique id.
"""
user = User.query.filter(User.id == user_id).one()
Resource = RESOURCES2[user.type][kind]
resource = Resource.query.filter(Resource.id == resource_id).one_or_none()
if resource.organiser_team_id != user.organiser_team_id:
# security error since resource does not belong to authorising user
return None
return resource
</code></pre>
<p>I think this seems a fairly reasonably and decoupled (DRY) way of coding this that is potentially testable and maintainable. Do you agree or are there gaping holes which will cause problems later?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T10:52:03.173",
"Id": "206864",
"Score": "1",
"Tags": [
"python",
"ajax",
"rest",
"user-interface",
"flask"
],
"Title": "Deletion button on a website that enforces database integrity"
} | 206864 |
<p>This simple Python code I wrote for a problem asked during an interview. The problem statement is:</p>
<blockquote>
<p>Given a tuple (a, b), transform this into (c, d) by applying any of the two below operations multiple time in any order you like:</p>
<ol>
<li>(a, b) -> (a+b, b)</li>
<li>(a, b) -> (a, a+b)</li>
</ol>
<p>The program should take in a, b, c, and d. And tells us if it is possible to transform (a, b) to (c, d).</p>
<p>Edit: a, b, c and d can be negative integers.</p>
</blockquote>
<p>This recursive solution seems correct but recursion depth increases very fast for even slight increase in input size. I feel I am missing some easy optimization here. I would be glad for any kind of inputs be it style, algorithm choice, speed etc.</p>
<pre><code>def intro():
print "This program will check if transformation (a, b) -> (c, d) is possible by recursive application of any of the below rules:"
print "1. (a, b) => (a+b, b) \n2. (a, b) => (a, a+b)\n"
def user_input():
print "Enter space separated four integers a, b, c and d:\n"
a, b, c, d = map(int, raw_input().split(' '))
return a, b, c, d
# print 'a = ' + a + ' b = ' + b + ' c = ' + c + ' d = ' + d
def solve(a, b, c, d):
print '(a: {}, b: {}) (c: {}, d:{})'.format(a,b,c,d)
if a == c and b == d:
return True
elif a > c or b > d:
return False
elif a == c and b != d:
return solve(a, a+b, c, d)
elif a !=c and b == d:
return solve(a+b, b, c, d)
else:
return solve(a+b, b, c, d) or solve(a, a+b, c, d)
if __name__ == '__main__':
intro()
a, b, c, d = user_input()
if solve(a, b, c, d):
print "Transformation possible"
else:
print "Transformation not possible"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T21:16:10.530",
"Id": "399088",
"Score": "0",
"body": "Is there any stipulation that `a` and `b` must be nonnegative?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T07:35:34.330",
"Id": "399133",
... | [
{
"body": "<pre><code>elif a == c and b != d:\n if (d-b) % a == 0:\n return True\n return False\nelif a !=c and b == d:\n if (c-a) % b == 0:\n return True\n return False\n</code></pre>\n\n<p>If you have correctly identified one number then the other's difference between target and curren... | {
"AcceptedAnswerId": "206890",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T13:42:57.563",
"Id": "206867",
"Score": "3",
"Tags": [
"python",
"performance",
"recursion",
"interview-questions",
"memory-optimization"
],
"Title": "Simple recursive transformation solution in Python"
} | 206867 |
<p>Task is reshape 3d array from [row, col, slice] to [slice,row,col]. I tried implement <code>base::aperm</code> analog with <code>Rcpp</code>.</p>
<pre><code>// [[Rcpp::export]]
Rcpp::NumericVector array_perm(const Rcpp::NumericVector& x) {
if (Rf_isNull(x.attr("dim"))) {
throw std::runtime_error("'x' does not have 'dim' attibute.");
}
Rcpp::Dimension d = x.attr("dim");
if (d.size() != 3) {
throw std::runtime_error("'x' must have 3 dimensions.");
}
std::size_t n = d[2];
std::size_t n_vec = d[0] * d[1];
std::size_t n_out = n_vec * n;
Rcpp::NumericVector res = Rcpp::no_init(n_out);
std::size_t ind_from = 0;
for (std::size_t i = 0; i < n; ++i) {
std::size_t ind_to = i;
for (std::size_t j = 0; j < n_vec; ++j) {
res[ind_to] = x[ind_from];
ind_to += n;
ind_from += 1;
}
}
res.attr("dim") = Rcpp::Dimension(d[2], d[0], d[1]);
return res;
}
</code></pre>
<p>How can I improve it?</p>
<p>For testing code:</p>
<pre><code># Observations
n <- 1000
# Dimension
d <- 100
# Array
a <- replicate(n, matrix(seq_len(d * d), nrow = d, ncol = d))
# Desired result
res <- aperm(a, c(3, 1, 2))
res
</code></pre>
<p>Small benchmark current variant of the code:</p>
<pre><code>b <- bench::mark(aperm(a, c(3, 1, 2)), array_perm(a))
b[, c("expression", "min", "median", "max", "itr/sec")]
#> expression min median max `itr/sec`
#> <chr> <bch:tm> <bch:tm> <bch:tm> <dbl>
#> 1 aperm(a, c(3, 1, 2)) 84.9ms 85.1ms 85.5ms 11.7
#> 2 array_perm(a) 124.8ms 125.2ms 127.2ms 7.96
</code></pre>
<h2>RcppArmadillo solution</h2>
<pre><code>// [[Rcpp::export]]
arma::Cube<double> array_perm2(const arma::Cube<double>& x) {
std::size_t rows = x.n_rows;
std::size_t cols = x.n_cols;
std::size_t slices = x.n_slices;
arma::Cube<double> res(slices, rows, cols);
for(std::size_t i = 0; i < rows; ++i) {
for(std::size_t j = 0; j < cols; ++j) {
for(std::size_t k = 0; k < slices; ++k) {
res(k, i, j) = x(i, j, k);
}
}
}
return res;
}
</code></pre>
<p>Benchmark:</p>
<pre><code> expression min median max `itr/sec`
<chr> <bch:tm> <bch:tm> <bch:tm> <dbl>
1 aperm(a, c(3, 1, 2)) 85.8ms 86.4ms 87.7ms 11.6
2 array_perm(a) 116.1ms 127.3ms 129.6ms 8.08
3 array_perm2(a) 217.4ms 219.7ms 222.1ms 4.55
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T15:02:37.747",
"Id": "399056",
"Score": "0",
"body": "Which version of c++ do you use or have access?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T15:03:49.043",
"Id": "399057",
"Score": "0... | [
{
"body": "<p>If you can change the signature, to directly get cols, rows and slices count, you will not have to check for their validity.</p>\n\n<pre><code>Rcpp::NumericVector array_perm(const Rcpp::NumericVector& input, \n std::size_t rows, std::size_t cols, std::size_t slice... | {
"AcceptedAnswerId": "206882",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T14:11:51.463",
"Id": "206870",
"Score": "3",
"Tags": [
"c++",
"array",
"r",
"rcpp"
],
"Title": "Effective 3d array transposition with R/C++ (Rcpp)"
} | 206870 |
<p>I have created a program that prints the Nth term of the Fibonacci sequence. The fib function needs to use tail recursion. If what I have coded isn't tail recursion, I would like to know how to change the fib function so it does.</p>
<pre><code>#include <iostream>
#include <sstream>
int fib(int n, int i = 0, int a = 0, int b = 1)
{
return (i >= n - 1) ? a : fib(n, i + 1, b, a + b);
}
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cerr << "Argument 2 must be the Nth term." << std::endl;
return -1;
}
std::stringstream ss_obj(argv[1]);
unsigned long int number;
ss_obj >> number;
std::cout << "\nFibonacci number: " << fib(number) << std::endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T17:39:46.520",
"Id": "399069",
"Score": "0",
"body": "Why the downvote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T17:54:30.467",
"Id": "399070",
"Score": "3",
"body": "@vnp because O... | [
{
"body": "<p>To address your immediate concerns, it is a tail recursion indeed. OTOH, there is no need to be <em>that</em> terse. You may want to be a little more explicit:</p>\n\n<pre><code> if (i == n) {\n return a;\n }\n return fib(n, i + 1, b, a + b);\n</code></pre>\n\n<p>Now the tail-recur... | {
"AcceptedAnswerId": "206879",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T17:08:34.453",
"Id": "206874",
"Score": "0",
"Tags": [
"c++",
"recursion",
"fibonacci-sequence"
],
"Title": "Fibonacci Nth term using tail recursion"
} | 206874 |
<p>I am trying to accept JavaScript array literals in an HTML text input.</p>
<p>The problem is that HTML text inputs are captured as strings, such that an input of <code>['name', 'who', 1]</code> becomes <code>"['name', 'who', 1]"</code>.<br>
<br> </p>
<p>My intention is for the following samples to yield the corresponding outputs.</p>
<pre><code>"['river',"spring"]" // ["river","spring"]
"[{key:'value'},20,'who']" // [{"key":"value"},20,"who"]
</code></pre>
<p>The way I worked around the problem is by using <strong>eval</strong> in the code snippet below: </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>const form = document.querySelector('.form');
const inputField = document.querySelector('.input');
const btnParse= document.querySelector('.btn');
const out = document.querySelector('.out');
form.addEventListener('submit', (e)=> {
e.preventDefault();
try {
parsed = eval(inputField.value);
if(Array.isArray(parsed)) {
out.textContent = JSON.stringify(parsed);
} else throw new Error('input is not a valid array' );
} catch(err) {
out.textContent = `Invalid input: ${err.message}`;
}
}); </code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form class="form">
<fieldset>
<legend>Enter array to parse</legend>
<input class="input" type="text">
<input class="btn" type="submit" value="parse">
</fieldset>
</form>
<div>
<p class="out">
</p>
</div> </code></pre>
</div>
</div>
</p>
<p><br></p>
<p>My solution, however, allows for the execution of any Javascript code inputted into the text field, which is a huge vulnerability.</p>
<p><br>
What alternative way is there to converting JavaScript array literal HTML text inputs into JS array objects without using <strong>eval</strong>? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T18:57:13.623",
"Id": "399079",
"Score": "0",
"body": "\"My solution, however, allows for the execution of any Javascript code inputted into the text field, which is a huge vulnerability.\" Yes, which is why we usually prefer to thin... | [
{
"body": "<h3>The answer</h3>\n\n<p>What you're actually trying to do is only converting objects from Javascript notation to actual javascript objects. Now what if there was a well-specified data interchange format that was named \"Javascript object notation\"? Oh there is?</p>\n\n<pre><code>parsed = JSON.pars... | {
"AcceptedAnswerId": "206904",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T18:33:09.987",
"Id": "206881",
"Score": "0",
"Tags": [
"javascript",
"array",
"html",
"parsing"
],
"Title": "Convert HTML input string to JavaScript Array literal"
} | 206881 |
<p>Background information: Given two different strings of equal length, the spacing between them is the number of other strings you would need to connect them on a word ladder. Alternately, this is 1 less than the number of letters that differ between the two strings. </p>
<p>The challenge: Given an input list of unique words and a maximum total spacing, output a list of distinct words taken from the input list. The output list's total spacing must not exceed the given maximum. The output list should be as long as possible.</p>
<p>My output list is 433 words long. May someone look over code proofreading/ efficiency? Much thanks.</p>
<p>Also, the text file used in the program can be found here: <a href="https://gist.githubusercontent.com/cosmologicon/0a4448e8fdb79ee620a68ed131eac58e/raw/a8831d08019f73e7d5a52042e2c4afe6fea70011/363-hard-words.txt" rel="nofollow noreferrer">https://gist.githubusercontent.com/cosmologicon/0a4448e8fdb79ee620a68ed131eac58e/raw/a8831d08019f73e7d5a52042e2c4afe6fea70011/363-hard-words.txt</a></p>
<pre><code>import operator
MAX = 100 # Max word ladder score I'm allowed in this program
with open("363-hard-words.txt") as f:
data = f.read().splitlines()
f.close()
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
# Returns numerical spacing between a and b on the word ladder
def spacing(a, b):
score = 0
for x, y in zip(a, b):
if x != y:
score += 1
return score - 1
# Returns a dictionary of txt file words as key, with number of words with sp spacing as value
def space_dict(sp):
totals = []
for word in data:
total = 0
for word1 in data:
if word == word1:
continue
if spacing(word, word1) == sp:
total += 1
totals.append(total)
return dict(zip(data, totals))
# Given a word, returns a dictionary with every other word as the key,
# and the spacing between the word and the other word as the value
def words_dict(word):
totals = []
for w in data:
if w == word:
continue
totals.append(spacing(word, w))
return dict(zip(data, totals))
# Sorts a dictionary by its keys in ascending order and returns a list
def sort_dict(space):
return sorted(space.items(), key=operator.itemgetter(1))
# Returns a list of words with number spacing to the word
def get_connections(word, number):
output = []
for w in data:
if (spacing(word, w) == number) and (word != w):
output.append(w)
return output
# Attempts to return max list of words with a total word ladder score of 0
def method1():
output = []
sorted_dict = sort_dict(space_dict(0))
output.append(sorted_dict[-1][0])
data.remove(sorted_dict[-1][0])
connections = get_connections(sorted_dict[-1][0], 0)
while len(get_connections(connections[-1], 0)) != 0:
connections = get_connections(connections[-1], 0)
output.append(connections[-1])
print("connections:", connections, "Output size:", str(len(output)))
data.remove(connections[-1])
return len(output)
# Attempts to return max length of a word ladder given first word, inspired by
# tajjet's solution
def method2_iter(wd):
score, length = 0, 0
output = [wd]
sorted_dict = sort_dict(words_dict(wd))
data.remove(wd)
while score <= 100:
length += 1
word = sorted_dict[0][0]
score += sorted_dict[0][1]
if score > 100:
break
output.append(word)
data.remove(word)
sorted_dict = sort_dict(words_dict(word))
print(output)
return length
def main():
# print(str(method1()))
print(str(method2_iter("kats")))
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T00:35:59.633",
"Id": "399117",
"Score": "0",
"body": "I am not sure I understand the problem statement. How the _output list's total spacing_ is defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-0... | [
{
"body": "<p>I would suggest renaming your methods. <code>method1</code>, and <code>method2_itr</code> would be better if they were instead named what they did. Currently, these functions have comments above them explaining their functionality, instead of that, let the function name speak for the function itse... | {
"AcceptedAnswerId": "206914",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T20:26:23.897",
"Id": "206887",
"Score": "3",
"Tags": [
"python",
"algorithm",
"comparative-review",
"graph",
"hash-map"
],
"Title": "Word ladders program in Python"
} | 206887 |
<p>I am given an array that represents a k-ary tree (I am also given the branching factor "k") that is stored in level order. My task was to print the tree in level order. </p>
<p>For example a trinary tree stored as {0,1,2,3,null,null,null,7,8,9,10,11,12} (It doesn't have to be full or complete) would print out as:</p>
<pre class="lang-none prettyprint-override"><code>0
1 2 3
null null null 7 8 9 10 11 12
</code></pre>
<p>My solution currently works fine but it is very messy and not as elegant as I would prefer. The runtime complexity is also very bad (I don't know if Math.pow is O(1) or O(n) but if it's O(1), my code is still O(n) which is not ideal. If Math.pow is O(n) then my code is O(n<sup>2</sup>) which is garbage.</p>
<p>Is there another approach I am not seeing or can my existing code be optimized at all?</p>
<pre><code>public static void main(String[] args) {
int k = 3;
Integer[] arrInt = {0,1,2,3,null,null,null,7,8,9,10,11,12};
String ans = arrInt[0] + "\n";
int currLvl = 1;
int prevLvl = 0;
//Print all values
for(int i = 1; i < arrInt.length-1; ++i){
//Add a line if we reach a new level
if(i == (Math.pow(k, currLvl)+Math.pow(k, prevLvl))){
currLvl++;
prevLvl++;
ans+= "\n";
}
ans+= " " + arrInt[i];
}
//EDGE CASE TO HANDLE LAST ELEMENT
ans+= " " + arrInt[arrInt.length-1];
System.out.println(ans);
}
</code></pre>
| [] | [
{
"body": "<p>Your biggest performance problem is the repeated string concatenation using the <code>+</code> operator. Since Java strings are immutable, every <code>+=</code> operation requires allocating a new string and copying the previous contents. Use a <code>StringBuilder</code> instead.</p>\n\n<p><code... | {
"AcceptedAnswerId": "206893",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-03T20:54:33.263",
"Id": "206888",
"Score": "2",
"Tags": [
"java",
"performance",
"array",
"tree",
"formatting"
],
"Title": "Printing a K-ary tree stored in level-order in an array"
} | 206888 |
<p>I'm trying to sketch out a stripped down generic form validation example. I started by creating Plain Old PHP Objects (referred as POPOs) for form input with some classes such as a validator and html renderer class, that I then reduced to explicit functions.</p>
<p>The POPOs are useful in as much as you can comment and glance at expected properties. Looking at the code, one starts to wonder if I'd be better off with well defined arrays as inputs and not bother with the plain objects, as some of the object wrangling (the <code>popo</code> functions) are effectively just wrappers for array functions, and perhaps an array would just do.</p>
<p>Are these plain objects muddying the waters?</p>
<p>Any comments welcome.</p>
<pre><code><?php
class UserForm
{
public $email;
}
class UserFormErrors extends UserForm
{}
function map_array_to_popo(array $array, $object)
{
foreach($object as $key => $value)
$object->$key = isset($array[$key])
? $array[$key]
: null;
return $object;
}
function popo_has_empty_values($object)
{
$array = (array) $object;
return empty(array_filter($array));
}
function user_form_validate(UserForm $input)
{
$errors = new UserFormErrors;
if($input->email == '') {
$errors->email[] = 'Email address is required.';
} elseif(filter_var($input->email, FILTER_VALIDATE_EMAIL) === false) {
$errors->email[] = 'Email address must be valid.';
}
return $errors;
}
function user_form_html_render(
$action = '',
UserForm $values,
UserFormErrors $errors
)
{
$escape = function($string) {
return htmlspecialchars($string);
};
$error = function($messages) use ($escape) {
return
empty($messages)
? ''
: '<ul><li>' .
implode('</li><li>', array_map($escape, $messages)) .
'</li></ul>';
};
?>
<form method='POST' action="<?= $action ?>">
<label for="email">Email address:</label>
<input type="text" name="email" id="email" value=
"<?= $escape($values->email) ?>">
<?= $error($errors->email) ?>
<input type="submit">
</form>
<?php
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$input = array_filter($_POST, 'is_string');
$input = array_map('trim', $input);
$values = map_array_to_popo($input, new UserForm);
$errors = user_form_validate($values);
$valid = popo_has_empty_values($errors);
if($valid) {
// Form values look good, do what you want with values.
echo 'Email address entered is: ' . $values->email;
} else {
// Display form with data and errors
user_form_html_render('', $values, $errors);
}
} else {
user_form_html_render('', new UserForm, new UserFormErrors);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T11:39:26.667",
"Id": "399152",
"Score": "0",
"body": "Not wanting to detract from above, but a sketch of a non POPO version is here: https://pastebin.com/DM52nCFG"
}
] | [
{
"body": "<p>Personally I don't see any value in introducing such objects. Especially given you are inclined to functional programming, which is a real trademark of your code, whereas such \"POPOs\" indeed look alien in it.</p>\n\n<p>Either way, there is one plain mistake in the code, an Error by no means is a... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T05:25:08.640",
"Id": "206896",
"Score": "2",
"Tags": [
"php",
"validation",
"form"
],
"Title": "User form validation using a POPO"
} | 206896 |
<p><code>TableContainer.js</code> does the common task of fetching data and passing it to a lower component, <code>Table.js</code>, which is a stateless functional component.</p>
<p><code>currentPage</code> is stored in redux, I did this just to practice redux.</p>
<p><strong>Question 1</strong></p>
<p>Is this all reasonable?</p>
<p><strong>Question 2</strong></p>
<p>I noticed that the component will re-render when it receives a new <code>currentPage</code> and then re-renders again, once the data is loaded. The first re-render is not necessary as nothing changes before data is actually loaded. Should I just live with this or should I implement <code>shouldComponentUpdate()</code> to check if <code>data</code> has changed. Or is that potentially even more costly than the re-render itself?</p>
<p><strong>Question 3</strong></p>
<p>Is using <code>componentDidUpdate()</code> to check if <code>currentPage</code> has changed and then re-load the data a good way of controlling the load process?</p>
<p><strong>Question 4</strong></p>
<p>Is building the URL this way acceptable?</p>
<pre><code>const pageParam = currentPage ? "?_page=" + currentPage : "";
fetch('https://jsonplaceholder.typicode.com/posts/' + pageParam)
</code></pre>
<p><strong>TableContainer.js</strong></p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import Table from "../components/Table";
import Pagination from "../components/Pagination";
import {connect} from "react-redux";
import {changePage} from "../js/actions";
const PAGE_COUNT = 10;
const mapStateToProps = state => {
return { currentPage: state.currentPage }
};
const mapDispatchToProps = dispatch => {
return {
changePage: page => dispatch(changePage(page))
};
};
class ConnectedTableContainer extends React.Component {
state = {
data: [],
loaded: false,
};
handlePageChange = page => {
if (page < 1 || page > PAGE_COUNT) return;
this.props.changePage(page);
};
loadData = () => {
this.setState({ loaded: false });
const { currentPage } = this.props;
console.log("load data: " + currentPage);
const pageParam = currentPage ? "?_page=" + currentPage : "";
fetch('https://jsonplaceholder.typicode.com/posts/' + pageParam)
.then(response => {
if (response.status !== 200) {
console.log("Unexpected response: " + response.status);
return;
}
return response.json();
})
.then(data => this.setState({
data: data,
loaded: true,
}))
};
componentDidMount() {
this.loadData(this.props.currentPage);
}
componentDidUpdate(prevProps) {
if (prevProps.currentPage != this.props.currentPage) {
this.loadData();
}
}
render() {
const { loaded } = this.state;
const { currentPage } = this.props;
console.log("render page: " + currentPage);
return (
<div className="container">
<div className="section">
<Pagination onPageChange={ this.handlePageChange } pageCount={ PAGE_COUNT } currentPage={ currentPage }/>
</div>
<div className={ "section " + (loaded ? "" : "loading") }>
<Table data={ this.state.data } />
</div>
</div>
)
}
}
ConnectedTableContainer.propTypes = {
changePage: PropTypes.func.isRequired,
currentPage: PropTypes.number.isRequired,
};
ConnectedTableContainer.defaultProps = {
currentPage: 1,
};
const TableContainer = connect(mapStateToProps, mapDispatchToProps)(ConnectedTableContainer);
export default TableContainer;
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Question 1</p>\n \n <p>Is this all reasonable?</p>\n</blockquote>\n\n<p>Absolutely!</p>\n\n<blockquote>\n <p>Question 2</p>\n \n <p>I noticed that the component will re-render when it receives a new\n currentPage and then re-renders again, once the data is loaded. The\n firs... | {
"AcceptedAnswerId": "207031",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T09:27:32.097",
"Id": "206902",
"Score": "1",
"Tags": [
"react.js",
"pagination",
"jsx"
],
"Title": "React container component to fetch paginated data for a stateless table component"
} | 206902 |
<p>Here is my code:</p>
<pre><code>package com.app;
public class Solution {
public String toBinaryString(int n) {
char[] buffer = new char[32];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = '0';
}
int i = buffer.length - 1;
while (n != 0) {
if (n % 2 != 0) {
buffer[i] = '1';
}
i--;
n >>>= 1;
}
return new String(buffer);
}
}
</code></pre>
<p>And I also wrote a few tests:</p>
<pre><code>package com.app;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SolutionTest {
@Test
void one() {
Solution solution = new Solution();
assertEquals("00000000000000000000000000000001", solution.toBinaryString(1));
}
@Test
void minusOne() {
Solution solution = new Solution();
assertEquals("11111111111111111111111111111111", solution.toBinaryString(-1));
}
@Test
void intMin() {
Solution solution = new Solution();
assertEquals("10000000000000000000000000000000", solution.toBinaryString(Integer.MIN_VALUE));
}
@Test
void intMax() {
Solution solution = new Solution();
assertEquals("01111111111111111111111111111111", solution.toBinaryString(Integer.MAX_VALUE));
}
@Test
void even() {
Solution solution = new Solution();
assertEquals("00000000000000000000000001111100", solution.toBinaryString(124));
}
@Test
void odd() {
Solution solution = new Solution();
assertEquals("00000000000000000000000000100101", solution.toBinaryString(37));
}
}
</code></pre>
<p>The problem seems to be pretty easy. However, it took me some time to make it work with negative numbers and some edge cases. So I'd greatly appreciate if you noticed any bugs in my code.</p>
| [] | [
{
"body": "<p>A single loop would be preferable.</p>\n\n<pre><code>public static String toBinaryString(int n) {\n char[] buffer = new char[32];\n for (int i = buffer.length - 1; i >= 0; i--) {\n buffer[i] = '0' + (n & 1);\n n >>>= 1;\n }\n return new String(buffer);\n}\... | {
"AcceptedAnswerId": "206923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T09:42:43.893",
"Id": "206905",
"Score": "0",
"Tags": [
"java",
"algorithm",
"bitwise",
"number-systems"
],
"Title": "Given an integer, return its binary representation. You cannot use any Integer.toXXXString methods"
} | 206905 |
<p>Here is my code:</p>
<pre><code>package com.app;
public class Solution {
// Suppose the operation ~ doesn't exist
public int invertBinaryNumber(int n) {
int singleOne = 1;
int singleZero = 0xfffffffe;
while (singleOne != 0) {
if ((n & singleOne) == 0) {
n |= singleOne;
} else {
n &= (singleZero);
}
singleZero <<= 1;
singleZero |= 1;
singleOne <<= 1;
}
return n;
}
}
</code></pre>
<p>And there are a few tests:</p>
<pre><code>package com.app;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SolutionTest {
@Test
void one() {
Solution solution = new Solution();
assertEquals(~1, solution.invertBinaryNumber(1));
}
@Test
void even() {
Solution solution = new Solution();
assertEquals(~12, solution.invertBinaryNumber(12));
}
@Test
void odd() {
Solution solution = new Solution();
assertEquals(~37, solution.invertBinaryNumber(37));
}
@Test
void intMax() {
Solution solution = new Solution();
assertEquals(~Integer.MAX_VALUE, solution.invertBinaryNumber(Integer.MAX_VALUE));
}
@Test
void intMin() {
Solution solution = new Solution();
assertEquals(~Integer.MIN_VALUE, solution.invertBinaryNumber(Integer.MIN_VALUE));
}
}
</code></pre>
<p>The problem seems to be pretty easy. However, it took me some time to make it work with negative numbers and some edge cases. So I'd greatly appreciate if you noticed any bugs in my code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T10:48:57.637",
"Id": "399149",
"Score": "0",
"body": "are you required to invert the bits one by one? Or does the challenge allow you to use default arithmetic operations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creatio... | [
{
"body": "<p>To flip a bit, XOR it with 1. To flip all bits, XOR the number with a mask consisting entirely of 1 bits.</p>\n\n<p>Make your function <code>static</code> so that you don't need to instantiate <code>Solution</code> to call it.</p>\n\n<pre><code>public class Solution {\n public static int invert... | {
"AcceptedAnswerId": "206919",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T09:49:38.493",
"Id": "206906",
"Score": "-1",
"Tags": [
"java",
"algorithm",
"interview-questions",
"bitwise"
],
"Title": "Given an integer number, invert its bits. You cannot use the ~ operator"
} | 206906 |
Logback is a successor to the popular log4j project, picking up where log4j leaves off. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T10:00:59.677",
"Id": "206908",
"Score": "0",
"Tags": null,
"Title": null
} | 206908 |
<p>This library management program can do following functions:</p>
<ul>
<li>Add a book to the library </li>
<li>Display all available books </li>
<li>Lend books to students </li>
<li>Return books to the library </li>
<li>Display students who have yet to return a book</li>
</ul>
<p>Question: How do you <em>refactor</em> this code so that it follows OOP, reads better, is manageable and is pythonic? How can I write name functions and classes better? How do you know which data structure you need to use so as to manage data effectively?</p>
<p><code>Library</code> class that <em>contains</em> a <em>list</em> of books</p>
<pre><code>class Library:
def __init__(self):
self._books = []
def add_book(self, new_book):
self._books.append(new_book)
def display_books(self):
if self._books: # if list of books is not empty
print("The books we have made available in our library are:\n")
for book in self._books:
print(book)
else:
print("Sorry, we have no books available in the library at the moment")
def lend_book(self, requested_book):
if requested_book in self._books:
print("You have now borrowed \"%s\" " % requested_book)
self._books.remove(requested_book)
else:
print("Sorry, \"%s\" is not there in our library at the moment" % requested_book)
</code></pre>
<p><code>StudentDatabase</code> class (container for all students)</p>
<pre><code>class StudentDatabase:
def __init__(self):
self._books = {}
def get_student(self, name):
if name not in self._books:
return "Not Found"
return self._books[name]
def borrow_book(self, name, book):
if name not in self._books:
self._books[name] = list(book)
else:
self._books[name].append(book)
def return_book(self, name, book):
if book not in self._books[name]:
print("You don't seem to have borrowed \"%s\"" % book)
else:
self._books[name].remove(book)
def display_students_with_books(self):
for name, books in self._books.items():
if books:
print("%s: %s" % (name, books))
</code></pre>
<p>Follow-up : <a href="https://codereview.stackexchange.com/q/207303">Object-oriented student library</a></p>
| [] | [
{
"body": "<p>In addition to the below, I recommend reading <a href=\"https://codereview.stackexchange.com/a/206995/140921\">Maarten Fabré's answer</a>.</p>\n\n<hr>\n\n<h1>Edge case</h1>\n\n<p>Consider the following scenario:</p>\n\n<pre><code>book_tracking = StudentDatabase()\nbook_tracking.return_book(\"Stude... | {
"AcceptedAnswerId": "206947",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T15:51:18.533",
"Id": "206921",
"Score": "8",
"Tags": [
"python",
"beginner",
"object-oriented",
"python-3.x"
],
"Title": "Object-oriented student library"
} | 206921 |
<p>There's a mission-critical ring buffer in production on which I'm curious to test some optimizations. Specifically, I'm wondering how much of a performance difference struct size will make on issues like <a href="https://software.intel.com/en-us/articles/avoiding-and-identifying-false-sharing-among-threads" rel="nofollow noreferrer">false sharing</a>. The queue itself is single-producer, many-consumer, and the current structs that get thrown around in shared memory are 48 bytes. My theory is that, if the structs being consumed are 64 bytes, perhaps there'd be less cache misses due to false sharing.</p>
<p>I wrote a simplified server/consumer pair of C++ programs and a Python script to build and run them many times. What I'd like to know is: am I testing properly to explore the title-line question? That is, do these various builds even produce differently sized cache reads and writes? Perhaps more importantly, is this even a sensible thing to want to test for performance reasons?</p>
<p>Here's my Makefile:</p>
<pre><code>CXX=g++
CFLAGS=-std=c++14 -O2 -I.
WFLAGS=-Wall -Wextra -Werror
all: server consumer
server: server.cpp data.h
@$(CXX) $(CFLAGS) $(WFLAGS) $(ADDFLAGS) -o $@ $^
consumer: consumer.cpp data.h
@$(CXX) $(CFLAGS) $(WFLAGS) $(ADDFLAGS) -o $@ $^
.PHONY: clean
clean:
@rm server consumer
</code></pre>
<p>Here's the shared data.h:</p>
<pre><code>#ifndef __DATA_H__
#define __DATA_H__
#include <cstdint>
#include <atomic>
#define QUEUE_SIZE 100
#ifdef SIZE_48B
typedef struct
{
uint64_t price_a;
uint64_t price_b;
uint32_t size_a;
uint32_t size_b;
uint32_t ts_a;
uint64_t ts_b;
uint64_t padding;
}Datum;
#elif SIZE_32B
typedef struct
{
uint64_t price_a;
uint64_t price_b;
uint64_t ts_b;
uint64_t padding;
}Datum;
#elif SIZE_64B
typedef struct
{
uint64_t price_a;
uint64_t price_b;
uint64_t size_a;
uint64_t size_b;
uint64_t ts_a;
uint64_t ts_b;
uint64_t padding_a;
uint64_t padding_b;
}Datum;
#endif
typedef struct
{
std::atomic_uint32_t current_index;
std::atomic_uint32_t current_turn;
Datum data[QUEUE_SIZE];
}SharedData;
#endif //__DATA_H__
</code></pre>
<p>This is server.cpp:</p>
<pre><code>#include <iostream>
#include <chrono>
#include <thread>
#include <csignal>
#include <cstdlib>
#include <ctime>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "data.h"
bool carry_on = true;
void sig_handler(int)
{
std::cout << std::endl;
carry_on = false;
}
int main()
{
signal(SIGHUP, sig_handler);
signal(SIGINT, sig_handler);
signal(SIGQUIT, sig_handler);
signal(SIGKILL, sig_handler);
signal(SIGTERM, sig_handler);
srand(time(NULL));
std::cout << "Using " << sizeof(Datum) << " byte structs" << std::endl;
key_t key = ftok("/etc/hosts", 1);
int shmid = shmget(key, sizeof(SharedData), 0666|IPC_CREAT);
SharedData* share = (SharedData*) shmat(shmid, (void*) 0, 0);
Datum* data_arr = share->data;
share->current_turn = 0;
while(carry_on)
{
for(uint32_t i = 0; i < QUEUE_SIZE; i++)
{
#ifdef SIZE_48B
data_arr[i].price_a = 1234567890*i;
data_arr[i].price_b = 987654321*i;
data_arr[i].size_a = 123*i;
data_arr[i].size_b = 456*i;
data_arr[i].ts_a = 789*i;
data_arr[i].ts_b = 78901232*i;
data_arr[i].padding = 0;
#elif SIZE_32B
data_arr[i].price_a = 1234567890*i;
data_arr[i].price_b = 987654321*i;
data_arr[i].ts_b = 78901232*i;
data_arr[i].padding = 0;
#elif SIZE_64B
data_arr[i].price_a = 1234567890*i;
data_arr[i].price_b = 987654321*i;
data_arr[i].size_a = 123*i;
data_arr[i].size_b = 456*i;
data_arr[i].ts_a = 789*i;
data_arr[i].ts_b = 78901232*i;
data_arr[i].padding_a = 0;
data_arr[i].padding_b = 0;
#endif
share->current_index = i;
std::chrono::microseconds duration(rand()%10);
std::this_thread::sleep_for(duration);
if(!carry_on) break;
}
if(carry_on)
{
share->current_index = 0;
share->current_turn++;
std::chrono::microseconds duration(rand()%100);
// std::cout << share->current_turn << std::endl;
std::this_thread::sleep_for(duration);
}
}
shmdt(share);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
</code></pre>
<p>This is consumer.cpp:</p>
<pre><code>#include <iostream>
#include <cstring>
#include <chrono>
#include <thread>
#include <csignal>
#include <ctime>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "data.h"
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
bool carry_on = true;
void sig_handler(int)
{
std::cout << std::endl;
carry_on = false;
}
int main()
{
signal(SIGINT, sig_handler);
srand(time(NULL));
key_t key = ftok("/etc/hosts", 1);
int shmid = shmget(key, sizeof(SharedData), 0666|IPC_CREAT);
SharedData* share = (SharedData*) shmat(shmid, (void*) 0, 0);
Datum current_datum;
uint32_t client_index = 0;
uint32_t client_turn = share->current_turn;
uint32_t orig_turn = client_turn;
uint32_t num_laps = 0;
steady_clock::time_point start = steady_clock::now();
while(carry_on)
{
if(client_turn < share->current_turn)
{
if(client_index < share->current_index)
{
num_laps++;
client_index = share->current_index;
client_turn = share->current_turn;
}
}
while(client_index <= share->current_index)
{
memcpy(&current_datum, &share->data[client_index], sizeof(Datum));
std::chrono::microseconds duration(rand()%100);
std::this_thread::sleep_for(duration);
client_index++;
if(client_index == QUEUE_SIZE)
{
client_turn++;
if((client_turn - orig_turn) >= 100)
{
carry_on = false;
}
client_index = 0;
break;
}
}
}
steady_clock::time_point end = steady_clock::now();
steady_clock::duration elapsed = duration_cast<nanoseconds>(end-start);
std::cout << elapsed.count() << " " << num_laps << std::endl;
shmdt(share);
return 0;
}
</code></pre>
<p>And finally, here's the Python script that drives it:</p>
<pre><code>#!/usr/bin/python3
import subprocess
import threading
import logging
from multiprocessing import cpu_count
def run_test():
total_runtime = []
total_laps = []
test_iter = 0
while test_iter < 100:
try: results = subprocess.run(["./consumer"], capture_output=True)
except KeyboardInterrupt: break
tokens = results.stdout.decode("utf-8").split(" ")
try:
total_runtime.append(int(tokens[0].strip()))
total_laps.append(int(tokens[1].strip()))
except ValueError:
print("Error logging output. Server died?", flush=True)
break
test_iter += 1
# if test_iter == 10:
# print(" "+str(test_iter), end="", flush=True)
# elif test_iter%10 == 0:
# print(", "+str(test_iter), end="", flush=True)
try:
avg_runtime = sum(total_runtime)//len(total_runtime)
avg_laps = round(sum(total_laps)/len(total_laps), 2)
one_pct_low_run = sorted(total_runtime)[1]
one_pct_high_run = sorted(total_runtime)[-1]
one_pct_low_lap = sorted(total_laps)[1]
one_pct_high_lap = sorted(total_laps)[-1]
logging.info(str(round(avg_runtime/1000/1000/1000, 6))+"s avg runtime "+
str(round(one_pct_low_run/1000/1000/1000, 6))+"s lo "+
str(round(one_pct_high_run/1000/1000/1000, 6))+"s hi")
logging.info(str(avg_laps)+" avg laps "+str(one_pct_low_lap)+" lo "+
str(one_pct_high_lap)+" hi")
except ZeroDivisionError:
return
logging.basicConfig(level=logging.INFO, format="%(threadName)s: %(message)s")
for size in ["'-DSIZE_32B'", "'-DSIZE_48B'", "'-DSIZE_64B'"]:
try:
subprocess.run(["make", "clean"], capture_output=True)
subprocess.run(["make", "all", "-j8", "ADDFLAGS="+size], check=True)
except KeyboardInterrupt:
quit()
server_proc = subprocess.Popen(["./server"])
threads = []
for cpu in range(cpu_count()):
t = threading.Thread(target=run_test)
threads.append(t)
t.start()
for thread in threads:
thread.join()
server_proc.terminate()
</code></pre>
<p>The only further notes I can think to offer is that I've called the condition where the consumer falls behind the producer a "lap". Obviously, I want overall execution time and number of laps to be as low as possible. Unfortunately, there appears to be very little difference in the runtime or laps of the various byte sizes. =) I have to assume this is because of some poorly controlled variables and would love to have your feedback on how to tidy this test up and better optimize this data model.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T17:19:48.947",
"Id": "206929",
"Score": "3",
"Tags": [
"python",
"c++",
"linux",
"benchmarking",
"ipc"
],
"Title": "Cache line versus struct size testing"
} | 206929 |
<p>This is my solution for NQueen problem in scala.
I just want to know how to make it more easy to read, modular and areas i need to improve.</p>
<pre><code>object Main {
def main(args: Array[String]): Unit = {
val matrix = Array.ofDim[Int](16,16)
val queen_place = (2,2)
nQueenSol(matrix,matrix.size)
}
def diagonal_rule(x1:Int,y1:Int,x2:Int,y2:Int) = x1 + y1 == x2 + y2 || x1 - y1 == x2 - y2
def vertical_or_horizontal_rule(x1:Int,y1:Int,x2:Int,y2:Int) = x1 == x2 || y1 == y2
def queen_places(x:Int,y:Int,chess_board:Array[Array[Int]]):Array[Array[Int]] = {
for(i <- 0 until chess_board.size;
j <- 0 until chess_board.size) {
if(chess_board(i)(j) == 0)
chess_board(i)(j) = if(diagonal_rule(x,y,i,j)|| vertical_or_horizontal_rule(x,y,i,j))1 else 0
}
chess_board
}
def printChessBoard(array: Array[Array[Int]]): Unit ={
array.foreach(y => {
y.foreach(x => print(x + " "))
println()
}
)
}
def queenNotPresentAt(chessBoard:Array[Array[Int]])(x:Int,y:Int) = chessBoard(x - 1)(y) == 0
def nQueenSol(chessBoard:Array[Array[Int]],nthQueen:Int): Unit ={
if(nthQueen == 0) {printChessBoard(chessBoard);println}
else {
for(i <- 0 until chessBoard.size){
val touched = chessBoard.map(_.clone())
if(queenNotPresentAt(touched)(nthQueen, i)) {
touched(nthQueen - 1)(i) = 2
val newchessBoard = queen_places(nthQueen - 1,i,touched)
nQueenSol(newchessBoard,nthQueen - 1)
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-06T08:24:04.380",
"Id": "399439",
"Score": "0",
"body": "If you want others to look at your code then you might spend some time making it presentable. You know, removing unnecessary white-space, making sure all comments are relevant to... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T17:22:35.733",
"Id": "206930",
"Score": "1",
"Tags": [
"algorithm",
"scala",
"n-queens"
],
"Title": "NQueen solution in scala"
} | 206930 |
<p>So, <a href="https://codereview.stackexchange.com/questions/68530/minheap-implementation">this</a> has <a href="https://codereview.stackexchange.com/questions/182624/minmax-heap-implementation-in-net">been</a> done <a href="https://codereview.stackexchange.com/questions/162311/min-max-heap-implementation">quite</a> a <a href="https://codereview.stackexchange.com/questions/128280/minheap-implementation">few</a> times on here, but each of the linked implementations has some significant issues. Since I needed a MinHeap anyway, I figured I would throw my version into the ring.</p>
<p>In my case, I'm working on a toy game prototype where the simulation runs a clock that keeps track of the time in-game, and I have callbacks that I want to run at a particular game time, so the callbacks go into a priority queue and each time the simulation clock ticks up, I execute all of the callbacks that are before the new in-game time.</p>
<h3>Previous Comments</h3>
<p>First off, to address some comments on other implementations that I don't agree with:</p>
<blockquote>
<p><a href="https://codereview.stackexchange.com/questions/68530/minheap-implementation#comment125194_68530">If this is in production code you should consider using SortedSet</a></p>
</blockquote>
<p><code>SortedSet<T></code> has a <em>much</em> more general API, and I'm not at all sure that it's as performant.</p>
<blockquote>
<p><a href="https://codereview.stackexchange.com/a/68535/23601">You should always try to program against an interface instead of against an implementation.</a> </p>
</blockquote>
<p>I agree for public APIs, but not for private implementation details. There's just no benefit whatsoever to using an interface for <code>data</code>.</p>
<h3>Lingering Questions</h3>
<p>One thing I'm undecided on is restricting <code>T</code> to be <code>ICompareable<T></code>. While this sends a strong signal about the requirements of T when using the default comparer, it's unnecessarily restrictive in the case where the user wants to provide their own comparer.</p>
<p>I also wonder whether there is an implementation that is faster than an array-based binary heap. I've done a bit of poking around and tried implementing a pairing heap for comparison, and so far everything suggests that the array-based binary heap wins in practice for reasonable (say, less than 100k elements) heap sizes.</p>
<h3>Code</h3>
<p>Heap Implementation:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace CodeReview.DataStructures
{
public sealed class MinHeap<T>
{
private readonly IComparer<T> comparer;
private readonly List<T> data;
/// <summary>
/// Returns the number of items in the heap.
/// </summary>
public int Count => data.Count;
/// <summary>
/// Returns <see langword="true"/> if the heap is empty, otherwise
/// <see langword="false"/>.
/// </summary>
public bool Empty => data.Count == 0;
/// <summary>
/// Creates an empty <see cref="MinHeap{T}"/> that uses the default comparer.
/// </summary>
public MinHeap() : this(Comparer<T>.Default) { }
/// <summary>
/// Creates an empty <see cref="MinHeap{T}"/> with the specified comparer.
/// </summary>
/// <param name="comparer">
/// The comparer used to determine the order of elements in the heap.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="comparer"/> is <see langword="null"/>.
/// </exception>
public MinHeap(IComparer<T> comparer)
{
this.comparer = comparer ?? throw new ArgumentNullException("comparer");
data = new List<T>();
}
/// <summary>
/// Creates a new <see cref="MinHeap{T}"/> containing the elements of
/// <paramref name="src"/>.
/// </summary>
/// <param name="collection">
/// The elements to add to the heap.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="collection"/> is <see langword="null"/>.
/// </exception>
public MinHeap(IEnumerable<T> collection) : this(collection, Comparer<T>.Default) { }
/// <summary>
/// Creates a new <see cref="MinHeap{T}"/> containing the elements of
/// <paramref name="collection"/>.
/// </summary>
/// <param name="collection">
/// The elements to add to the heap.
/// </param>
/// <param name="comparer">
/// The comparer used to determine the order of elements in the heap.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="collection"/> or <paramref name="comparer"/> are
/// <see langword="null"/>.
/// </exception>
public MinHeap(IEnumerable<T> collection, IComparer<T> comparer)
{
this.comparer = comparer ?? throw new ArgumentNullException("comparer");
data = new List<T>(collection);
for (int i = Count / 2; i >= 0; --i)
{
SiftDown(i);
}
}
/// <summary>
/// Gets the item at the top of the heap.
/// </summary>
/// <returns>The item at the top of the heap.</returns>
/// <exception cref="InvalidOperationException">
/// If the heap is empty.
/// </exception>
public T Peek()
{
if (Empty)
{
throw new InvalidOperationException("Cannot peek empty heap");
}
return data[0];
}
/// <summary>
/// Removes the item at the top of the heap and returns it.
/// </summary>
/// <returns>The item at the top of the heap.</returns>
/// <exception cref="InvalidOperationException">
/// If the heap is empty.
/// </exception>
public T Pop()
{
if (Empty)
{
throw new InvalidOperationException("Cannot pop empty heap");
}
T result = data[0];
data[0] = data[Count - 1];
data.RemoveAt(Count - 1);
SiftDown(0);
return result;
}
/// <summary>
/// Inserts the specified item into the heap.
/// </summary>
/// <param name="item">The item to insert.</param>
public void Push(T item)
{
data.Add(item);
SiftUp(Count - 1);
}
/// <summary>
/// Replaces the item at the top of the heap with <paramref name="item"/>
/// and returns the old top.
/// </summary>
/// <param name="item">The item to insert.</param>
/// <returns>The previous top of the heap.</returns>
/// <exception cref="InvalidOperationException">
/// If the heap is empty.
/// </exception>
/// <remarks>
/// This operation is useful because it only needs to rebalance the heap
/// once, as opposed to two rebalances for a pop followed by a push.
/// </remarks>
public T Replace(T item)
{
if (Empty)
{
throw new InvalidOperationException("Cannot replace on empty heap");
}
T result = data[0];
data[0] = item;
SiftDown(0);
return result;
}
private void SiftUp(int index)
{
while (index > 0)
{
int parent = (index - 1) / 2;
if (comparer.Compare(data[index], data[parent]) < 0)
{
Swap(index, parent);
index = parent;
}
else
{
return;
}
}
}
private void SiftDown(int i)
{
while (i < Count)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if (left < Count && comparer.Compare(data[left], data[largest]) < 0)
{
largest = left;
}
if (right < Count && comparer.Compare(data[right], data[largest]) < 0)
{
largest = right;
}
if (largest == i)
{
return;
}
Swap(i, largest);
i = largest;
}
}
private void Swap(int i, int j)
{
T tmp = data[j];
data[j] = data[i];
data[i] = tmp;
}
}
}
</code></pre>
<p>Unit Tests:</p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CodeReview.DataStructures;
namespace CodeReview.Test.DataStructures
{
[TestClass]
public class MinHeapTests
{
[TestMethod]
public void Count()
{
var heap = new MinHeap<int>();
Assert.AreEqual(0, heap.Count);
heap.Push(10);
Assert.AreEqual(1, heap.Count);
heap.Push(1);
Assert.AreEqual(2, heap.Count);
heap.Push(20);
Assert.AreEqual(3, heap.Count);
heap.Pop();
Assert.AreEqual(2, heap.Count);
heap.Pop();
Assert.AreEqual(1, heap.Count);
heap.Pop();
Assert.AreEqual(0, heap.Count);
}
[TestMethod]
public void Empty()
{
var heap = new MinHeap<int>();
Assert.AreEqual(0, heap.Count);
Assert.IsTrue(heap.Empty);
heap.Push(10);
Assert.IsFalse(heap.Empty);
heap.Push(5);
Assert.IsFalse(heap.Empty);
heap.Pop();
Assert.IsFalse(heap.Empty);
heap.Pop();
Assert.IsTrue(heap.Empty);
}
[TestMethod]
public void PushPeek1()
{
var heap = new MinHeap<int>();
heap.Push(10);
Assert.AreEqual(10, heap.Peek());
}
[TestMethod]
public void PushPeek2()
{
var heap = new MinHeap<int>();
heap.Push(10);
heap.Push(5);
Assert.AreEqual(5, heap.Peek());
}
[TestMethod]
public void PushPeek3()
{
var heap = new MinHeap<int>();
heap.Push(10);
heap.Push(5);
heap.Push(20);
Assert.AreEqual(5, heap.Peek());
}
[TestMethod]
public void PushPeekRandom()
{
const int COUNT = 200;
var heap = new MinHeap<int>();
var rng = new Random();
var elements = new List<int>(COUNT);
int min = Int32.MaxValue;
for (int i = 0; i < COUNT; ++i)
{
int value = rng.Next();
if (value < min)
{
min = value;
}
heap.Push(value);
Assert.AreEqual(min, heap.Peek());
}
}
[TestMethod]
public void PushPop1()
{
var heap = new MinHeap<int>();
heap.Push(10);
Assert.AreEqual(10, heap.Pop());
}
[TestMethod]
public void PushPop2()
{
var heap = new MinHeap<int>();
heap.Push(10);
heap.Push(5);
Assert.AreEqual(5, heap.Pop());
Assert.AreEqual(10, heap.Pop());
}
[TestMethod]
public void PushPop3()
{
var heap = new MinHeap<int>();
heap.Push(10);
heap.Push(5);
heap.Push(20);
Assert.AreEqual(5, heap.Pop());
Assert.AreEqual(10, heap.Pop());
Assert.AreEqual(20, heap.Pop());
}
[TestMethod]
public void PushPopRandom()
{
const int COUNT = 200;
var heap = new MinHeap<int>();
var rng = new Random();
var elements = new List<int>(COUNT);
for (int i = 0; i < COUNT; ++i)
{
int value = rng.Next();
elements.Add(value);
heap.Push(value);
}
elements.Sort();
for (int i = 0; i < COUNT; ++i)
{
Assert.AreEqual(elements[i], heap.Pop());
}
}
[TestMethod]
public void ReplacePeek1()
{
var heap = new MinHeap<int>();
heap.Push(2);
int result = heap.Replace(1);
Assert.AreEqual(2, result);
Assert.AreEqual(1, heap.Peek());
}
[TestMethod]
public void ReplacePeek2()
{
var heap = new MinHeap<int>();
heap.Push(20);
heap.Push(10);
int result = heap.Replace(30);
Assert.AreEqual(10, result);
Assert.AreEqual(20, heap.Peek());
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void PeekEmpty()
{
var heap = new MinHeap<int>();
heap.Peek();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void PopEmpty()
{
var heap = new MinHeap<int>();
heap.Pop();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void ReplaceEmpty()
{
var heap = new MinHeap<int>();
int item = heap.Replace(0);
}
[TestMethod]
public void ConstructFromArray2()
{
int[] elements = new int[] { 10, 20 };
var heap = new MinHeap<int>(elements);
Assert.AreEqual(2, heap.Count);
Assert.AreEqual(10, heap.Peek());
}
[TestMethod]
public void ConstructFromArrayRandom()
{
const int COUNT = 200;
var rng = new Random();
var elements = new int[COUNT];
for (int i = 0; i < COUNT; ++i)
{
elements[i] = rng.Next();
}
var heap = new MinHeap<int>(elements);
Array.Sort(elements);
for (int i = 0; i < COUNT; ++i)
{
Assert.AreEqual(elements[i], heap.Pop());
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructFromNullEnumerable()
{
var heap = new MinHeap<int>((IEnumerable<int>)null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructFromNullComparer()
{
var heap = new MinHeap<int>((IComparer<int>)null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructFromArrayAndNullComparer()
{
var heap = new MinHeap<int>(new int[0], (IComparer<int>)null);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T17:58:51.707",
"Id": "399186",
"Score": "0",
"body": "_Since I needed a MinHeap anyway_ - would you disclose your particular use for it? It would be tremendously useful to know where it can be applied in real-world rather than seein... | [
{
"body": "<p>This is a very nice and clean implementation and looks like there's not much to complain about but I have a few thoughts.</p>\n\n<hr>\n\n<blockquote>\n <p>One thing I'm undecided on is restricting <code>T</code> to be <code>ICompareable<T></code>. While this sends a strong signal about the ... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T17:24:41.540",
"Id": "206931",
"Score": "10",
"Tags": [
"c#",
"heap",
"priority-queue"
],
"Title": "Yet Another MinHeap"
} | 206931 |
<p>I'm learning Swift and I have a following problem: I create a dictionary containing some data, one of which is stored as an array. I want make an operation on this array to add some info. Currently I have managed to achieve this by writing this code:</p>
<pre><code>var myDictionary = [String: Any]()
myDictionary = [
"name": "Wiktor",
"age": 25,
"scores": [1, 2, 3, 4, 5, 6],
]
var l = myDictionary["scores"] as? [Int] ?? [Int]()
l.append(100)
myDictionary["scores"] = l
print("\(myDictionary["scores"]!)")
</code></pre>
<p>This works, meaning an array with value <code>100</code> is printed out, but this solution seems a little bit over engineered to me. Can I do it easier, more like:</p>
<pre><code>myDictionary["scores"].append(100)
</code></pre>
<p>in python?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T18:47:23.350",
"Id": "399198",
"Score": "0",
"body": "Can you provide more context? Where does the dictionary come from? Why do you use a dictionary instead of a custom type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Crea... | [
{
"body": "<p>Since <code>myDictionary</code> values are declared as <code>Any</code>, you could have anything (or even nothing) assigned at \"scores\", so you need to safe-cast the value in to a variable first and then reassign it.</p>\n\n<p>I don't know about Python, but Swift doesn't check dictionary values ... | {
"AcceptedAnswerId": "207152",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T18:43:00.227",
"Id": "206934",
"Score": "0",
"Tags": [
"beginner",
"swift",
"hash-map",
"variant-type"
],
"Title": "Swift append an array when it's been declared as Any"
} | 206934 |
<p>My question is about an easy FileLogger. I want the FileLoggers to store new logs in a <em>collection</em>, and write them in a file only if:<br>
- There are <strong>100 logs</strong> if the <em>collection</em><br>
- It's been more than <strong>1 second</strong> that no new log has been reported<br>
- The logger is being destroyed</p>
<p>Here is my <code>Log</code> class:</p>
<pre><code>public sealed class Log
{
DateTime Date { get; }
string Message { get; }
public Log(string message)
: this(DateTime.Now, message)
{ }
private Log(DateTime writeDate, string message)
{
Date = writeDate;
Message = message;
}
public override string ToString() => $"{Date}: {Message}";
public static implicit operator Log(string message) => new Log(message);
}
</code></pre>
<p>This is the <code>LogCollection</code> (not an <code>ICollection</code> because I don't want to allow removals):</p>
<pre><code>internal class LogCollection
{
private Log[] Logs { get; }
private int CurrentIndex { get; set; }
private bool IsFull => CurrentIndex == Logs.Length;
private Timer Timer { get; }
public LogCollection() : this(100, 1000) { }
public LogCollection(int capacity, int interval)
{
Logs = new Log[capacity];
Timer = new Timer(interval);
Timer.Elapsed += TimerIntervalElapsed;
}
~LogCollection()
{
ReadyingLogs();
}
public void Add(Log log)
{
Logs[CurrentIndex++] = log;
Timer.Start();
if (IsFull)
ReadyingLogs();
}
public void Clear() => CurrentIndex = 0;
private void TimerIntervalElapsed(object sender, ElapsedEventArgs args) => ReadyingLogs();
private void ReadyingLogs()
{
Timer.Stop();
int count = CurrentIndex;
Clear();
LogsReady?.Invoke(this, new EventArgs(Logs.Take(count).ToArray()));
}
internal class EventArgs : System.EventArgs { public Log[] Logs { get; } public EventArgs(Log[] logs) { Logs = logs; } }
internal delegate void EventHandler(object sender, EventArgs args);
public event EventHandler LogsReady;
}
</code></pre>
<p>And finally the <code>FileLogger</code> itself:</p>
<pre><code>public sealed class FileLogger // : ILogger
{
public string FilePath { get; }
private LogCollection Logs { get; set; }
public FileLogger()
{
FilePath = Path.Combine(
Directory.GetCurrentDirectory(),
"Logs",
DateTime.Today.ToString("yyyyMMdd") + ".log"
);
InitializeFilePath();
InitializeCollection();
}
public FileLogger(string filePath)
{
FilePath = filePath;
InitializeFilePath();
InitializeCollection();
}
private void InitializeFilePath()
{
string directory = Path.GetDirectoryName(FilePath);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
if (!File.Exists(FilePath))
File.Create(FilePath);
}
private void InitializeCollection()
{
Logs = new LogCollection();
Logs.LogsReady += LogsReady;
}
public void Log(string message) => Logs.Add(message);
private void LogsReady(object sender, LogCollection.EventArgs args) => WriteLogs(args.Logs);
private void WriteLogs(Log[] logs)
{
using (StreamWriter writer = new StreamWriter(FilePath, true))
{
foreach (Log log in logs)
writer.WriteLine(log + $" (wrote at {DateTime.Now.ToString("hh:mm:ss:fff")})");
writer.Close();
}
}
}
</code></pre>
<p>It works as intended for a single thread with this <code>ConsoleApplication</code>:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
FileLogger logger = new FileLogger();
if (File.Exists(logger.FilePath))
File.Delete(logger.FilePath);
for (int i = 0; i < 150; i++)
logger.Log($"This is log #{i + 1,0:000}");
Thread.Sleep(1500);
for (int i = 0; i < 50; i++)
logger.Log($"This is log #{i + 151,0:000}");
}
}
</code></pre>
<p>Output: </p>
<blockquote>
<p>The first hundred of logs are wrote at <code>t=0ms</code> all together (pack of 100)<br>
The fifty next logs are wrote at <code>t=1050ms</code> all together (timer elapsed)<br>
The fifty last logs are wrote at <code>t=1500ms</code> all together (logger destroyed)</p>
</blockquote>
<hr>
<p><strong>This</strong> is for a single thread, but I am not comfortable with multi-threading. Is this safe if I use it in this state with multiple threads? I want to keep the chronology, and of course do not loose any log...</p>
| [] | [
{
"body": "<p>This design does not convince me. You would achieve much better manintainability and testability when the buffering functionality would be implemented as a decorator. This is, create another logger that takes some other logger as a dependency and adds buffering on top of it. You would then be able... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T21:14:37.053",
"Id": "206938",
"Score": "3",
"Tags": [
"c#",
"multithreading",
"file-system"
],
"Title": "Special FileLogger: write-all after 100 logs or before 1 second without new log"
} | 206938 |
<p>Used to use Laravel's easy to use form validation class, decided to mimic it in JS. I've been learning JS for 4 days now and decided to write my first piece of real code. </p>
<p>I'm pretty sure its full of bad practices, and a lot of it can be improved. I'm looking for some constructive criticism on what I can do better next time, thanks in advance.</p>
<p>Class:</p>
<pre><code>class Validator {
make(rules) {
this.rules = rules;
}
valid() {
if (!this.hasOwnProperty('rules')) {
return true;
}
let errors = [];
let checkFunction = this.checkRuleForElement; // Storing this here because it doesn't seem to work in its invoked scope.
Object.keys(rules).forEach(function(key) {
let formElement = document.getElementsByName(key)[0];
if (formElement == undefined) {
return;
}
let ruleSet = rules[key].split('|');
ruleSet.forEach((rule) => {
let result = checkFunction(rule, formElement)
if (!result.valid && result.message != undefined) {
errors.push(result.message);
}
});
});
return {
valid: errors.length == 0,
errors: errors
}
}
checkRuleForElement(rule, formElement) {
let isValid = true;
let error = "no error";
switch (rule) {
case "required":
if (formElement.value.length <= 0) {
isValid = false;
error = `Form element ${formElement.getAttribute("name")} is required.`;
}
break;
// todo: alpha => only alpha characters
// todo: alphanum => Alphanumeric characters
// todo: num => Numbers only
}
return {
valid: isValid,
message: error
};
}
}
</code></pre>
<p>Setup (usage):</p>
<pre><code>let validator = new Validator();
function checkValidation() {
validator.make({
"username": "required",
"password": "required",
});
let result = validator.valid();
if (!result.valid) {
alert('Something went wrong.');
alert('Errors are: ' + result.errors[0]);
}
else {
alert('Validation was a success.');
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T06:04:47.320",
"Id": "399241",
"Score": "1",
"body": "Welcome to Code Review. For better reviews, I suggest you to add some more information what your code does. Not everyone knows Laravel, so an independent description can improve ... | [
{
"body": "<p>I must admit this is pretty good code for someone that has just started, I like that you use the more \"functional\" style Javascript allow you to use . So good job :) But there are some design issues I see with the code.</p>\n\n<p><strong>1. Factory vs constructor</strong></p>\n\n<p>Your Validato... | {
"AcceptedAnswerId": "206969",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-04T23:22:25.210",
"Id": "206940",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"validation",
"ecmascript-6"
],
"Title": "Simple form validation in javascript"
} | 206940 |
<p>I'm a data scientist attempting to build stronger CS fundamentals, particularly in Data Structures & Algorithms.</p>
<p>Below is my attempt at implementing a Singly Linked List. Looking for advice regarding:</p>
<ol>
<li>Code style</li>
<li>Can space/time complexity of methods be improved? </li>
<li>Debugging in case I missed any edge cases</li>
<li>Checking for premature optimizations</li>
</ol>
<h1>Demonstrates implementation of a linked list and helper Node class</h1>
<pre><code>class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class Linkedlist:
def __init__(self, *args):
self.head = Node()
self.tail = self.head
self.size = 0
# Nodes indexes defined from 0, 1, ..., N - 1 (where N = self.size) but are counted as First Node, Second Node, ..., Nth-Node respectively
self._args = args
if len(self._args) > 0:
for val in self._args:
self.append(val)
def __len__(self):
return self.size
def _get_prev_node(self, index):
"""gets Node previous to given index
i.e. if index is 1, will return Node 0 (1st Node)
i.e. if size of linked list is 6 & index is -3, will return Node 3 (4th Node)
"""
if index < 0:
index += self.size
cur_node = self.head
prev_node_number = 1
while prev_node_number < index:
cur_node = cur_node.next
prev_node_number += 1
return cur_node
def __getitem__(self, index):
if index >= self.size or index < -self.size:
raise IndexError
elif index == 0 or index == -self.size:
return self.head.value
else:
prev_node = self._get_prev_node(index)
cur_node = prev_node.next
return cur_node.value
def __delitem__(self, index):
if index >= self.size or index < -self.size:
raise IndexError
elif index == 0 or index == -self.size:
self.head = self.head.next
else:
prev_node = self._get_prev_node(index)
prev_node.next = prev_node.next.next
if index == -1 or index == self.size - 1:
self.tail = prev_node
self.size -= 1
def __repr__(self):
values = []
cur_node = self.head
for _ in range(self.size):
values.append(str(cur_node.value))
cur_node = cur_node.next
return ' -> '.join(values)
def append(self, value):
if self.head.value is None:
self.head.value = value
else:
new_node = Node(value)
self.tail.next = new_node
self.tail = new_node
self.size += 1
def prepend(self, value):
if self.head.value is None:
self.head.value = value
else:
new_node = Node(value)
new_node.next = self.head
self.head = new_node
self.size += 1
def insert(self, value, index):
# Inserts node with value before given index
if abs(index) > self.size:
raise IndexError
elif index == 0 or index == -self.size:
self.prepend(value)
elif index == self.size:
self.append(value)
else:
prev_node = self._get_prev_node(index)
new_node = Node(value)
new_node.next = prev_node.next
prev_node.next = new_node
self.size += 1
def main():
def disp_attributes(lnk_list_obj):
print(f'Linked List: {lnk_list_obj}')
print(f'\tSize: {len(lnk_list_obj)}')
print(f'\tHead node value: {lnk_list_obj.head.value}')
print(f'\tTail node value: {lnk_list_obj.tail.value}')
print('<< Instantiate empty Linked List >>')
lnk = Linkedlist()
disp_attributes(lnk)
print('<< Append -3, 1, 0 to Linked List >>')
values = -3, 1, 0
for val in values:
lnk.append(val)
disp_attributes(lnk)
print('<< Prepend -12 to Linked List >>')
lnk.prepend(-12)
disp_attributes(lnk)
print(f'Linked List value at first Node: {lnk[0]}')
print('<< Instantiate Linked List with values 1, -2, -6, 0, 2 >>')
lnk2 = Linkedlist(1, -2, -6, 0, 2)
disp_attributes(lnk2)
print('<< Prepend 6 to Linked List >>')
lnk2.prepend(6)
disp_attributes(lnk2)
print(f'Linked List value at second Node: {lnk2[1]}')
print('<< Delete First Node >>')
del lnk2[0]
disp_attributes(lnk2)
print('<< Delete Last Node >>')
del lnk2[-1]
disp_attributes(lnk2)
print('<< Append 7 to LinkedList >>')
lnk2.append(7)
disp_attributes(lnk2)
print('<< Delete 3rd Node >>')
del lnk2[2]
disp_attributes(lnk2)
print('<< Insert -10 before 2nd Node >>')
lnk2.insert(-10, 1)
disp_attributes(lnk2)
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-07T06:49:31.510",
"Id": "399659",
"Score": "1",
"body": "You are not allowed to significantly change your question post after someone posts an answer. Doing so can invalidate answers. See [what should I do when someone answers](https... | [
{
"body": "<p>You should add <code>\"\"\"docstrings\"\"\"\"</code> for each public class and method, describing what it does and how to use it.</p>\n\n<hr>\n\n<h1><code>class Node</code></h1>\n\n<p>This class has members <code>value</code> and <code>next</code>, which are not for use outside of the linked list ... | {
"AcceptedAnswerId": "206948",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T01:43:50.600",
"Id": "206943",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"linked-list"
],
"Title": "Linked List implementation in Python"
} | 206943 |
<p>I got a 2D grid (n x n matrix). The user selects his player in this 2D grid and after that selects another node in this grid to mark his destination position. The player is allowed to move horizontally, vertically or if the player is standing in one of the 4 corners of this grid also diagonally. Also the player can only reach the selected destination if there are no other nodes in the grid blocking the way.</p>
<p>I need to know whether the player can reach the destination or not. To summarize the following needs to be solved:</p>
<blockquote>
<p><strong>Input:</strong></p>
<ul>
<li><p>Start (row: Int, column: Int)</p></li>
<li><p>Destination (row: Int, column: Int)</p></li>
<li><p>func isValidMove(from: Start, to: Destination) -> Bool</p></li>
</ul>
</blockquote>
<p>I have a working implementation however I am more than unhappy with the current state. I think there should be a way more declarative and mathematically correct way to achieve that.</p>
<p>This is what I came up with:</p>
<pre><code>private func isValidHorizontal(move: GameMove, board: GameBoard) -> Bool {
guard let start = move.start else { return false }
guard start.row == move.end.row else { return false }
var from: Int = start.column
var to: Int = move.end.column + 1
if start.column < move.end.column {
from += 1
} else {
from = move.end.column
to = start.column
}
for column in from..<to {
if board.tileType(at: GameBoardPosition(row: start.row, column: column)) != .empty {
return false
}
}
return true
}
private func isValidVertical(move: GameMove, board: GameBoard) -> Bool {
guard let start = move.start else { return false }
guard start.column == move.end.column else { return false }
var from: Int = start.row
var to: Int = move.end.row + 1
if start.row < move.end.row {
from += 1
} else {
from = move.end.row
to = start.row
}
for row in from..<to {
if board.tileType(at: GameBoardPosition(row: row, column: start.column)) != .empty {
return false
}
}
return true
}
private func isValid(position: GameBoardPosition, on board: GameBoard) -> Bool {
return position.row >= 0 && position.row <= board.rows - 1 && position.column >= 0 && position.column <= board.columns - 1
}
private func isValidDiagonal(move: GameMove, board: GameBoard) -> Bool {
guard let start = move.start else { return false }
var currentPosition = start
var walkingIncrement: WalkingIncrement!
if start.row == 0 && start.column == 0 {
walkingIncrement = WalkingIncrement(dx: 1, dy: 1)
} else if start.row == 0 && start.column == board.columns - 1 {
walkingIncrement = WalkingIncrement(dx: -1, dy: 1)
} else if start.row == board.rows - 1 && start.column == 0 {
walkingIncrement = WalkingIncrement(dx: 1, dy: -1)
} else if start.row == board.rows - 1 && start.column == board.columns - 1 {
walkingIncrement = WalkingIncrement(dx: -1, dy: -1)
} else {
return false
}
currentPosition = currentPosition.walk(increment: walkingIncrement)
while(isValid(position: currentPosition, on: board) && currentPosition != move.end) {
if board.tileType(at: currentPosition) != .empty {
return false
}
currentPosition = currentPosition.walk(increment: walkingIncrement)
}
return true
}
</code></pre>
<p>Do you have any advice for me to solve this more practical ?</p>
<p>As asked in the comments I provided a sample playground with a self contained example to better understand the problem and to get a compilable example:<a href="https://gist.github.com/dehlen/1b2d43f5074fc8b68d586cacddfb9e3f" rel="nofollow noreferrer">Playground Gist</a></p>
| [] | [
{
"body": "<p>At several places in your code the explicit type annotation is not\nneeded, for example</p>\n\n<pre><code>var from: Int = start.column\nvar to: Int = move.end.column + 1\n</code></pre>\n\n<p>can be simplified because the compiler infers the type automatically:</p>\n\n<pre><code>var from = start.co... | {
"AcceptedAnswerId": "206974",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T08:07:31.357",
"Id": "206960",
"Score": "2",
"Tags": [
"matrix",
"swift",
"ios",
"pathfinding"
],
"Title": "Finding valid path on 2D Grid"
} | 206960 |
<p>I am using following code to delete color and hide rows that include several criteria before exporting sheets to pdf's. Is there any way to speed up this process as it is taking quite a lot of time to process. Especially in situations when I have several sheets in one workbook and to apply this on each sheet = "printed page".</p>
<pre><code>Sub Color()
Dim myRange As Range
Dim cell As Range
Application.ScreenUpdating = False
Set myRange = ThisWorkbook.Sheets("Print version").Range("Print_Area")
For Each cell In myRange
myRange.Interior.ColorIndex = 0
If cell.HasFormula = True And cell.Value = "" And cell.EntireRow.Hidden = False Then Rows(cell.Row).EntireRow.Hidden = True
Next
Application.ScreenUpdating = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T10:34:44.637",
"Id": "399272",
"Score": "1",
"body": "Welcome to Code Review! What does your data look like? Can you share an (anonimized) sample? How many rows per worksheet are we talking about?"
},
{
"ContentLicense": "CC... | [
{
"body": "<p>Your test for hidden rows suggests you may already have hidden rows.</p>\n\n<p>Nested IF statements could reduce the number of tests to be done.</p>\n\n<p>As you are removing color from all cells, do it before the loop:</p>\n\n<pre><code>Sub Color()\n Dim myRange As Range\n Dim cell As Range... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T09:03:50.000",
"Id": "206964",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Excel VBA speed up code to hide rows/delete color"
} | 206964 |
<p>This code to solve <a href="https://projecteuler.net/problem=23" rel="nofollow noreferrer">Problem 23 in Project Euler</a> gives the correct answer. But, running the last expression takes around 40 seconds. I welcome advice on how to improve performance here.</p>
<pre><code>(defn sum-div [num]
(->> (range 2 (+ 1 (int (Math/ceil (Math/sqrt num)))))
(filter #(= (mod num %) 0))
(map (fn [x]
(let [d (/ num x)]
(if (= x d)
x
[x d]))))
flatten
distinct
(reduce +)
(+ 1)))
(def abundants
(->> (range 12 28123)
(map #(vector % (sum-div %)))
(filter #(> (second %) (first %)))
(map first)
set))
(defn is-sum-of-two-abundants?
[num]
(let [sub-ab (->> abundants
(filter #(< % num))
set)]
(some (fn [ab]
(sub-ab (- num ab)))
sub-ab)))
(->> (range 28124)
(filter (complement is-sum-of-two-abundants?))
(reduce +))
</code></pre>
| [] | [
{
"body": "<p>I played around with this for a good half hour without any luck. I was consistently getting ~57 seconds on my crappy M3 laptop.</p>\n\n<p>As a last ditch effort though, I changed</p>\n\n<pre><code>(->> abundants\n (filter #(< % num))\n set)\n</code></pre>\n\n<p>to </p>\n\n<pre><co... | {
"AcceptedAnswerId": "206989",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T09:33:40.653",
"Id": "206966",
"Score": "0",
"Tags": [
"performance",
"clojure"
],
"Title": "Project Euler 23 implementation"
} | 206966 |
<p>Given a Balanced Parenthesis problem.</p>
<blockquote>
<p>"Balanced Parenthesis</p>
<p>Create a program that checks if in a given string expression all the parenthesis are balanced.</p>
<p>For Example:</p>
<p>(test) - valid</p>
<p>(no() - invalid</p>
<p>()(()) - valid</p>
<p>(123(456)(7))( - invalid</p>
<p>(val()id) - valid</p>
<p>Also, take into account the "\" escape sequences:</p>
<p>(nope\) - invalid</p>
<p>(v\(al) - valid </p>
<p>Too easy? Try doing the same for [] and {} and <>.</p>
<p>(The description from Sololearn application)"</p>
</blockquote>
<p>This is my solution. Do you have any advice? Is it clear enough?</p>
<pre><code>import java.util.Stack;
public class BalancedParenthesis {
private static final Stack<Character> STACK = new Stack<>();
private static final String BRACELETS = "({[<)}]>";
private static final int SEPARATOR = BRACELETS.length() / 2;
private static final char BACKSLASH = '\\';
public static boolean isBalanced(String str) {
int index; char ch;
STACK.clear();
for (int pos = 0; pos < str.length(); pos++) {
ch = str.charAt(pos);
if (ch == BACKSLASH) {
pos ++;
continue ; }
index = BRACELETS.indexOf(ch);
if (isBaceletFind(index)) {
if (isOpenBracelet(index)) STACK.push(ch);
else if (isPopable(index)) STACK.pop();
else return false; }
}
return STACK.empty();
}
private static boolean isPopable(int index) {
return !STACK.empty() && STACK.peek() == BRACELETS.charAt(index - SEPARATOR);
}
private static boolean isBaceletFind(int index) {
return index != -1;
}
private static boolean isOpenBracelet(int index) {
return index < SEPARATOR;
}
public static void checkBalance(String str) {
System.out.print("\"" + str + "\" is");
System.out.println((isBalanced(str) ? "" : " not") + " balanced");
}
public static void main(String[] args) {
checkBalance("");
checkBalance("\\");
checkBalance("\\(");
checkBalance("(({[<>]}))");
checkBalance("))");
checkBalance("(({[<(>]}))");
checkBalance("(({[<\\(>]}))");
}
}
</code></pre>
| [] | [
{
"body": "<p>I am not a pro Java programmer, so I will only talk about the algorithm</p>\n\n<p>Your reasoning is good, a stack is the right container to use, but:</p>\n\n<ul>\n<li>You don't catch the case where backslash itself is escaped </li>\n<li>You can avoid <code>SEPERATOR</code> in two way:\n\n<ul>\n<li... | {
"AcceptedAnswerId": "207030",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T09:36:30.163",
"Id": "206967",
"Score": "1",
"Tags": [
"java",
"strings",
"interview-questions",
"balanced-delimiters",
"escaping"
],
"Title": "Balanced parenthesis, with backslash escaping"
} | 206967 |
<p>What I'm trying to achieve is
Given a predicate function and an action which returns the object to check,
check predicate, retry and fail after numTries .. or success .</p>
<p>Purpose of this function is : </p>
<p>During constant data collection from network resources ( web, apis, .. ) return of network operations not successful every time ( because of bad servers, network problems , etc.. ). If you need that data you should retry, and if you do this kind of ops. a lot, you should have a function to handle this.</p>
<p>I'm looking for are there better ways to do this.</p>
<pre><code>public static async Task<bool> CheckAndRetryAsync<T>
(
T _object, //object to check state
Func<T, bool> predicate, Func<Task<T>> action, // object creation func
int sleep = 150, // sleep ms. between tries
int numTries = 6, // ..
bool rethrowExceptions = false, // should rethrow exc. during object creation
ManualResetEvent mr = null
)
{
int tries = 0;
bool success = false;
while (true)
{
try
{
_object = await action();
success = predicate(_object);
if (!success && tries < numTries)
{
tries++;
await Task.Delay(sleep);
}
else
{
//goto exit;
break;
}
}
catch (Exception e)
{
if (rethrowExceptions)
throw;
if (tries < numTries){
tries++;
await Task.Delay(sleep);
}
else{
goto exit;
}
}
}
exit:
if(mr != null)
mr.Set();
return success;
}
</code></pre>
<p>Tests for function : </p>
<pre><code>public class StaticUtilFuncTests
{
ManualResetEvent mr = new ManualResetEvent(false);
[Fact]
public async Task T_010_CheckAndRetryAsync()
{
int tries = 1;
mr.Reset();
Stopwatch sw = new Stopwatch();
sw.Start();
TObj ttx = null;
bool succsess = await CheckAndRetryAsync<TObj>(ttx,
(o) => (o != null && o.Value != ""),
async () =>
{
if (tries <= 4)
{
ttx = new TObj();
tries++;
}
else
{
ttx = new TObj("sdf");
}
mr.Set();
return ttx;
},
numTries: 5, sleep: 400
);
mr.WaitOne();
long elapsed = sw.ElapsedMilliseconds;
Assert.True(elapsed >= 1600l); // numtries * sleep
Assert.True(succsess);
Assert.True(tries == 5);
}
[Fact]
public async Task T_011_CheckAndRetryAsync()
{
mr.Reset();
Stopwatch sw = new Stopwatch();
sw.Start();
TObj ttx = null;
bool succsess = await CheckAndRetryAsync<TObj>(
ttx,
(o) => (o != null && o.Value != ""),
async () =>
{
ttx = new TObj("");
mr.Set();
return ttx;
},
numTries: 3, sleep: 1100
);
mr.WaitOne();
long elapsed = sw.ElapsedMilliseconds;
Assert.True(elapsed >= 3300l); // numtries * sleep
Assert.False(succsess);
}
[Fact]
public async Task T_012_CheckAndRetryAsync()
{
mr.Reset();
//Mock<TObj> to = new Mock<TObj>();
//to.Setup(
// m => m.)
Stopwatch sw = new Stopwatch();
sw.Start();
TObj ttx = null;
bool succsess = await CheckAndRetryAsync<TObj>(
ttx,
(o) => (o != null && o.Value != ""),
async () =>
{
ttx = new TObj("",true);
//mr.Set();
return ttx;
},
numTries: 30, sleep: 50, mr: mr
);
mr.WaitOne();
long elapsed = sw.ElapsedMilliseconds;
Assert.True(elapsed >= 1500l); // numtries * sleep
Assert.False(succsess);
}
}
public class TObj
{
public string Value;
public TObj(string value = "" , bool testing = false)
{
if(value == "" && testing)
throw new Exception();
Value = value;
}
}
}
</code></pre>
<p>A real usage example : </p>
<pre><code> BittrexBtcTicker btcTicker = null;
success |= await CheckAndRetryAsync<BittrexBtcTicker>(
btcTicker, // object we need to get ( also save db )
(o) => (o != null && o.Value > 0), // predicate not null, and bigger than 0
async () =>
{
mr.Reset(); // a noise but needed during async ops.
btcTicker = await BittrexClient
.GetTicker(saveDb: true, updateDb: updateDb, _context: context, mr: mr); // call to object creation..
mr.WaitOne(); // wait to op. complete
return btcTicker;
}
);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T12:04:23.487",
"Id": "399293",
"Score": "1",
"body": "Welcome to Code Review. Please try to improve the first paragraph of your question. As it currently stands, I'm having trouble deciphering it. You have an action and a prediction... | [
{
"body": "<p><strong>Design</strong></p>\n\n<ul>\n<li>I see you fixed the bug where the method would get stuck in an infinite loop when <code>action</code> throws an exception, but note how similar the normal and the exception paths are now. The method can be simplified by incrementing <code>tries</code> befor... | {
"AcceptedAnswerId": "207045",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T11:33:54.167",
"Id": "206975",
"Score": "2",
"Tags": [
"c#",
"beginner",
"error-handling",
"async-await"
],
"Title": "Simple but important function to check and retry given action's result"
} | 206975 |
<p>This is a quick and dirty QBE method that covers about 60% of my use cases in my DAO. I just wanted to see if someone would take a quick look at it to see if there are any issues.</p>
<pre><code>public List<Order> orderQuery(Order order) {
StringBuilder sql = new StringBuilder();
sql.append("select * from orders ");
List<String> clauses = new ArrayList<String>();
List<Object> values = new ArrayList<>();
if (order.getOrderID() != null) {
clauses.add("order_id = ?" + order.getOrderID());
values.add(order.getOrderID());
}
if (order.getAccountCode() != null) {
clauses.add("acct_nmbr = ?");
values.add(order.getAccountCode());
}
// TODO: Once I switch this to the AccountType enum, use order.getAccountType().getCode()
if (order.getAccountType() != null) {
clauses.add("acct_typ = ?");
values.add(order.getAccountType());
}
if (order.getRsid() != null) {
clauses.add("rsid = ?");
values.add(order.getRsid());
}
if (order.getUserID() != null) {
clauses.add("user_id = ?");
values.add(order.getUserID());
}
if (order.getCurrentStatus() != null) {
values.add(order.getCurrentStatus());
}
if (!clauses.isEmpty()) {
sql.append("where ");
}
String whereClause = clauses.stream().collect(Collectors.joining(" and "));
sql.append(whereClause);
List<Order> result = jdbcTemplate.query(sql.toString(), orderRowMapper, values.toArray());
return result;
}
</code></pre>
<p>Generally it's simple:
1. Put the SQL clause in a StringBuilder.
2. Check the various fields I care about and if they aren't null, add a clause for them.
3. Turn the list of SQL where clauses into a single string
4. Build the entire SQL statement.
5. Execute it with Spring JDBC Template.</p>
<p>Any external input?</p>
| [] | [
{
"body": "<p>Be careful of SQL injections.</p>\n\n<p>Assuming that the <code>Order</code> object is sanitized, then the only suggestion I'd make is to make a class for your order query and extract the logic from your method into that class.</p>\n\n<p>A quick example would be that:</p>\n\n<pre><code>public clas... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T12:49:25.030",
"Id": "206978",
"Score": "1",
"Tags": [
"java",
"spring",
"jdbc"
],
"Title": "Simple JDBC Query By Example (QBE) for Spring JDBC Template"
} | 206978 |
<p>I'm trying to learn Ajax better, and I'm developing an application in CodeIgniter.</p>
<p>The following code is working, there are no errors. But for every function and call I think I'm repeating callbacks too often.</p>
<pre><code> <script type="text/javascript">
$(document).ready(function(){
show_costumer();
function show_costumer(){
$.ajax({
type : 'ajax',
url : "<?php echo base_url(); ?>admin/costumer/costumer_data",
async : true,
dataType : 'JSON',
success : function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td><input type="checkbox" class="checkbox" data-id="'+data[i].id_anagrafica+'" /></td>'+
'<td>'+data[i].nome+'</td>'+
'<td>'+data[i].cognome+'</td>'+
'<td>'+data[i].telefono+'</td>'+
'<td>'+data[i].email+'</td>'+
'<td>'+data[i].cf+'</td>'+
'<td>'+data[i].data_nascita+'</td>'+
'<td>'+data[i].comune+'</td>'+
'<td>'+data[i].tipo_attivita+'</td>'+
'<td>'+data[i].note_anagrafica+'</td>'+
'<td>'+data[i].note_tipo_attivita+'</td>'+
'<td style="text-align:right;">'+
'<a href="javascript:void(0);" class="btn btn-info btn-sm item_edit" data-id_anagrafica="'+data[i].id_anagrafica+'" data-nome="'+data[i].nome+'" data-cognome="'+data[i].cognome+'" data-telefono="'+data[i].telefono+'" data-email="'+data[i].email+'" data-cf="'+data[i].cf+'" data-nascita="'+data[i].data_nascita+'" data-comune="'+data[i].comune+'"data-tipo_attivita="'+data[i].tipo_attivita+'" data-note_anagrafica="'+data[i].note_anagrafica+'" data-note_tipo_attivita="'+data[i].note_tipo_attivita+'">Edit</a>'+' '+
'<a href="javascript:void(0);" class="btn btn-danger btn-sm item_delete" data-id_anagrafica="'+data[i].id_anagrafica+'">Delete</a>'+
'</td>'+
'</tr>';
}
$('#show_costumer').html(html);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if( search != "" ){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>admin/costumer/search",
data:'search='+$('#search_text').val(),
dataType: "JSON",
cache: false,
success:function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td><input type="checkbox" class="checkbox" data-id="'+data[i].id_anagrafica+'" /></td>'+
'<td>'+data[i].nome+'</td>'+
'<td>'+data[i].cognome+'</td>'+
'<td>'+data[i].telefono+'</td>'+
'<td>'+data[i].email+'</td>'+
'<td>'+data[i].cf+'</td>'+
'<td>'+data[i].data_nascita+'</td>'+
'<td>'+data[i].comune+'</td>'+
'<td>'+data[i].tipo_attivita+'</td>'+
'<td>'+data[i].note_anagrafica+'</td>'+
'<td>'+data[i].note_tipo_attivita+'</td>'+
'<td style="text-align:right;">'+
'<a href="javascript:void(0);" class="btn btn-info btn-sm item_edit" data-id_anagrafica="'+data[i].id_anagrafica+'" data-nome="'+data[i].nome+'" data-cognome="'+data[i].cognome+'" data-telefono="'+data[i].telefono+'" data-email="'+data[i].email+'" data-cf="'+data[i].cf+'" data-nascita="'+data[i].data_nascita+'" data-comune="'+data[i].comune+'"data-tipo_attivita="'+data[i].tipo_attivita+'" data-note_anagrafica="'+data[i].note_anagrafica+'" data-note_tipo_attivita="'+data[i].note_tipo_attivita+'">Edit</a>'+' '+
'<a href="javascript:void(0);" class="btn btn-danger btn-sm item_delete" data-id_anagrafica="'+data[i].id_anagrafica+'">Delete</a>'+
'</td>'+
'</tr>';
}
$('#show_costumer').html(html);
},
error: function(data){
return false;
}
});
}
else{
show_costumer();
}
});
//Save product
$('#btn_save').on('click',function(){
var id_anagrafica = $('#id_anagrafica').val();
var nome = $('#nome').val();
var cognome = $('#cognome').val();
var telefono = $('#telefono').val();
var email = $('#email').val();
var cf = $('#cf').val();
var data_nascita = $('#data_nascita').val();
var comune = $('#comune').val();
var tipo_attivita = $('#tipo_attivita').val();
var note_anagrafica = $('#note_anagrafica').val();
var note_tipo_attivita = $('#note_tipo_attivita').val();
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>admin/costumer/save",
dataType : "JSON",
data : {id_anagrafica:id_anagrafica, nome:nome , cognome:cognome, telefono:telefono, email:email, cf:cf, data_nascita:data_nascita, comune:comune, tipo_attivita:tipo_attivita, note_anagrafica:note_anagrafica, note_tipo_attivita:note_tipo_attivita},
success: function(data){
$('[name="id_anagrafica"]').val("");
$('[name="nome"]').val("");
$('[name="cognome"]').val("");
$('[name="telefono"]').val("");
$('[name="email"]').val("");
$('[name="cf"]').val("");
$('[name="data_nascita"]').val("");
$('[name="comune"]').val("");
$('[name="tipo_attivita"]').val("");
$('[name="note_anagrafica"]').val("");
$('[name="note_tipo_attivita"]').val("");
$('#addcostumer').modal('close');
show_costumer();
}
});
return false;
});
//get data for update record
$('#show_costumer').on('click','.item_edit',function(){
var id_anagrafica = $(this).data('id_anagrafica');
var nome = $(this).data('nome');
var cognome = $(this).data('cognome');
var telefono = $(this).data('telefono');
var email = $(this).data('email');
var cf = $(this).data('cf');
var data_nascita = $(this).data('data_nascita');
var comune = $(this).data('comune');
var tipo_attivita = $(this).data('tipo_attivita');
var note_anagrafica = $(this).data('note_anagrafica');
var note_tipo_attivita = $(this).data('note_tipo_attivita');
$('#Modal_Edit').modal('open');
$('[name="id_anagrafica_edit"]').val(id_anagrafica);
$('[name="nome_edit"]').val(nome);
$('[name="cognome_edit"]').val(cognome);
$('[name="telefono_edit"]').val(telefono);
$('[name="email_edit"]').val(email);
$('[name="cf_edit"]').val(cf);
$('[name="data_nascita"]').val(data_nascita);
$('[name="comune_edit"]').val(comune);
$('[name="tipo_attivita_edit"]').val(tipo_attivita);
$('[name="note_anagrafica_edit"]').val(note_anagrafica);
$('[name="note_tipo_attivita_edit"]').val(note_tipo_attivita);
});
//update record to database
$('#btn_update').on('click',function(){
var id_anagrafica = $('#id_anagrafica_edit').val();
var nome = $('#nome_edit').val();
var cognome = $('#cognome_edit').val();
var telefono = $('#telefono_edit').val();
var email = $('#email_edit').val();
var cf = $('#cf_edit').val();
var data_nascita = $('#data_nascita_edit').val();
var comune = $('#comune_edit').val();
var tipo_attivita = $('#tipo_attivita_edit').val();
var note_anagrafica = $('#note_anagrafica_edit').val();
var note_tipo_attivita = $('#note_tipo_attivita_edit').val();
$.ajax({
type : "POST",
url : "<?php base_url( 'admin/costumer/update' ) ?>",
dataType : "JSON",
data : {id_anagrafica:id_anagrafica, nome:nome , cognome:cognome, telefono:telefono, email:email, cf:cf, data_nascita:data_nascita, comune:comune, tipo_attivita:tipo_attivita, note_anagrafica:note_anagrafica, note_tipo_attivita:note_tipo_attivita},
success: function(data){
$('[name="id_anagrafica_edit"]').val("");
$('[name="nome_edit"]').val("");
$('[name="cognome_edit"]').val("");
$('[name="telefono_edit"]').val("");
$('[name="email_edit"]').val("");
$('[name="cf_edit"]').val("");
$('[name="data_nascita_edit"]').val("");
$('[name="comune_edit"]').val("");
$('[name="tipo_attivita_edit"]').val("");
$('[name="note_anagrafica_edit"]').val("");
$('[name="note_tipo_attivita_edit"]').val("");
$('#Modal_Edit').modal('close');
show_costumer();
}
});
return false;
});
//get data for delete record
$('#show_costumer').on('click','.item_delete',function(){
var id_anagrafica = $(this).data('id_anagrafica');
$('#Modal_Delete').modal('open');
$('[name="id_anagrafica_delete"]').val(id_anagrafica);
});
//delete record to database
$('#btn_delete').on('click',function(){
var id_anagrafica =$('#id_anagrafica_delete').val();
$.ajax({
type : "POST",
url : "<?php base_url('admin/costumer/delete') ?>",
dataType : "JSON",
data : {id_anagrafica:id_anagrafica},
success: function(data){
$('[name="id_anagrafica_delete"]').val("");
$('#Modal_Delete').modal('close');
show_costumer();
}
});
return false;
});
//delete all record to database
$('#delete_all_costumers').on('click',function()
{
if(this.checked)
{
$('.checkbox').each(function()
{
this.checked = true;
}
);
}
else
{
$('.checkbox').each(function()
{
this.checked = false;
}
);
}
});
$('.delete_all_customers').on('click', function(e) {
var allVals = [];
$(".checkbox:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
} else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: "<?php base_url( 'admin/costumer/delete_all' ) ?>
",
type: 'POST',
data: 'id_anagrafica='+join_selected_values,
success: function (data) {
console.log(data);
$(".checkbox:checked").each(function() {
$(this).parents("tr").remove();
});
alert("Item Deleted successfully.");
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('.pagination').on('click','a',function(e){
e.preventDefault();
var page_number = $(this).attr('data-ci-pagination-page');
loadPagination(page_number);
});
loadPagination(0);
// Load pagination
function loadPagination(page_number){
$.ajax({
url: '<?=base_url()?>admin/costumer/load_record/'+page_number,
type: 'get',
dataType: 'json',
success: function(response){
$('.pagination').html(response.pagination);
createTable(response.result,response.row);
}
});
}
// Create table list
function createTable(result,sno){
sno = Number(sno);
$('#table tbody').empty();
for(index in result){
var id_anagrafica = result[index].id_anagrafica;
var nome = result[index].nome;
var cognome = result[index].cognome;
var telefono = result[index].telefono;
var email = result[index].email;
var cf = result[index].cf;
var data_nascita = result[index].data_nascita;
var comune = result[index].comune;
var tipo_attivita = result[index].tipo_attivita;
var note_anagrafica = result[index].note_anagrafica;
var note_tipo_attivita = result[index].note_tipo_attivita;
// content = content.substr(0, 60) + " ...";
// var link = result[index].link;
sno+=1;
var tr = "<tr>";
tr += "<td><input type='checkbox' id='checkbox' class='checkbox' data-id="+ id_anagrafica +" /></td>";
tr += "<td><div class='row_data' edit_type='click' col_name='fname'>"+ nome +"</div></td>";
tr += "<td>"+ cognome +"</td>";
tr += "<td>"+ telefono +"</td>";
tr += "<td>"+ email +"</td>";
tr += "<td>"+ cf +"</td>";
tr += "<td>"+ data_nascita +"</td>";
tr += "<td>"+ comune +"</td>";
tr += "<td>"+ tipo_attivita +"</td>";
tr += "<td>"+ note_anagrafica +"</td>";
tr += "<td>"+ note_tipo_attivita +"</td>";
tr += '<td style="text-align:right;">'+
'<a href="javascript:void(0);" class="btn btn-info btn-sm item_edit" data-id_anagrafica="'+ id_anagrafica +'" data-nome="'+nome+'" data-cognome="'+cognome+'" data-telefono="'+telefono+'" data-email="'+email+'" data-cf="'+cf+'" data-nascita="'+data_nascita+'" data-comune="'+comune+'"data-tipo_attivita="'+tipo_attivita+'" data-note_anagrafica="'+note_anagrafica+'" data-note_tipo_attivita="'+note_tipo_attivita+'">Edit</a>'+' '+
'<a href="javascript:void(0);" class="btn btn-danger btn-sm item_delete" data-id_anagrafica="'+id_anagrafica+'">Delete</a>'+
'</td>';
tr += "</tr>";
$('#table tbody').append(tr);
}
}
//--->make div editable > start
$(document).on('click', '.row_data', function(event)
{
event.preventDefault();
//make div editable
$(this).closest('div').attr('contenteditable', 'true');
$(this).focus();
})
//--->make div editable > end
});
</script>
</code></pre>
<p>Is this a good approach? What if I need to change or add a function? Do I need to edit every single function or is there a better way to write this code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T13:25:51.123",
"Id": "399300",
"Score": "0",
"body": "Did you test whether it works like you want it to? How?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T13:27:18.800",
"Id": "399301",
"Sc... | [
{
"body": "<p>Take a step back and forget about what your code does; what does it <em>look like</em>? Find the text that's duplicated, then try sticking those in functions. If this code uses variables, make these arguments for your functions. If a few snippets of code are 90% similar, move one copy to a new fun... | {
"AcceptedAnswerId": "207033",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T13:21:56.837",
"Id": "206980",
"Score": "3",
"Tags": [
"javascript",
"php",
"jquery",
"ajax",
"codeigniter"
],
"Title": "Ajax table action and process"
} | 206980 |
<p>I've create a program that finds mixed duo within a string. It removes characters from a string that do not form the first mixed duo. It does not rearrange the order of the string, it ony remove characters to reveal the mixed duo...... aka "abababab", "chchchchc", "!s!s!s!". </p>
<p>Tell me what do you think of this code? Is my solution too complex? is it too slow?, is the code messy? is it maintainable?, am I following industry norms? Your honest opinion and critique of my style, logic, and approach is what I desire.</p>
<pre><code>#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
struct Data{
std::map<char,char> data1;
std::string data2;
};
bool finalVerification(std::string input){
////////////////
//DECLARATIONS//
////////////////
int size_Of_String;
char a;
char b;
//When flip = true a fails, when flip = false b fails;
bool flip;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
a = input[0];
b = input[1];
//When flip = true a fails, when flip = false b fails;
flip = false;
//////////////////////////////
//RULE CHECKING BEFORE LOGIC//
//////////////////////////////
//Last minute condition check
if(input.size() < 4){return false;}
if(input.size() == 4){
if((input[0] == input[2])&&(input[1] == input[3])){ return true;}
else {return false;}
}
//////////////////
//IMPLEMENTATION//
//////////////////
//Go through the string array from both ends.
for(int i=0; i<size_Of_String; i++)
{
if((input[i] != a) && (flip == false))
{
return false;
}
else if((input[i] != b ) && (flip == true))
{
return false;
}
if(flip == true)
{
flip = false;
}
else if (flip == false) {
flip = true;
}
}
return true;
}
Data findUniqueChar(std::string input)
{
////////////////
//DECLARATIONS//
////////////////
int size_Of_String;
int run_Through;
std::string temp;
std::map<char, char> records;
Data output;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
run_Through = size_Of_String;
temp = "";
//////////////////
//IMPLEMENTATION//
//////////////////
//Find all the unique characters and record them in this map.
for (int i=0; i<run_Through; i++){
if(input[i] != input[0])
{
//Assume this can form a twisted pair with the first element.
if(records.find(input[i]) == records.end()){
records[input[i]] = '0';
temp += input[i];
}
}
}
output.data1 = records;
output.data2 = temp;
return output;
}
std::string quickCheckFix(std::string input)
{
///////////////
//DECLARATION//
///////////////
int size_Of_String;
std::string output;
char tmp;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
output = input;
//////////////////
//IMPLEMENTATION//
//////////////////
//Go through the string array from both ends.
for(int i=0; i<size_Of_String/2; i++)
{
//If duplicates are encountered remove all instances of that character from the string and break out of the loop
if(output[i] == output[i+1])
{
tmp = output[i];
output.erase(std::remove(output.begin(), output.end(), tmp), output.end());
break;
}
else if(output[size_Of_String - 1 - i] == output[size_Of_String - 2 - i])
{
tmp = output[size_Of_String - 1 - i];
output.erase(std::remove(output.begin(), output.end(), tmp), output.end());
break;
}
}
//Call yourself again if output has been changed. set output to equal the value of the call. Use the altered output as the argument,
if(output != input){
output = quickCheckFix(output);
}
return output;
}
std::string condition(std::string input)
{ ////////////////
//DECLARATIONS//
////////////////
int size_Of_String;
std::string output;
std::string pair_Values;
std::string saved_Failures;
//False = alpha fail, true = omega fails
Data records;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
output = input;
pair_Values += input[0];
pair_Values += input[1];
saved_Failures = "";
// bool keys were replaced with chars key for more options. 0 = false, 1 = true, X = failure!
records = findUniqueChar(input);
//////////////////
//IMPLEMENTATION//
//////////////////
for(int i=0; i<size_Of_String; i++)
{
//----------------------------------//
//--------Ender conditions----------//
//----------------------------------//
//If there are no more unique characaters that could succeed it is finally safe to remove the 1st element from the string.
if(saved_Failures.size() == records.data2.size()){
//Free yourself from the loop first
break;
}
//---------------------------------------//
//--------Logic and computation----------//
//---------------------------------------//
//If the first elements was encountered again
if(input[i] == input[0])
{
//Record all true key as failures
for(int a=0; a<records.data1.size(); a++)
{
if(records.data1.find(records.data2[a])->second == '1'){
saved_Failures += records.data2[a];
records.data1[records.data2[a]] = 'X';
}
}
//Change all the false keys to true
for(int a=0; a<records.data1.size(); a++)
{
if(records.data1.find(records.data2[a])->second == '0'){
records.data1[records.data2[a]] = '1';
pair_Values[1] = input[i];
}
}
}
else if(records.data1.find(input[i])->second == '1'){ //If the key was found again while being true flip the value to false.
records.data1[input[i]] = '0';
pair_Values[1] = input[i];
}
else if(records.data1.find(input[i])->second == '0'){ //If the key was found again while being false record it as failure.
saved_Failures += input[i];
records.data1[input[i]] = 'X'; // Will never get in the loop again
}
}
//If if failed go ahead and remove the first element instances and call your friend again.
if(saved_Failures.size() == records.data2.size()){
output.erase(std::remove(output.begin(), output.end(), input[0]), output.end());
}
//If you think it succeeded remove all other characters.
else{
//Remove the 1st element character from this string
saved_Failures.erase(std::remove(saved_Failures.begin(), saved_Failures.end(), input[0]), saved_Failures.end());
//Start from the top and work your way to the bottom.
for(int i=0; i<saved_Failures.size(); i++){
output.erase(std::remove(output.begin(), output.end(), saved_Failures[i]), output.end());
}
}
return output;
}
std::string findPair(std::string input)
{
///////////////
//DECLARATION//
///////////////
std::string output;
std::string pair_Values;
////////////////////////////////////////////////
//RULE CHECKING BEFORE LOGIC & INITIALIZATION //
////////////////////////////////////////////////
//Check if the string size is invalid
if(input.size() < 4){return "";}
//If the string is valid see if you can cut it down to size before processing. Apply rule 1 again in case you got lucky
input = quickCheckFix(input);
if(input.size() < 4){return "";}
//Super lucky condition just to save more time.
if(input.size() == 4){
if((input[0] == input[2])&&(input[1] == input[3])){ return input;}
else {return "";}
}
///////////////////////
// INITIALIZATION //
///////////////////////
//Only munipulate the output string, and begin the set up for the logic loop
output = input;
pair_Values += output[0];
pair_Values += output[1];
//////////////
// LOGIC //
//////////////
output = condition(output);
//If the function return false, it is on
switch(finalVerification(output)){
case true: break;
case false: output = findPair(output);
}
return output;
}
void autoStringRead()
{
///////////////
//DECLARATION//
///////////////
std::ifstream inputs( "pairs-in.txt" );
std::string line;
std::string done;
std::ofstream results;
///////////////////////
// INITIALIZATION //
///////////////////////
//Generate the file
results.open ("results.txt");
//Make sure this exists
if( inputs == NULL ) { return; }
while (getline(inputs, line)) {
done = findPair(line);
results << done <<std::endl;
std::cout<< line << std::endl;
std::cout<< done << std::endl;
}
inputs.close();
results.close();
}
int main()
{
autoStringRead();
system("pause");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T14:16:37.087",
"Id": "399307",
"Score": "0",
"body": "\"Is my solution too complex?\" Yes. Can you tell us why you took the approach you did? Because a lot about your code is not obvious."
},
{
"ContentLicense": "CC BY-SA 4.... | [
{
"body": "<p>A few nitpicks off the bat since you asked about messiness. First, use a tool (any tool) to automatically format your code. Your braces and indentation are all over the place. Second, I would remove all of the \"section\" comments from your code. It's obvious that, for example, the first few lines... | {
"AcceptedAnswerId": "207016",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T14:08:44.720",
"Id": "206983",
"Score": "3",
"Tags": [
"c++",
"performance",
"object-oriented",
"strings"
],
"Title": "Mixed Duo String Generator"
} | 206983 |
<p>I've been learning Rust for the past few days and I just passed the "Smart Pointers" chapter. To check what I've learned I've decided to implement a doubly linked list.</p>
<p>My question is, is this appropriate way to implement one and what can be improved? Which is better - using <code>Rc<T></code> or <code>Box<T></code> for the node values?</p>
<p>lib.rs</p>
<pre><code>use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Error;
type NextNode<T> = Rc<RefCell<Node<T>>>;
type PrevNode<T> = Weak<RefCell<Node<T>>>;
pub struct List<T> {
head: Option<NextNode<T>>,
tail: Option<PrevNode<T>>,
size: usize,
}
impl<T: Debug> Debug for List<T> {
fn fmt(&self, f: &'_ mut Formatter) -> Result<(), Error> {
writeln!(f, "List size: {:?}", self.size);
if let Some(ref h) = self.head {
let mut node = Rc::clone(h);
loop {
let prev = match node.borrow().prev {
None => None,
Some(ref p) => Some(p.upgrade().unwrap())
};
let next = match node.borrow().next {
None => None,
Some(ref n) => Some(Rc::clone(n))
};
let p_val = match prev {
None => None,
Some(ref t) => Some(Rc::clone(&t.borrow().value))
};
let n_val = match next {
None => None,
Some(ref t) => Some(Rc::clone(&t.borrow().value))
};
let c_val = Rc::clone(&node.borrow().value);
writeln!(f, "{:?} <<--prev--<< {:?} >>--next-->> {:?}", p_val, c_val, n_val);
match next {
None => break,
Some(ref t) => node = Rc::clone(t),
}
}
}
return Ok(());
}
}
#[derive(Debug)]
struct Node<T> {
next: Option<NextNode<T>>,
prev: Option<PrevNode<T>>,
value: Rc<T>,
}
impl<T> List<T> {
pub fn new() -> List<T> {
return List {
head: None,
tail: None,
size: 0,
};
}
pub fn push_head(&mut self, value: T) {
let boxed_value = Rc::new(value);
let new_node = Node::new_unlinked(boxed_value);
let back_link = Some(Rc::downgrade(&new_node));
match self.head {
None => {
self.tail = back_link;
}
Some(ref mut h) => {
h.borrow_mut().prev = back_link;
new_node.borrow_mut().next = Some(Rc::clone(h));
}
}
self.head = Some(new_node);
self.size += 1;
}
pub fn push_tail(&mut self, value: T) {
let boxed_value = Rc::new(value);
let new_node = Node::new_unlinked(boxed_value);
let weak_link = Some(Rc::downgrade(&new_node));
match self.tail {
None => {
self.head = Some(new_node);
}
Some(ref t) => {
new_node.borrow_mut().prev = Some(Weak::clone(t));
let next_ref = t.upgrade().unwrap();
next_ref.borrow_mut().next = Some(new_node);
}
}
self.tail = weak_link;
self.size += 1;
}
}
impl<T> Node<T> {
fn new_unlinked(value: Rc<T>) -> NextNode<T> {
return Rc::new(RefCell::new(Node {
next: None,
prev: None,
value,
}));
}
}
</code></pre>
<p>main.rs</p>
<pre><code>extern crate linkedlist;
use linkedlist::List;
fn main() {
let mut list: List<i32> = List::new();
list.push_head(3);
list.push_head(2);
list.push_head(1);
list.push_tail(4);
list.push_tail(5);
list.push_tail(6);
println!("{:#?}", list);
}
</code></pre>
<p>Debug output: </p>
<pre><code>List size: 6
None <<--prev--<< 1 >>--next-->> Some(2)
Some(1) <<--prev--<< 2 >>--next-->> Some(3)
Some(2) <<--prev--<< 3 >>--next-->> Some(4)
Some(3) <<--prev--<< 4 >>--next-->> Some(5)
Some(4) <<--prev--<< 5 >>--next-->> Some(6)
Some(5) <<--prev--<< 6 >>--next-->> None
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-06T06:57:57.870",
"Id": "399429",
"Score": "1",
"body": "You might be interested in [*Learning Rust With Entirely Too Many Linked Lists*](https://cglab.ca/~abeinges/blah/too-many-lists/book/). It's a little bit older (~2 years) but sti... | [
{
"body": "<p>Some quick caveats:</p>\n\n<ol>\n<li>Linked Lists are a rarely useful data structure, outside of a learning exercise you should almost never use them.</li>\n<li>The techniques for implementing typical rust code (which primarily uses already crafted data structures) is quite different from rust cod... | {
"AcceptedAnswerId": "207187",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T14:45:41.663",
"Id": "206986",
"Score": "6",
"Tags": [
"linked-list",
"rust",
"pointers"
],
"Title": "Implementing a doubly linked list with smart pointers"
} | 206986 |
<p>I've create a program that finds mixed duo within a string. It removes characters from a string that do not form the first mixed duo. It does not rearrange the order of the string, it ony remove characters to reveal the mixed duo...... aka "abababab", "chchchchc", "!s!s!s!".</p>
<p>What is a mixed duo? It is the combination of 2 characters repeating in oscillating fashion. for example the string "@@byb:b4bb:4b:4@@ybbb@b@:@@4" mixed duo would be ":4:4:4:4 because upon removal of every other character these two characters confirmed to the condition. @b does not form a mixed duo from the string because removal of all other character form this string forms "@@bbbbbb@@bbb@b@@@". It is not a repeating pattern of the first 2 characters otherwise it would look like this "@b@b@b@b@b@b@b"</p>
<p>Tell me what do you think of this code? Is my solution too complex? is it too slow?, is the code messy? is it maintainable?, am I following industry norms? Your honest opinion and critique of my style, logic, and approach is what I desire.</p>
<p>Below is an example of input and output. </p>
<p>input: @@byb:b4bb:4b:4@@ybbb@b@:@@4</p>
<p>output: :4:4:4:4</p>
<pre><code>#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
struct Data{
std::map<char,char> data1;
std::string data2;
};
bool finalVerification(std::string input){
////////////////
//DECLARATIONS//
////////////////
int size_Of_String;
char a;
char b;
//When flip = true a fails, when flip = false b fails;
bool flip;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
a = input[0];
b = input[1];
//When flip = true a fails, when flip = false b fails;
flip = false;
//////////////////////////////
//RULE CHECKING BEFORE LOGIC//
//////////////////////////////
//Last minute condition check
if(input.size() < 4){return false;}
if(input.size() == 4){
if((input[0] == input[2])&&(input[1] == input[3])){ return true;}
else {return false;}
}
//////////////////
//IMPLEMENTATION//
//////////////////
//Go through the string array from both ends.
for(int i=0; i<size_Of_String; i++)
{
if((input[i] != a) && (flip == false))
{
return false;
}
else if((input[i] != b ) && (flip == true))
{
return false;
}
if(flip == true)
{
flip = false;
}
else if (flip == false) {
flip = true;
}
}
return true;
}
Data findUniqueChar(std::string input)
{
////////////////
//DECLARATIONS//
////////////////
int size_Of_String;
int run_Through;
std::string temp;
std::map<char, char> records;
Data output;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
run_Through = size_Of_String;
temp = "";
//////////////////
//IMPLEMENTATION//
//////////////////
//Find all the unique characters and record them in this map.
for (int i=0; i<run_Through; i++){
if(input[i] != input[0])
{
//Assume this can form a twisted pair with the first element.
if(records.find(input[i]) == records.end()){
records[input[i]] = '0';
temp += input[i];
}
}
}
output.data1 = records;
output.data2 = temp;
return output;
}
std::string quickCheckFix(std::string input)
{
///////////////
//DECLARATION//
///////////////
int size_Of_String;
std::string output;
char tmp;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
output = input;
//////////////////
//IMPLEMENTATION//
//////////////////
//Go through the string array from both ends.
for(int i=0; i<size_Of_String/2; i++)
{
//If duplicates are encountered remove all instances of that character from the string and break out of the loop
if(output[i] == output[i+1])
{
tmp = output[i];
output.erase(std::remove(output.begin(), output.end(), tmp), output.end());
break;
}
else if(output[size_Of_String - 1 - i] == output[size_Of_String - 2 - i])
{
tmp = output[size_Of_String - 1 - i];
output.erase(std::remove(output.begin(), output.end(), tmp), output.end());
break;
}
}
//Call yourself again if output has been changed. set output to equal the value of the call. Use the altered output as the argument,
if(output != input){
output = quickCheckFix(output);
}
return output;
}
std::string condition(std::string input)
{ ////////////////
//DECLARATIONS//
////////////////
int size_Of_String;
std::string output;
std::string pair_Values;
std::string saved_Failures;
//False = alpha fail, true = omega fails
Data records;
///////////////////////
// INITIALIZATION //
///////////////////////
size_Of_String = input.size();
output = input;
pair_Values += input[0];
pair_Values += input[1];
saved_Failures = "";
// bool keys were replaced with chars key for more options. 0 = false, 1 = true, X = failure!
records = findUniqueChar(input);
//////////////////
//IMPLEMENTATION//
//////////////////
for(int i=0; i<size_Of_String; i++)
{
//----------------------------------//
//--------Ender conditions----------//
//----------------------------------//
//If there are no more unique characaters that could succeed it is finally safe to remove the 1st element from the string.
if(saved_Failures.size() == records.data2.size()){
//Free yourself from the loop first
break;
}
//---------------------------------------//
//--------Logic and computation----------//
//---------------------------------------//
//If the first elements was encountered again
if(input[i] == input[0])
{
//Record all true key as failures
for(int a=0; a<records.data1.size(); a++)
{
if(records.data1.find(records.data2[a])->second == '1'){
saved_Failures += records.data2[a];
records.data1[records.data2[a]] = 'X';
}
}
//Change all the false keys to true
for(int a=0; a<records.data1.size(); a++)
{
if(records.data1.find(records.data2[a])->second == '0'){
records.data1[records.data2[a]] = '1';
pair_Values[1] = input[i];
}
}
}
else if(records.data1.find(input[i])->second == '1'){ //If the key was found again while being true flip the value to false.
records.data1[input[i]] = '0';
pair_Values[1] = input[i];
}
else if(records.data1.find(input[i])->second == '0'){ //If the key was found again while being false record it as failure.
saved_Failures += input[i];
records.data1[input[i]] = 'X'; // Will never get in the loop again
}
}
//If if failed go ahead and remove the first element instances and call your friend again.
if(saved_Failures.size() == records.data2.size()){
output.erase(std::remove(output.begin(), output.end(), input[0]), output.end());
}
//If you think it succeeded remove all other characters.
else{
//Remove the 1st element character from this string
saved_Failures.erase(std::remove(saved_Failures.begin(), saved_Failures.end(), input[0]), saved_Failures.end());
//Start from the top and work your way to the bottom.
for(int i=0; i<saved_Failures.size(); i++){
output.erase(std::remove(output.begin(), output.end(), saved_Failures[i]), output.end());
}
}
return output;
}
std::string findPair(std::string input)
{
///////////////
//DECLARATION//
///////////////
std::string output;
std::string pair_Values;
////////////////////////////////////////////////
//RULE CHECKING BEFORE LOGIC & INITIALIZATION //
////////////////////////////////////////////////
//Check if the string size is invalid
if(input.size() < 4){return "";}
//If the string is valid see if you can cut it down to size before processing. Apply rule 1 again in case you got lucky
input = quickCheckFix(input);
if(input.size() < 4){return "";}
//Super lucky condition just to save more time.
if(input.size() == 4){
if((input[0] == input[2])&&(input[1] == input[3])){ return input;}
else {return "";}
}
///////////////////////
// INITIALIZATION //
///////////////////////
//Only munipulate the output string, and begin the set up for the logic loop
output = input;
pair_Values += output[0];
pair_Values += output[1];
//////////////
// LOGIC //
//////////////
output = condition(output);
//If the function return false, it is on
switch(finalVerification(output)){
case true: break;
case false: output = findPair(output);
}
return output;
}
void autoStringRead()
{
///////////////
//DECLARATION//
///////////////
std::ifstream inputs( "pairs-in.txt" );
std::string line;
std::string done;
std::ofstream results;
///////////////////////
// INITIALIZATION //
///////////////////////
//Generate the file
results.open ("results.txt");
//Make sure this exists
if( inputs == NULL ) { return; }
while (getline(inputs, line)) {
done = findPair(line);
results << done <<std::endl;
std::cout<< line << std::endl;
std::cout<< done << std::endl;
}
inputs.close();
results.close();
}
int main()
{
autoStringRead();
system("pause");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T14:50:42.023",
"Id": "399308",
"Score": "1",
"body": "Wasn't this just posted for review here: https://codereview.stackexchange.com/questions/206983/mixed-duo-string-generator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Cr... | [
{
"body": "<h3>Algorithm</h3>\n\n<p>Your code does strike me as unnecessarily difficult to follow for the task it accomplishes.</p>\n\n<p>Given that the final result needs to consist of alternating characters, I think I'd start by eliminating any characters that include any run of two or more:</p>\n\n<pre><code... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T14:49:11.117",
"Id": "206987",
"Score": "1",
"Tags": [
"c++",
"performance",
"object-oriented",
"strings",
"complexity"
],
"Title": "Mixed Duo String Generator 2"
} | 206987 |
<p>I have written an implementation of <code>malloc()</code> and <code>free()</code> for Linux using the <code>sbrk()</code> system call.</p>
<p>When memory is requested, it checks if there is a large enough chunk available already, if there is then that gets returned to the user, otherwise a new block of memory will be requested from the kernel. When memory is free'd the block is marked as such and kept for later, and adjacent free blocks of memory are merged together. If there is a free block at the end of the heap that is larger than the size of a page then the largest possible multiple of page size bytes is returned to the kernel.</p>
<p>This is the first version of this code and my first time working with system calls, as such I have kept things fairly simple and not included padding or a <code>realloc()</code> implementation. Both of these will feature in the next version along with any improvements suggested here.</p>
<p><strong>malloc.h</strong></p>
<pre><code>#ifndef _MALLOC_H
#define _MALLOC_H
#include <stdbool.h>
#define PAGE_SIZE 4096
typedef struct mem_header mem_header;
struct mem_header {
size_t size;
bool free;
mem_header * prev;
mem_header * next;
};
void * _malloc(size_t size);
void _free(void * ptr);
#endif
</code></pre>
<p><strong>malloc.c</strong></p>
<pre><code>#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include "malloc.h"
static inline void eat_next_block(mem_header * header_ptr);
mem_header * head_ptr = NULL;
mem_header * tail_ptr = NULL;
void * _malloc(size_t size)
{
if(!size)
return NULL;
bool heap_empty = false;
size_t additional_space = 0;
if(!head_ptr) {
/* Try and get the base pointer for the heap, as it is defined sbrk(0) could suprisingly fail */
if((head_ptr = tail_ptr = sbrk(0)) == (void *) -1)
return NULL;
heap_empty = true;
} else {
/* Try and find enough free space to give the user */
for(mem_header * heap_ptr = head_ptr; heap_ptr; heap_ptr = heap_ptr->next) {
if(heap_ptr->free && heap_ptr->size >= size + sizeof(mem_header)) {
/* Set up free block, if there is space for one */
if(heap_ptr->size > size + 2 * sizeof(mem_header)) {
mem_header * next_block = (mem_header *)((char *) heap_ptr + size + sizeof(mem_header));
next_block->size = heap_ptr->size - size - sizeof(mem_header);
next_block->free = true;
next_block->prev = heap_ptr;
next_block->next = heap_ptr->next;
heap_ptr->next = next_block;
} else {
size = heap_ptr->size;
}
/* Configure newly allocated block */
heap_ptr->size = size;
heap_ptr->free = false;
if((tail_ptr == heap_ptr) && heap_ptr->next)
tail_ptr = heap_ptr->next;
/* Cast heap_ptr as char * since we're doing byte level arithmetic, then convert to void * before returning */
return (void *)((char *) heap_ptr + sizeof(mem_header));
}
}
/* If we have a free block at the end that isn't large enough we can subtract its size from our allocation requirement */
if(tail_ptr->free)
additional_space = tail_ptr->size + sizeof(mem_header);
}
/* Determine how much we need to grow the heap by, alligned to a multiple of PAGE_SIZE bytes */
size_t block_size = size + sizeof(mem_header) - additional_space;
if(block_size % PAGE_SIZE != 0)
block_size += PAGE_SIZE - (block_size % PAGE_SIZE);
/* Grow the heap */
if(sbrk(block_size) == (void *) -1)
return NULL;
/* Configure the memory block to be returned */
if(heap_empty) {
tail_ptr->prev = NULL;
} else if(!tail_ptr->free) {
mem_header * tail_ptr_temp = tail_ptr;
tail_ptr->next = (mem_header *)((char *) tail_ptr + tail_ptr->size + sizeof(mem_header));
tail_ptr = tail_ptr->next;
tail_ptr->prev = tail_ptr_temp;
}
tail_ptr->next = NULL;
tail_ptr->free = false;
tail_ptr->size = size;
/* Configure any free space at the top of the heap */
void * return_ptr = (void *)((char *) tail_ptr + sizeof(mem_header));
size_t leftover = block_size + additional_space - (size + sizeof(mem_header));
if(leftover > sizeof(mem_header)) {
mem_header * tail_ptr_temp = tail_ptr;
tail_ptr->next = (mem_header *)((char *) tail_ptr + size + sizeof(mem_header));
tail_ptr = tail_ptr->next;
tail_ptr->free = true;
tail_ptr->prev = tail_ptr_temp;
tail_ptr->next = NULL;
tail_ptr->size = leftover - sizeof(mem_header);
} else {
tail_ptr->size += leftover;
}
return return_ptr;
}
void _free(void * ptr)
{
if(!ptr)
return;
mem_header * header_ptr = (mem_header *) ptr;
header_ptr--;
if(header_ptr->free)
return;
header_ptr->free = true;
/* If there is a free block in front then consume it */
if(header_ptr->next && header_ptr->next->free)
eat_next_block(header_ptr);
/* If there is a free block directly behind then jump to it and consume the block infront */
if(header_ptr->prev && header_ptr->prev->free) {
header_ptr = header_ptr->prev;
eat_next_block(header_ptr);
}
/* If there is a sufficient amount of memory at the end of the heap, return it to the kernel */
if(!header_ptr->next && header_ptr->size + sizeof(mem_header) >= PAGE_SIZE) {
size_t leftover = (header_ptr->size + sizeof(mem_header)) % PAGE_SIZE;
size_t excess = header_ptr->size + sizeof(mem_header) - leftover;
if(!header_ptr->prev) {
head_ptr = tail_ptr = NULL;
} else {
header_ptr->prev->size += leftover;
header_ptr->prev->next = NULL;
}
sbrk(-excess);
}
return;
}
static inline void eat_next_block(mem_header * header_ptr)
{
header_ptr->size += header_ptr->next->size + sizeof(mem_header);
header_ptr->next = header_ptr->next->next;
if(header_ptr->next)
header_ptr->next->prev = header_ptr;
return;
}
</code></pre>
<p><strong>malloc_test.c</strong></p>
<pre><code>#include <unistd.h>
#include <stdio.h>
#include "malloc.h"
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(*(x)))
int main()
{
char * mem_block[4];
char * initial_break = sbrk(0);
size_t alloc_size[4] = { 8192, 16384, 405, 32768 };
for(size_t i = 0; i < ARRAY_SIZE(mem_block); i++) {
if(!(mem_block[i] = _malloc(alloc_size[i] * sizeof(char)))) {
fprintf(stderr, "Error: Could not allocate memory!\n");
return -1;
}
}
char * final_malloc_break = sbrk(0);
for(size_t i = 0; i < ARRAY_SIZE(mem_block); i++)
for(size_t j = 0; j < alloc_size[i]; j++)
mem_block[i][j] = 'a';
_free(mem_block[1]);
_free(mem_block[0]);
_free(mem_block[3]);
_free(mem_block[2]);
char * final_free_break = sbrk(0);
size_t total_allocated = (size_t) final_malloc_break - (size_t) initial_break;
size_t excess_pages = ((size_t) final_free_break - (size_t) initial_break) / PAGE_SIZE;
printf("\n\tHeap Break Positions\n\nInitial break:\t\t%p\nFinal allocation break:\t%p\nFinal free break:\t%p\n\n", initial_break, final_malloc_break, final_free_break);
if(excess_pages)
printf("Error: %zu pages were not free'd\n", excess_pages);
else
printf("All allocated pages free'd\n");
printf("Allocated %zu bytes (%zu pages)\n", total_allocated, total_allocated / PAGE_SIZE);
return 0;
}
</code></pre>
<p>All code was compiled with gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) and tested on Debian GNU/Linux 9.5 (stretch) with the command <code>gcc malloc.c malloc_test.c -o malloc -Wall -Wextra -Wpedantic</code></p>
<p>Note: This code was designed to fulfill a specification for one of my classes, which included a page size of 4096 bytes and function names starting with underscores. I was unaware about the portability concerns arising from these and even though it wasn't a tag, portability is something I definitely want to know about</p>
| [] | [
{
"body": "<p>Names beginning with <code>_</code> are reserved for the implementation; I'm surprised that <code>-Wpedantic</code> doesn't help with this!</p>\n\n<p>Include what you use - it helps if your implementation and test program include <code>malloc.h</code> before any standard headers. In this case, it... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T15:18:37.213",
"Id": "206988",
"Score": "12",
"Tags": [
"performance",
"c",
"memory-management",
"linux",
"portability"
],
"Title": "malloc() and free() for Linux with system calls"
} | 206988 |
<p>I have the following assignment that I succeeded in solving, but the code is very inefficient. I would appreciate if someone could show me a more efficient way, perhaps with substring. Note that I am not allowed to use imports or regexes or add more functions.</p>
<pre><code>/**
* Separates a given string into tokens, which are the "words" that are
* separated by one or more occurrences of the given separator character.
* Returns the tokens as an array of String values.
*/
public static String[] tokenize (String str, char separator) {
// Removes all the occurrences of the separator at the beginning and end of str
String source = trim(str, separator);
String[] tokens = new String[charRunCount (source,separator)+1];
String tmp = ""; // a string in order to take a word, then run over this string
int j = 0;
int i = 0;
while (i < tokens.length) {
if ( source.charAt (j) != separator ) {
do {
tmp += source.charAt (j);
if ( j >= source.length () - 1 ) {
break;
}
else { // so that we math the source length
j++;
}
} while (source.charAt (j) != separator);
}
if ( source.charAt (j) == separator ) {
j++;
while (source.charAt (j) == separator) {
j++;
}
}
tokens[i] = tmp;// taking the token into place
tmp = ""; //resetting the token so we can begin anew
i++;
}
return tokens;
}
</code></pre>
<p>the <code>charRunCount()</code> function:</p>
<pre><code>public static int charRunCount(String str, char c){
char last = 0;
int counter = 0;
for (int i = 0; i < str.length(); i++) {
// whenever a run starts.
if (last != c && str.charAt(i) == c) {
counter++;
}
last = str.charAt(i);
}
return counter;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T16:49:35.250",
"Id": "399329",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your ... | [
{
"body": "<p><code>tmp</code> is never a good name for a variable. In this case, you should call it <code>token</code> instead, or perhaps <code>word</code>. And you rightly complain that building strings using repeated <code>+=</code> operations is inefficient, and correctly suggest that <code>.substring()<... | {
"AcceptedAnswerId": "207039",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T16:32:21.563",
"Id": "206997",
"Score": "2",
"Tags": [
"java",
"performance",
"strings",
"parsing",
"reinventing-the-wheel"
],
"Title": "Split a string into a list of tokens"
} | 206997 |
<p>I'm workin on this code that will be a licensing class integrated with an electron app. For now it's a simple object who will generate and check for a licence stored inside the electron app folder. I want to improve it before implementing it inside my projects. Using this class it's simple: It will check for a valid licence file inside a predefined folder, if the file not exist, the class will generate one for using a trial version of the app. It's not perfect, but for now it work as expected. Any suggestion will be appreciated. </p>
<pre><code><?php
if(!defined('ABSPATH')){
define('ABSPATH', __DIR__);
}
class Activator{
private $uuid;
private $licence_code;
private $machine_uuid;
private $current_date;
private $start_date;
private $end_date;
private $timezone;
public static function generateLicence($uuid){
if(!file_exists(ABSPATH.'/DataStorage/.licence')){
$timezone = new DateTimeZone('Europe/Rome');
$start_date = new DateTime("now", $timezone);
$end_date = new DateTime("+30 days", $timezone);
$machine_uuid = $uuid;
$licence_code = hash('sha384', $machine_uuid);
$licence_file = array(
'uuid' => $machine_uuid,
'activation_date' => $start_date->format('d-M-Y'),
'expire_date' => $end_date->format('d-M-Y'),
'trial_version' => true,
'licence_code' => $licence_code
);
$w = file_put_contents(ABSPATH.'/DataStorage/.licence' ,json_encode($licence_file));
echo $w;
}
}
public function checkLicence($uuid){
if(!file_exists(ABSPATH.'/DataStorage/.licence')){
return;
}
else{
$current_date = new DateTime('now');
$licence_file = json_decode(file_get_contents(ABSPATH.'/DataStorage/.licence'), true);
$licence_code = $licence_file['licence_code'];
$licence_check = hash_equals($licence_code, hash('sha384', $uuid));
if($licence_check){
if($current_date->format('d-M-Y') != $licence_file['expire_date']){
return 'OK';
}
else{
return 'EXPIRED';
}
}
}
}
}
// usage example with an AJAX call:
if(isset($_POST['uid'])){
$system_id = $_POST['uid'];
echo Activator::checkLicence($system_id);
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T12:47:58.067",
"Id": "400494",
"Score": "1",
"body": "The problem with this is it relies on the current time of the computer and I could simply change the time back to 1970, does the rest of the app depend on the internet or not ? B... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-05T18:04:51.153",
"Id": "207007",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"ajax",
"electron"
],
"Title": "License Manager PHP Class"
} | 207007 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.