body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is my first react app and it was for a job interview challenge. The app is really simple and it works, but although I don't think I'm gonna get it, could I have some feedback about what is wrong and how could I improve it?</p>
<p>***I already submitted this, so is not cheating, I just need to know how can I be better</p>
<ul>
<li>The way requests are being made is correct? </li>
<li>Should planetas object be populated this way? Is there a better approach? (thats how I managed to make it work)</li>
<li>planetas.films was taking too long to be loaded and giving me a map is undefined problem, is my conditional render bad?</li>
<li>And anything else you find to be wrong</li>
</ul>
<p>service:</p>
<pre><code>import axios from 'axios'
const PLANETS_URL = 'https://swapi.co/api/planets'
const FILMS_URL = 'https://swapi.co/api/films'
const GetPlanets = async () => {
let planetas = {}
await axios.get(`${PLANETS_URL}`)
.then((p) => {
planetas = p.data.results
return axios.get(`${FILMS_URL}`)
}).then((f) => {
planetas.forEach((pv, i) => {
pv.films.forEach((pf, j) => {
f.data.results.forEach((el, k) => {
if(pf === el.url){
pv.films[j] = el
}
})
})
})
})
.catch((e) => {
console.error(e);
})
return planetas
}
export default GetPlanets
</code></pre>
<p>component:</p>
<pre><code>import React, { useState, useEffect } from 'react'
import GetPlanets from '../services'
import { Loader, Container, Name, Info, Button } from '../components'
export default function Planetas () {
const [ counter, setCounter ] = useState(1)
const [ planetas, setPlanetas ] = useState([])
const [ toShow, setToShow ] = useState({})
useEffect( () => {
const fetchPlanetas = async () => {
const planetas = await GetPlanets()
setPlanetas(planetas)
setToShow(planetas[0])
};
fetchPlanetas()
}, [])
const handleClick = () => {
if(counter === (planetas.length - 1)){
setCounter(0)
setToShow(planetas[counter])
} else {
setCounter(counter + 1)
setToShow(planetas[counter])
}
}
if(typeof toShow.films !== 'undefined') {
return (
<Container>
<Name>{toShow.name}</Name>
<Info>
<p>Population: {toShow.population}</p>
<p>Climate: {toShow.climate}</p>
<p>Terrain: {toShow.terrain}</p>
Featured in Films:
<ul>
{toShow.films.map((film, key) => (
<li key={key}>{film.title}</li>
))}
</ul>
</Info>
<Button onClick={handleClick}>Next</Button>
</Container>
)
} else {
return(
<Loader>Loading...</Loader>
)
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Requests could be handled better by first fetching planets and then fetching films, instead of waiting for all data to fetched before render. I would prefer to make a service call to get planets and then fetch films asynchronously after that.</li>\n<li>As I mentioned above, I think it's better to get planets and then fetch films asynchronously. </li>\n<li>Since you're looping through all planets and films, I expect it to take long time. In addition, you're waiting for films to be fetched all and then you display planet information. Also, this approach would not be working correct if there was more than one page of films response. </li>\n<li>You can fetch planet and keep a current index value to show current planet information. And you can fetch featured films of that planet after planet info is rendered. To implement a better structured code, you can also use reducers. </li>\n</ul>\n\n<p>I've implemented two versions, first version is without reducers and second one is with reducers. You can take a look at to get some idea and compare both solutions.</p>\n\n<p>Without reducer: <a href=\"https://codesandbox.io/embed/swapiplanetsfilms-simple-wdtoh\" rel=\"nofollow noreferrer\">https://codesandbox.io/embed/swapiplanetsfilms-simple-wdtoh</a></p>\n\n<p>With reducer: <a href=\"https://codesandbox.io/embed/swapiplanetsfilms-reducer-yg44l\" rel=\"nofollow noreferrer\">https://codesandbox.io/embed/swapiplanetsfilms-reducer-yg44l</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T17:29:23.960",
"Id": "436397",
"Score": "0",
"body": "hi, could you explain why \"Also, this approach would not be working correct if there was more than one page of films response\", please. thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T07:28:37.407",
"Id": "437103",
"Score": "1",
"body": "In your code it's only sending one request to Films API and gets all films because there is only 7 results. If there was more results and next attribute of films API response was not null, then you'd have to send another request to fetch those films too. I hope I made it more clear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:36:47.863",
"Id": "224759",
"ParentId": "224509",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224759",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T22:32:54.433",
"Id": "224509",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "Simple react app to fetch and display data"
}
|
224509
|
<p>I'm building a basic data pipeline in .NET to extract data from tables in our RDBMS systems, that exports into columnar storage using Parquet. I'm using Parquet's row group to batch up the writes into manageable segments as switching from rows to columns means holding a chunk of data in memory.</p>
<p>Having to write each column in the batch synchronously (to preserve order) means that it's a fairly slow endeavor to begin with. I'm dealing with datasets with hundreds of millions of rows deep and 100s of columns wide, I need to squeeze every last drop of performance I can muster.</p>
<p>Working example so far:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Parquet;
using Parquet.Data;
using Parquet.Data.Rows;
namespace ParquetDBTest
{
public static class Program
{
private const int BatchSize = 5000;
public static void Main(string[] args)
{
var tables = new[] {"TABLE"};
foreach (var table in tables) Writer(table);
Console.ReadKey();
}
public static async void Writer(string tableName)
{
Console.WriteLine($"Start Time {DateTime.Now}");
var watch = Stopwatch.StartNew();
var rowCount = 0;
var connectionString =
"Data Source=;User ID=;Password=;Provider=OraOLEDB.Oracle.1;Persist Security Info=True;PLSQLRSet=1;";
using (var connection = new OleDbConnection(connectionString))
{
try
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT * FROM {tableName}";
command.CommandType = CommandType.Text;
command.CommandTimeout = 1000;
using (var reader = await command.ExecuteReaderAsync())
{
var columns = Enumerable.Range(0, reader.FieldCount)
.Select(o => new {FieldName = reader.GetName(o), DataType = reader.GetFieldType(o)})
.ToList();
var columnSchema = new List<DataField>(columns.Count);
columnSchema.AddRange(from column in columns
let columnType = column.DataType.IsClass
? column.DataType
: typeof(Nullable<>).MakeGenericType(column.DataType)
let fieldType = typeof(DataField<>).MakeGenericType(columnType)
select (DataField) Activator.CreateInstance(fieldType, column.FieldName));
var schema = new Schema(columnSchema);
var dataset = new Table(schema);
var i = 1;
var outputFile =
new FileInfo($"C:\\Temp\\{tableName}\\{tableName}.snappy.parquet");
outputFile.Directory.Create();
using (var fileStream = outputFile.Create())
{
using (var writer = new ParquetWriter(schema, fileStream)
{CompressionMethod = CompressionMethod.Snappy})
{
while (await reader.ReadAsync())
{
var row = Enumerable.Range(0, reader.FieldCount)
.Select(o => ToParquetType(reader.GetValue(o)))
.ToArray();
dataset.Add(row);
if (i == BatchSize)
{
writer.Write(dataset);
dataset.Clear();
i = 1;
}
i++;
rowCount++;
}
}
}
}
}
}
catch (OleDbException ex)
{
Console.WriteLine(ex.Message);
throw;
}
finally
{
connection.Close();
watch.Stop();
Console.WriteLine($"Finish Time {DateTime.Now}");
Console.WriteLine("--------------");
Console.WriteLine($"Wrote {rowCount} row(s) in {watch.Elapsed.TotalSeconds} seconds!");
}
}
}
private static object ToParquetType(object inputObject)
{
var outputObject = inputObject;
if (inputObject == DBNull.Value) outputObject = null;
if (inputObject is DateTime time) outputObject = new DateTimeOffset(time);
return outputObject;
}
}
}
</code></pre>
<p>Are there any obvious optimizations I can make?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T23:22:41.923",
"Id": "224513",
"Score": "3",
"Tags": [
"c#",
"parquet"
],
"Title": "Optimizing throughput when writing millions of rows with Parquet's row group"
}
|
224513
|
<p>This is a simple implementation of Django's sample project "Poll" using and express.</p>
<p>The controller code:</p>
<pre><code>export default class AuthController {
private db: AuthDb;
constructor(db: AuthDb) {
this.db = db;
}
login = async (user: User) => {
try {
userValidator(user);
const { username, password } = user;
const originalUser = await this.db.getUser(username);
await checkPassword(password, originalUser.password);
const token = createToken(originalUser.id);
return ResourceRetrieved({ token });
} catch (err) {
return errorHandler(err);
}
};
register = async (user: User) => {
try {
userValidator(user);
const userToCreate = await getHashedUser(user);
await this.db.createUser(userToCreate);
return ResourceCreated('User');
} catch (err) {
return errorHandler(err);
}
};
}
</code></pre>
<p>Each method receives the input, and runs validation logic that is outside of the Controller class, each of them can throw a predefined error object that are handled by the errorHandler() function, the Controller class just executes the steps of the action, but it doesn't know what kind of errors can happen.</p>
<p>ErrorHandler method</p>
<pre><code>export default function errorHandler(err: ApiResponse) {
// Checks if err is not an Api Response
if (err.code == null || err.data == null) {
return InternalServerError;
}
return err;
}
</code></pre>
<p>It just checks for unexpected errors, returning a Internal Server Error if the error is not an ApiResponse object.</p>
<p>For example, the checkPassword method:</p>
<pre><code>async function checkPassword(password: string, hash: string) {
const isPasswordRight = await compare(password, hash);
if (!isPasswordRight) {
throw Forbidden('Wrong password');
}
}
</code></pre>
<p>The Forbidden object code</p>
<pre><code>const Forbidden = (msg: string) => ({
code: 403,
data: {
error: {
type: 'forbidden',
msg
}
}
});
</code></pre>
<p>The database is treated the same way</p>
<pre><code>export default class AuthDb {
createUser = async (user: User) => {
try {
const { password, username } = user;
await query(createUserSQL, [username, password]);
return;
} catch (err) {
if ((err.code = '23505')) {
throw Forbidden('Username already in use');
}
throw InternalServerError;
}
};
getUser = async (username: string) => {
const { rows } = await query(getUserSQL, [username]);
if (rows.length === 0) {
throw ResourceNotFound('user');
}
return rows[0] as User;
};
}
</code></pre>
<p>Database errors are handled and re-trowed as a recognized error object rather than
PostgreSQL default error objects so the controller method does not need to know what happens in the database class.</p>
<p>All errors are sent as responses and they all have the same pattern, with a status code and a data object.</p>
<p>The AuthHandler class is just a adapter for express and AuthController</p>
<pre><code>export default class AuthHandler {
private controller: AuthController;
constructor(controller: AuthController) {
this.controller = controller;
}
login = async (req: Request, res: Response) => {
const { body } = req;
const result = await this.controller.login(body);
return handleResult(result, res);
}
register = async (req: Request, res: Response) => {
const { body } = req;
const result = await this.controller.register(body);
return handleResult(result, res);
}
}
</code></pre>
<p>It receives the output of controller's methods and returns a response regardless of being an error or a normal response.</p>
<p>Is is an usual solution for error handling?, i'm in doubt if it is easy to comprehend and maintainable.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T23:43:51.897",
"Id": "224514",
"Score": "2",
"Tags": [
"node.js",
"error-handling",
"typescript",
"express.js"
],
"Title": "Error handling in express without middlewares and using class structure"
}
|
224514
|
<p>A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of
the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call
it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:</p>
<p>012 021 102 120 201 210</p>
<p>What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?</p>
<pre><code>import itertools
def lexicographic(n, digits):
"""Assumes digits a string.
returns the nth item of the lexicographic permutation of digits."""
return list(itertools.permutations(digits))[n - 1]
if __name__ == '__main__':
permutation = list(lexicographic(1000000, '0123456789'))
print(''.join(permutation))
</code></pre>
|
[] |
[
{
"body": "<h3>itertools.islice()</h3>\n\n<p>Looks pretty good, but generating a list of all the permutations can take a lot of memory. Use <code>itertools.islice()</code> to skip over the first 999,999 permutations that you don't want. The indexing parameters to <code>islice</code> are just like for <code>range(start, stop, step)</code></p>\n\n<pre><code>def lexicographic(n, digits):\n \"\"\"Assumes digits a string.\n returns the nth item of the lexicographic permutation of digits.\"\"\"\n\n full_sequence = itertools.permutations(digits)\n starting_at_n = itertools.islice(full_sequence, n-1, n)\n return next(starting_at_n)\n</code></pre>\n\n<p>you may need to adjust the <code>n-1</code> part depending on whether the problem counts from zero or 1.</p>\n\n<p>This still iterates over all the permutations, so it isn't very efficient for large sequences. With some math you can determine the permutation without iterating them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T01:08:45.210",
"Id": "224521",
"ParentId": "224516",
"Score": "1"
}
},
{
"body": "<p>You’re building up a huge list of permutations in order to get to exactly one permutation. This is needlessly using time (computing all permutations that come before it) and memory (storing all those permutations in a list. </p>\n\n<p>If you have 9 objects, you can have 9! = 3,628,800 permutations. So with the 10 digits, 0 through 9, the first 362,880 permutations will be 0#########, the next 362,880 permutations will be 1#########, and you’ll reach the millionth permutation 274,240 permutations in to the 2#########’s. So, 1 digit down, 9 to go. </p>\n\n<p>With 8 objects, you can have 8! = 40,320 permutations. Again, you can determine you’ll cross the 274,240’th permutation during the 7th group of permutations of the 9 objects: 013456789 ... so the your millionth permutation will be of the form 27########. </p>\n\n<p>Repeat for the rest of the digits: a calculator works fine. Or write a program to solve this, and the answer will be returned directly in a fraction of a second. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T07:33:37.437",
"Id": "224537",
"ParentId": "224516",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224537",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T00:12:35.683",
"Id": "224516",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"combinatorics"
],
"Title": "Project Euler # 24 Lexicographic permutations in Python"
}
|
224516
|
<blockquote>
<p>The Fibonacci sequence is defined by the recurrence relation:</p>
<p>F<sub>n</sub> = F<sub>n−1</sub> + F<sub>n−2</sub>, where F<sub>1</sub>
= 1 and F<sub>2</sub> = 1.</p>
<p>Hence the first 12 terms will be:</p>
<p>F<sub>1</sub> = 1<br>
F<sub>2</sub> = 1<br>
F<sub>3</sub> = 2<br>
F<sub>4</sub> = 3<br>
F<sub>5</sub> = 5<br>
F<sub>6</sub> = 8<br>
F<sub>7</sub> = 13<br>
F<sub>8</sub> = 21<br>
F<sub>9</sub> = 34<br>
F<sub>10</sub> = 55<br>
F<sub>11</sub> = 89<br>
F<sub>12</sub> = 144</p>
<p>The 12th term, F<sub>12</sub>, is the first term to contain three digits.</p>
<p>What is the index of the first term in the Fibonacci sequence to
contain 1000 digits?</p>
</blockquote>
<pre><code>from time import time
def fib(n):
"""returns index of the first fibonacci of length n digits."""
fibs = [0, 1]
while len(str(fibs[-1])) < n:
fibs.append(fibs[-1] + fibs[-2])
return len(fibs) - 1
if __name__ == '__main__':
time1 = time()
print(fib(1000))
print(f'Time: {time() - time1} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:27:12.757",
"Id": "435576",
"Score": "4",
"body": "If you examine the [Wikipedia article on Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number), in particular the section \"Computation by Rounding, it should be possible to calculate the the first F_n > 10^1000 by taking base 10 logs of both sides."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T13:18:10.430",
"Id": "435693",
"Score": "0",
"body": "@JamesKPolk [Exactly](https://codereview.stackexchange.com/a/224562/139491)."
}
] |
[
{
"body": "<p>This isn't a full review but something I found very interesting about this problem: I would have thought that keeping a list of every Fibonacci number would get expensive over larger numbers but that doesn't seem to be the case with my testing.</p>\n\n<p>Instead it seems the bottleneck is the line:</p>\n\n<pre><code>len(str(fibs[-1])) < n:\n</code></pre>\n\n<p>I ran the function for n = 10,000 and it took roughly 32 seconds to run. If you instead do a comparison to a constant value such as:</p>\n\n<pre><code>threshold = 10 ** (n-1)\nwhile fibs[-1] <= threshold:\n</code></pre>\n\n<p>The time drops to about a 10th of a second. If you change your list to only track the last three numbers that times is roughly halved again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:26:15.220",
"Id": "435815",
"Score": "1",
"body": "You should consider moving the actual computation out to a constant ... `threshold = 10 ** (n - 1)` ... then later you have `fibs[-1] <= threshold` .... so you only have to do that computation once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:59:08.643",
"Id": "435893",
"Score": "1",
"body": "Instead of just tacking on text at the end, fix your initial answer to show the good way first. Some Python implementations would CSE that loop-invariant `10 ** (n-1)`, but unlike C/C++ you apparently have to do that optimization manually. Anyway yes, converting a huge integer from binary to a base-10 string is very slow, requiring repeated division by 10 or equivalent."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T01:26:19.810",
"Id": "224522",
"ParentId": "224518",
"Score": "13"
}
},
{
"body": "<p>Two comments:</p>\n\n<ol>\n<li><p>There isn't any reason to keep a list of all the fib numbers. You only need the last two numbers to compute the next one.</p></li>\n<li><p>A number with 1000 digits satisfies 1e1000 <= f < 1e1001. It might be faster to compare f to the numbers rather than to convert it to a string and get its length.</p></li>\n</ol>\n\n\n\n<pre><code>def fib_of_length(n):\n \"\"\"returns index of the first fibonacci of length n digits.\n for n > 0.\n \"\"\"\n\n bound = 10**(n-1)\n fib, previous_fib = 1,0\n index = 1\n while fib < bound:\n fib, previous_fib = fib + previous_fib, fib\n index += 1\n\n return index\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:11:46.410",
"Id": "435658",
"Score": "0",
"body": "It's reasonably fast, taking into account that you iterate over every Fibonacci number."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T01:32:23.153",
"Id": "224523",
"ParentId": "224518",
"Score": "17"
}
},
{
"body": "<p>Project Euler has quite a few problems on the Fibonacci numbers. Other things also repeatedly crop up, like prime numbers, triangular numbers, and so on. In fact, quite a few problems build on earlier, easier, problems.</p>\n\n<p>Because of this it is worth it to start designing your functions for reusability. Put these functions into modules, so you can reuse them later. This one should probably go to the <code>sequences.py</code> module or just a general <code>utils.py</code>.</p>\n\n<p>Currently you have one function that does everything. Instead you will probably want a generator function that generates all Fibonacci numbers, which you can then use afterwards:</p>\n\n<pre><code>def fibonacci():\n \"\"\"Yield the numbers from the Fibonacci sequence\"\"\"\n a, b = 1, 1\n while True:\n yield a\n a, b = b, a + b\n</code></pre>\n\n<p>The actual problem can then be solved in many ways, either like you did or by writing another generally applicable function, <code>first</code>:</p>\n\n<pre><code>def first(it, condition=bool):\n \"\"\"Return the first truthy (default) or first value satisfying `condition` from `it`.\"\"\"\n it = iter(it)\n return next(filter(condition, it))\n</code></pre>\n\n<p>The <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module is well worth a read, although it is not needed here (I had used it in an earlier version). If you want to spend an entire afternoon, also have a look at the <a href=\"https://pypi.org/project/more-itertools/\" rel=\"nofollow noreferrer\"><code>more_itertools</code></a> module.</p>\n\n<p>The actual solution is then:</p>\n\n<pre><code>if __name__ == \"__main__\":\n condition = lambda n: 10**999 <= n[1] < 10**1000\n print(first(enumerate(fibonacci(), 1), condition)[0])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T12:22:19.933",
"Id": "224557",
"ParentId": "224518",
"Score": "10"
}
},
{
"body": "<p>It's possible to calculate the n<sup>th</sup> Fibonacci number directly thanks to <a href=\"https://en.wikipedia.org/wiki/Fibonacci_number#Binet's_formula\" rel=\"noreferrer\">Binet's formula</a>.</p>\n\n<p>Due to floating point errors, the formula doesn't give correct values if <code>n</code> is too large, but it works fine in order to calculate the number of digits.</p>\n\n<pre><code>from math import log10, floor, ceil\n\ndef fibonacci_digits(n):\n if n < 2:\n return 1\n ϕ = (1 + 5**0.5) / 2\n return floor(n * log10(ϕ) - log10(5) / 2) + 1\n</code></pre>\n\n<p>It's possible to calculate the inverse of this function. This way, you can find the first Fibonacci with <code>k</code> digits directly, without any loop:</p>\n\n<pre><code>def euler25(k):\n if k < 2:\n return 1\n ϕ = (1 + 5**0.5) / 2\n return ceil((k + log10(5) / 2 - 1) / log10(ϕ))\n</code></pre>\n\n<p>It seems to return the correct answer for any <code>k</code> in less than 1 μs :</p>\n\n<pre><code>>>> euler25(1000)\n4782\n>>> euler25(10_000)\n47847\n>>> euler25(100_000)\n478495\n>>> euler25(100_000_000_000_000_000)\n478497196678166592\n</code></pre>\n\n<p>The digits are the same as in:</p>\n\n<pre><code>>>> 1 / log10(ϕ)\n4.784971966781666\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:06:02.757",
"Id": "435650",
"Score": "1",
"body": "Oh god, `φ` as an identifier. Can't wait to start seeing bugs like `φ = 1; assert ϕ == 1`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T07:28:34.490",
"Id": "435655",
"Score": "0",
"body": "@Peilonrayz: I agree it can be dangerous. I used two different symbols at first, without noticing it. :-/ Your example isn't a bug, it's a [feature](https://stackoverflow.com/a/34097194/6419007)!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T07:33:04.477",
"Id": "435656",
"Score": "2",
"body": "You say feature, I say death trap. ;) Yeah I know about NFKC normalization, that's [how I made my example legit](https://gist.github.com/Peilonrayz/215a596b40309f49a9740896b886725b) ;P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:16:53.847",
"Id": "435659",
"Score": "0",
"body": "@Peilonrayz: Nice little script, thanks! And wow, that's an impressive/scary amount of collisions!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:26:21.723",
"Id": "435660",
"Score": "2",
"body": "@Peilonrayz: `i` leads the pack with 21 collisions: `\"iᵢⁱℹⅈⅰⓘi\"`. Next time I want to troll a colleague, I'll be sure to use every single synonym for `i` in a script. :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:37:02.313",
"Id": "435661",
"Score": "2",
"body": "You've gained my eternal ire and awe. :O Also, de ⓗ ⓝ |³ ˢⅇ. - Yeah there's an impressive amount of collisions, which should make Unicode easier to support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:59:03.397",
"Id": "435662",
"Score": "0",
"body": "@Peilonrayz: Sadly, not every collision is an identifier, e.g. `ⓘ`. You're right, it's possible to create words out of collisions for even more fun! `ᵉᵒʸ = \"test\"; print(ℙₑᵃ)`"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:25:11.937",
"Id": "224562",
"ParentId": "224518",
"Score": "18"
}
},
{
"body": "<p>As others have pointed out, if you are brute-forcing this:</p>\n\n<ul>\n<li>there's no reason to keep the old values around in a list. You just need <code>a += b; b += a;</code> to go 2 steps, or in Python <code>a,b = b,a+b</code> to go one step.</li>\n<li>binary integer -> base-10 digit string is very expensive, requiring repeated division by 10 or equivalent. (And that's division of the whole BigInteger by 10; it can't be done in chunks because the lowest decimal digit depends on all higher binary digits.) So compare against a threshold instead.</li>\n</ul>\n\n<p>There's another trick nobody's mentioned:</p>\n\n<p><strong>Fib(n) grows fast enough that you can discard some of the the lowest digits occasionally</strong> without affecting the most-significant digits of your running total. Fib(n) grows close to exponentially; faster than any polynomial function.</p>\n\n<p>For example, an Extreme Fibonacci code-golf question was to print the first 1000 digits of <code>Fib(1 billion)</code> with a program that could actually finish in a reasonable amount of time. One <a href=\"https://codegolf.stackexchange.com/questions/133618/extreme-fibonacci/133678#133678\">Python2 answer from @AndersKaseorg</a> used this code:</p>\n\n<pre><code>## golfed for minimum source-code size in bytes, not readability or performance\na,b=0,1\ni=1e9\nwhile i:\n a,b=b,a+b;i-=1\n if a>>3360:a/=10;b/=10\nprint a\n# prints first 1000 digits of Fib(1**9),\n# plus some (possibly wrong) extra trailing digits, as allowed by that question\n</code></pre>\n\n<p>which discards the low decimal digit of <code>a</code> and <code>b</code> if <code>a > 2 ** 3360</code>. That's a 1012 digit number, so this keeps at least 1012 significant digits. (And slightly more in <code>b</code> which is the larger of the 2).</p>\n\n<p>For your case, you only care about the magnitude, so basically 1 significant digit of precision. You probably only have to keep about 12 or 13 significant digits to make sure the leading significant digit is always correct and doesn't grow too soon or too late. Maybe fewer; you might get away with keeping your running totals small enough to fit into 32-bit integers. Although I think Python on 64-bit machines will use 64-bit integers.</p>\n\n<p>For your case, you do care about how many total digits there are. So you need to count how many times you truncate.</p>\n\n<p>For efficiency, you probably want to set a higher truncation threshold and divide by 100 or 1000 so you don't have to do as many divisions. You might also be able to bit-shift (divide by a power of 2) instead of dividing by 10, if handle your final threshold appropriately, but that's trickier.</p>\n\n<p>(That Python version takes about 12.5 minutes on a 4.4GHz Skylake x86-64 with Arch Linux CPython 2.7. My hand-written asm answer on the same question takes about 70 seconds by using base-10^9 extended precision, making it efficient to discard groups of 9 decimal digits.)</p>\n\n<p>You can also unroll the loop so you only check for truncation every few additions because compare isn't free either. Perhaps have an efficient main loop that stops one or two orders of magnitude below the target digit-count, then go one step at a time without further truncation.</p>\n\n<p>Working out the implementation details is left as an exercise for the reader (because the most efficient solution for large n is the closed-form FP math version). <strong>Keeping the numbers small should make the run time scale linearly with <code>n</code></strong>, instead of having each addition take longer as the numbers get larger.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T20:41:46.740",
"Id": "224701",
"ParentId": "224518",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224562",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T00:32:05.767",
"Id": "224518",
"Score": "15",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"fibonacci-sequence"
],
"Title": "Project Euler # 25 The 1000 digit Fibonacci index"
}
|
224518
|
<p>I'm a beginner in Python and I made a password checker. I'm following these rules:</p>
<ul>
<li>I have to use regex</li>
<li>password must be at least 8 characters</li>
<li>must have at least one lower case character</li>
<li>must have at least one upper case character</li>
<li>must have at least one special character</li>
<li>must have at least one number</li>
</ul>
<p>I also wanted to display a message letting the user know what conditions weren't met.</p>
<p>I'm a bit concerned by the succession of <code>if</code>s.</p>
<pre><code>#strong password checks
import re
#ask the user for the password to check
pwtocheck = input('please enter the password to be checked:')
#Error message to be
Err_mess = ''
#first regex : at least one lower case characters
pw_lc = re.compile(r'([a-z]+)')
#second regex : at least one upper case characters
pw_uc = re.compile(r'([A-Z]+)')
#third regex: at least one special character
pw_sc = re.compile(r'([\-_\?!@#$%^&\*]+)')
#fourth regex : password must have at least one number
pw_d = re.compile(r'([0-9])+')
#create a list to be given to all() to evaluate if all conditions are met or not
cond_pw = [len(pwtocheck) > 8, pw_lc.search(pwtocheck), pw_uc.search(pwtocheck), pw_sc.search(pwtocheck), pw_d.search(pwtocheck)]
#building an error message
#is the password at least 8 characters
if len(pwtocheck) < 8:
Err_mess = Err_mess + 'password is too short\n'
#first regex is none
if pw_lc.search(pwtocheck) is None:
Err_mess = Err_mess + 'password needs at least one lower case character\n'
#second regex is None
if pw_uc.search(pwtocheck) is None:
Err_mess = Err_mess + 'password needs at least one upper case character\n'
#third regex is None
if pw_sc.search(pwtocheck) is None:
Err_mess = Err_mess + 'password needs at least one special character\n'
#fourth regex is none
if pw_d.search(pwtocheck) is None:
Err_mess = Err_mess + 'password needs at least one number\n'
if all (cond_pw) is True:
print('password is ok')
else:
print(Err_mess)
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <h3>Your code looks great!</h3>\n</blockquote>\n\n<p>I'm guessing that the expression you wish to design, in a final/combined form, would somewhat look like,</p>\n\n<pre><code>^(?=.*[a-z])(?=.*[A-Z])(?=.*[?!@#$%^&*_-])(?=.*[0-9])[A-Za-z0-9?!@#$%^&*_-]{8}$\n</code></pre>\n\n<p>for instance, which of-course can be likely simplified. </p>\n\n<hr>\n\n<p>Here, we are using four positive lookaheads to check for those <code>at least</code> conditions, anywhere in the 8 chars. </p>\n\n<p>We probably don't want to escape some metachars inside the character class <code>[]</code>, usually we would include <code>-</code> at the end, which is used as a <strong>range</strong> inside a char class such as <code>a-z</code>, <code>A-Z</code> and <code>A-z</code>. </p>\n\n<hr>\n\n<p>The expression is explained on the top right panel of <a href=\"https://regex101.com/r/VGvnUa/1/\" rel=\"nofollow noreferrer\">regex101.com</a>, if you wish to explore/simplify/modify it, and in <a href=\"https://regex101.com/r/VGvnUa/1/debugger\" rel=\"nofollow noreferrer\">this link</a>, you can watch how it would match against some sample inputs, if you like. </p>\n\n<h3>Test with <code>re.findall</code></h3>\n\n<pre><code>import re\n\nregex = r\"^(?=.*[a-z])(?=.*[A-Z])(?=.*[?!@#$%^&*_-])(?=.*[0-9])[A-Za-z0-9?!@#$%^&*_-]{8}$\"\n\ntest_str = \"\"\"\naB&9aaaa\naB&9aaaaa\naB&9aaa\naB&9xy8a\n\"\"\"\n\nprint(re.findall(regex, test_str, re.MULTILINE))\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>['aB&9aaaa', 'aB&9xy8a']\n</code></pre>\n\n<h3>Test with <code>re.finditer</code></h3>\n\n<pre><code># coding=utf8\n# the above tag defines encoding for this document and is for Python 2.x compatibility\n\nimport re\n\nregex = r\"^(?=.*[a-z])(?=.*[A-Z])(?=.*[?!@#$%^&*_-])(?=.*[0-9])[A-Za-z0-9?!@#$%^&*_-]{8}$\"\n\ntest_str = \"\"\"\naB&9aaaa\naB&9aaaaa\naB&9aaa\naB&9xy8a\n\"\"\"\n\nmatches = re.finditer(regex, test_str, re.MULTILINE)\n\nfor matchNum, match in enumerate(matches, start=1):\n\n print (\"Match {matchNum} was found at {start}-{end}: {match}\".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))\n\n for groupNum in range(0, len(match.groups())):\n groupNum = groupNum + 1\n\n print (\"Group {groupNum} found at {start}-{end}: {group}\".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))\n\n# Note: for Python 2.7 compatibility, use ur\"\" to prefix the regex and u\"\" to prefix the test string and substitution.\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>Match 1 was found at 1-9: aB&9aaaa\nMatch 2 was found at 28-36: aB&9xy8a\n</code></pre>\n\n<h3>RegEx Circuit</h3>\n\n<p><a href=\"https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZQIxJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZQIxJ.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Reference</h3>\n\n<p><a href=\"https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a\">Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T07:49:38.963",
"Id": "435514",
"Score": "0",
"body": "Using four separate regular expressions keeps the code as readable as possible. Reading your combined regular expression is much more difficult."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T03:23:10.007",
"Id": "224526",
"ParentId": "224525",
"Score": "1"
}
},
{
"body": "<h2>Concept</h2>\n\n<p>Current security research recommends <a href=\"https://www.microsoft.com/en-us/research/publication/password-guidance/\" rel=\"nofollow noreferrer\">eliminating character composition requirements</a>. It's more important to blacklist common weak passwords. Also, <a href=\"https://protonmail.com/blog/protonmail-com-blog-password-vs-passphrase/\" rel=\"nofollow noreferrer\">passphrases</a> are a good alternative to passwords. For the purposes of this code review, though, I'll play along with your original premise.</p>\n\n<h2>Style</h2>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, the official Python style guide, recommends <code>lower_case_with_underscores</code> for variable names. <code>Err_mess</code> violates that guideline for no good reason.</p>\n\n<h2>Regexes</h2>\n\n<p>You don't need the capturing parentheses, if you're not going to do anything with the capture groups. You also don't need the <code>+</code> modifiers, since the requirement is for just one character of each class.</p>\n\n<p>Within a character class (inside square brackets), most characters lose their special meanings. You don't need to escape <code>?</code> and <code>*</code> with backslashes.</p>\n\n<h2>Design</h2>\n\n<p>You're performing each check twice: once to check the password validity, and a second time to gather all of the failure reasons.</p>\n\n<p>This code suffers from the fact that the rules are encoded in multiple places:</p>\n\n<ul>\n<li>the regular expressions (and their variable names)</li>\n<li>the comments</li>\n<li>the <code>if</code> statements (note especially the length check, which breaks the pattern)</li>\n<li>the error message strings </li>\n</ul>\n\n<p>It would be better to treat all of the rules as data, uniformly, and have a single statement that performs all of the checks.</p>\n\n<pre><code>import re\n\npw_to_check = input('please enter the password to be checked:')\n\nrules = [\n ('password is too short', r'.{8}'),\n ('password needs at least one lower case character', r'[a-z]'),\n ('password needs at least one upper case character', r'[A-Z]'),\n ('password needs at least one special character', r'[-_?!@#$%^&*]'),\n ('password needs at least one number', r'[0-9]'),\n]\n\nerr_msg = '\\n'.join(\n req\n for req, regex in rules\n if not re.search(regex, pw_to_check)\n)\n\nprint(err_msg or 'password is ok')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T10:00:02.743",
"Id": "224548",
"ParentId": "224525",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224548",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T02:36:29.603",
"Id": "224525",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"regex",
"validation"
],
"Title": "Checking the strength of a password using regexes"
}
|
224525
|
Apache Parquet is a columnar storage format available to any project in the Hadoop ecosystem, regardless of the choice of data processing framework, data model or programming language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T06:24:38.430",
"Id": "224531",
"Score": "0",
"Tags": null,
"Title": null
}
|
224531
|
<p>I had the following assignment for the Python 101 course I'm taking in my university. </p>
<pre><code>'''
Modify the naive implementation (see below) of a sorting algorithm so that
the list to be sorted is modified *in place*.
Here is the idea:
1. Iterate over all indices i = 0, 1, 2, ... of the input list
2. Find the index j of the smallest element in the rest of the list (from i on)
3. Replace the elements at indices i and j
If we want to sort the list [5, 3, 1, 4, 8, 2, 7, 6], for instance, a run of
the algorithm would be:
i=0, j=2, list=[5, 3, 1, 4, 8, 2, 7, 6]
i=1, j=5, list=[1, 3, 5, 4, 8, 2, 7, 6]
i=2, j=5, list=[1, 2, 5, 4, 8, 3, 7, 6]
i=3, j=3, list=[1, 2, 3, 4, 8, 5, 7, 6]
i=4, j=5, list=[1, 2, 3, 4, 8, 5, 7, 6]
i=5, j=7, list=[1, 2, 3, 4, 5, 8, 7, 6]
i=6, j=6, list=[1, 2, 3, 4, 5, 6, 7, 8]
'''
</code></pre>
<p>In principle, the only two funcions I have to modify are "index_of_smallest_element" and "naive_sort_inplace".</p>
<pre><code>def index_of_smallest_element(some_list):
'''Returns the index of the smallest element in some_list'''
guess=some_list[0]
for element in some_list:
if element < guess:
guess=element
return some_list.index(guess)
def naive_sort(some_list):
sorted_list = []
while len(some_list) > 0:
# remove smallest element from some_list
smallest_element = some_list.pop(index_of_smallest_element(some_list))
# ... and append it to sorted_list
sorted_list.append(smallest_element)
return sorted_list
def naive_sort_inplace(some_list):
def exchange(some_list,x,y):
some_list[x],some_list[y]=some_list[y],some_list[x]
for i in range(0,len(some_list)):
remaining_list=some_list[i:(len(some_list)+1)]
i_rest=index_of_smallest_element(remaining_list)
j=i+i_rest
print('i=',i,'j=',j,'list=',some_list)
exchange(some_list,i,j)
return some_list
if __name__ == '__main__':
my_list = [5, 3, 1, 4, 8, 2, 7, 6]
naive_sort_inplace(my_list)
print('Test: ', my_list == [1, 2, 3, 4, 5, 6, 7, 8])
</code></pre>
<p>Although the code is fully functional, I'm wondering is there would be a better way to do it, especially the "naive_sort_inplace" function.</p>
|
[] |
[
{
"body": "<h2>Problems</h2>\n\n<p>First of all, your current implementation is not truly in-place, since the slice operation creates a new list of that size, which breaches the required max constant extra space usage.</p>\n\n<p>In addition you perform double work in the <code>index_of_smallest_element</code> when you first find the value you want, and then have to run through the entire list again to find the index (the index call has linear time cost)</p>\n\n<h2>Advise</h2>\n\n<p>When working in-place you usually have to work with indexes or pointers, and this is also such a case. Most of the work can be put into 3 categories, index work, swapping work, and control flow, if you are doing work outside of those you should think through an extra time on whether you are off in a problematic direction.</p>\n\n<p>This means that you should manually keep track of relevant indexes, and when calling functions the way to work on a subset is to pass the indexes describing this to it.</p>\n\n<h2>Solution</h2>\n\n<p>there are 2 main changes to be done, both connected to <code>index_of_smallest_element</code>. We first change thats implementation to the following:</p>\n\n<pre><code>def index_of_smallest_element(some_list, start=0):\n smallest = some_list[start]\n for i in range(start+1, len(some_list)):\n value = some_list[I]\n if value < smallest:\n smallest = value\n start = i\n return start\n</code></pre>\n\n<p>With this it becomes easy to write the naive (and really bad) sorting in-place:</p>\n\n<pre><code>def naive_sort_inplace(some_list, out=None):\n def exchange(some_list,x,y):\n some_list[x],some_list[y]=some_list[y],some_list[x] \n\n\n for i in range(0,len(some_list)):\n j = index_of_smallest_element(remaining_list, i)\n if out is not None:\n out('i=',i,'j=',j,'list=',some_list)\n exchange(some_list,i,j)\n return some_list\n</code></pre>\n\n<p>I am not quite sure why you want to do all the printing, but I assume it is for testing or proving correctness. For reuse I have changed it so it by default does not print, but if you pass in <code>print</code> (or some other output function such as <code>open(filename,'w').write</code>) then it write those log updates to that output function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T11:59:04.037",
"Id": "224555",
"ParentId": "224534",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T07:18:09.087",
"Id": "224534",
"Score": "2",
"Tags": [
"python",
"beginner",
"sorting",
"homework"
],
"Title": "Naive implementation of sort inplace"
}
|
224534
|
<p>I'm parsing <a href="https://en.wikipedia.org/wiki/STL_(file_format)" rel="nofollow noreferrer">STL files</a> to load the coordinates. My code is:</p>
<pre><code>void Importer::scanFileSTL_ASCII(
QVector<QVector3D> &vertices, // Coordinates to be filled
const QUrl &url)
{
QFile file;
file.setFileName(url.toLocalFile());
if (!file.open(QIODevice::OpenModeFlag::ReadOnly | QIODevice::OpenModeFlag::Text))
return;
while (!file.atEnd()) {
QByteArray line_BA = file.readLine();
QString line = QString::fromLatin1(line_BA);
// Split line by spaces
QStringList words = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (words.isEmpty())
continue; // Skip this line and jump to next iteration/line
if (words[0] == "vertex") {
assert (words.length() == 4 && "STL file format is wrong: vertex-line must have 4 strings");
float x = words[1].toFloat();
float y = words[2].toFloat();
float z = words[3].toFloat();
vertices.append(QVector3D(x, y, z));
}
}
return;
}
</code></pre>
<p>The code is tested, it works fine. But it is by far slower than the <a href="https://github.com/assimp/assimp/blob/master/code/STL/STLLoader.cpp" rel="nofollow noreferrer">STL loader</a> of asset import library. More accurate comparisons in release mode:</p>
<p>Import of a <code>13MB</code> <em>ASCII</em> STL file: </p>
<ul>
<li>Assimp library: <strong>03.58</strong> seconds</li>
<li>Our code: <strong>04.70</strong> seconds</li>
</ul>
<p>Import of <code>287MB</code> <em>ASCII</em> STL file:</p>
<ul>
<li>Assimp library: <strong>05.72</strong> seconds</li>
<li>Our code: <strong>44.19</strong> seconds</li>
</ul>
<p>I wonder if something is noticeably wrong with my code. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T07:58:08.383",
"Id": "435516",
"Score": "1",
"body": "Can you please guide me how to improve my question, if it is unclear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T22:42:36.723",
"Id": "435639",
"Score": "1",
"body": "As a side notice, if you don't want to use assimp, you still might want to use [vcg](https://github.com/cnr-isti-vclab/vcglib), the self-contained library behind MeshLab."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T14:33:59.737",
"Id": "435697",
"Score": "1",
"body": "Can you share how you test this? Results of a profile are next-to-useless if we can't see how it was retrieved. For general question-improvement advice, see [this FAQ](https://codereview.meta.stackexchange.com/q/2436/52915)."
}
] |
[
{
"body": "<p>Well, it's not much of a mystery. Your code is simple and pretty. <a href=\"https://github.com/assimp/assimp/blob/57c46db04256671878b0b87b18a88645ee448fa1/code/STL/STLLoader.cpp#L326-L344\" rel=\"noreferrer\">Their code</a> is ugly because it performs exactly what it needs to do, and no more:</p>\n\n<blockquote>\n<pre><code>} else if (!strncmp(sz,\"vertex\",6) && ::IsSpaceOrNewLine(*(sz+6))) { // vertex 1.50000 1.50000 0.00000\n if (faceVertexCounter >= 3) {\n ASSIMP_LOG_ERROR(\"STL: a facet with more than 3 vertices has been found\");\n ++sz;\n } else {\n if (sz[6] == '\\0') {\n throw DeadlyImportError(\"STL: unexpected EOF while parsing facet\");\n }\n sz += 7;\n SkipSpaces(&sz);\n positionBuffer.push_back(aiVector3D());\n aiVector3D* vn = &positionBuffer.back();\n sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );\n SkipSpaces(&sz);\n sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );\n SkipSpaces(&sz);\n sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );\n faceVertexCounter++;\n }\n</code></pre>\n</blockquote>\n\n<p>A few differences in the amount of work it does:</p>\n\n<ul>\n<li>There's no regex that needs to be compiled.</li>\n<li>It's not splitting tokens into a list. So, no list needs to be allocated and filled. More importantly, no strings need to be allocated, copied, and destroyed.</li>\n<li>The <code>aiVector3D</code> is allocated first, then each of the three numbers is parsed and written directly into the memory location of the coordinate, with no temporary variable assignments.</li>\n</ul>\n\n<p>I'll also point out that your use of <code>assert</code> is improper. You should only assert conditions that you <em>know must be true</em> due to logic. You should not assert conditions that you <em>hope to be true</em> about the input. If you compile with assertions disabled, then the validation code goes away! That would introduce a bug, and possibly a security vulnerability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T08:45:22.420",
"Id": "224541",
"ParentId": "224535",
"Score": "8"
}
},
{
"body": "<p>Note that we don't have a fully-compilable program, or the example data. But you do! So you can actually measure what's taking up the time using a profiler.</p>\n\n<hr>\n\n<p>However, I would guess that the following lines are the problem:</p>\n\n<pre><code> QString line = QString::fromLatin1(line_BA);\n // Split line by spaces\n QStringList words = line.split(QRegExp(\"\\\\s+\"), QString::SkipEmptyParts);\n</code></pre>\n\n<p>I guess that <code>fromLatin1()</code> effectively copies the <code>QByteArray</code> (i.e. memory allocation, then iterate over everything and copy it).</p>\n\n<p>Then the regex will split every word, which involves something like iterating over the string to match the regex, memory allocation for each separate word, then copying each word.</p>\n\n<p>None of this processing / memory allocation / copying is actually necessary to extract the data required.</p>\n\n<p>Using the C++ standard library instead of Qt things, we could do something like:</p>\n\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <cerrno>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nbool try_parse_float(char const*& start, char const* end, float& value)\n{\n errno = 0;\n auto cend = const_cast<char*>(end);\n float v = std::strtof(start, &cend);\n\n if (end == start)\n return false; // no conversion.\n\n if (errno == ERANGE)\n return false; // float out of range.\n\n // success!\n value = v;\n start = cend;\n\n return true;\n}\n\nbool parse(std::string const& filename)\n{\n std::ifstream file(filename);\n\n if (!file)\n return false;\n\n std::string line;\n while (std::getline(file, line))\n {\n auto i = line.data();\n auto end = line.data() + line.size();\n\n // parse whitespace\n while (i != end && std::isspace(static_cast<unsigned char>(*i)))\n ++i;\n\n // empty line\n if (i == end)\n continue;\n\n // check for \"vertex\" prefix\n char const prefix[] = \"vertex\";\n auto prefix_size = sizeof(prefix) - 1;\n auto starts_with = std::strncmp(i, prefix, std::min<std::size_t>(prefix_size, end - i));\n\n if (starts_with != 0)\n return false; // \"vertex\" is missing or malformed.\n\n i += prefix_size;\n\n // convert floats (discards leading whitespace internally)\n float x;\n if (!try_parse_float(i, end, x))\n return false;\n\n float y;\n if (!try_parse_float(i, end, y))\n return false;\n\n float z;\n if (!try_parse_float(i, end, z))\n return false;\n\n // parse any trailing whitespace\n while (i != end && std::isspace(static_cast<unsigned char>(*i)))\n ++i;\n\n if (i != end)\n return false; // there's something else on this line!\n\n std::cout << \"vertex: \" << x << \" \" << y << \" \" << z << \"\\n\"; // (... or copy vertex to vector)\n }\n\n return true;\n}\n\nint main()\n{\n std::cout << (parse(\"test.stl\") ? \"success\" : \"failure\") << \"\\n\";\n}\n</code></pre>\n\n<p>Which is rather more fiddly, but does no extra copying. The messiness can be hidden neatly into separate functions if necessary.</p>\n\n<hr>\n\n<p>As a side note, you might want to return a bool indicating success / failure from that function. At the moment there would be no obvious difference between failing to read a file, or a valid file that just contains no data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T09:35:35.550",
"Id": "224544",
"ParentId": "224535",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "224541",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T07:20:04.220",
"Id": "224535",
"Score": "4",
"Tags": [
"c++",
"performance",
"parsing",
"coordinate-system",
"qt"
],
"Title": "Parser for STL stereolithography data files"
}
|
224535
|
<p>I am implementing Kalman filtering in R. Part of the problem involves generating a really huge error covariance block-diagonal matrix (dim: 18000 rows x 18000 columns = 324,000,000 entries). We denote this matrix Q. This Q matrix is multiplied by another huge rectangular matrix called the linear operator, denoted by H.</p>
<p>I am able to construct these matrices but it takes a lot of memory and hangs my computer. I am looking at ways to make my code efficient or do the matrix multiplications without actually creating the matrices exclusively.</p>
<pre><code>library(lattice)
library(Matrix)
library(ggplot2)
nrows <- 125
ncols <- 172
p <- ncols*nrows
#--------------------------------------------------------------#
# Compute Qf.OSI, the "constant" model error covariance matrix #
#--------------------------------------------------------------#
Qvariance <- 1
Qrho <- 0.8
Q <- matrix(0, p, p)
for (alpha in 1:p)
{
JJ <- (alpha - 1) %% nrows + 1
II <- ((alpha - JJ)/ncols) + 1
#print(paste(II, JJ))
for (beta in alpha:p)
{
LL <- (beta - 1) %% nrows + 1
KK <- ((beta - LL)/ncols) + 1
d <- sqrt((LL - JJ)^2 + (KK - II)^2)
#print(paste(II, JJ, KK, LL, "d = ", d))
Q[alpha, beta] <- Q[beta, alpha] <- Qvariance*(Qrho^d)
}
}
# dn <- (det(Q))^(1/p)
# print(dn)
# Determinant of Q is 0
# Sum of the eigen values of Q is equal to p
#-------------------------------------------#
# Create a block-diagonal covariance matrix #
#-------------------------------------------#
Qf.OSI <- as.matrix(bdiag(Q,Q))
print(paste("Dimension of the forecast error covariance matrix, Qf.OSI:")); print(dim(Qf.OSI))
</code></pre>
<p>It takes a long time to create the matrix Qf.OSI at the first place. Then I am looking at pre- and post-multiplying Qf.OSI with a linear operator matrix, H, which is of dimension 48 x 18000. The resulting H<em>Qf.OSI</em>Ht is finally a 48x48 matrix. What is an efficient way to generate the Q matrix? The above form for Q matrix is one of many in the literature. In the below image you will see yet another form for Q (called the Balgovind form) which I haven't implemented but I assume is equally time consuming to generate the matrix in R.</p>
<p><a href="https://i.stack.imgur.com/EgsYL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EgsYL.jpg" alt="Balgovind form for Q"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T08:15:20.337",
"Id": "435519",
"Score": "1",
"body": "I'm voting to close this question as off-topic because it belongs on https://cs.stackexchange.com/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T03:31:43.770",
"Id": "435649",
"Score": "0",
"body": "I think this question should go to SO. @dfhwze there is no [r] tag in cs.stackexchange.com I dont think it will be very useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T05:44:14.190",
"Id": "435653",
"Score": "0",
"body": "@GradaGukovic Initially I posted this on SO they sent me over to CodeReview. There someone voted to my question here so I have the same question posted on 3 locations. Not sure where is the right place for this question. Any help with code is highly appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:02:25.227",
"Id": "435657",
"Score": "0",
"body": "Rather than toggling between sites, perhaps it should stay then. Hopefully some expert in this subject can help you out."
}
] |
[
{
"body": "<blockquote>\n<pre><code> JJ <- (alpha - 1) %% nrows + 1\n II <- ((alpha - JJ)/ncols) + 1\n</code></pre>\n</blockquote>\n\n<p>That looks likely to be buggy. I would guess that <code>a</code> is supposed to be an encoding for a pair <code>(row, col)</code>, but in that case the same base should be used for the <code>%%</code> and the <code>/</code>.</p>\n\n<p>I would also suggest that if you can't use 0-indexed matrices then you do the offset to 1-based when you access the matrices, and keep the values you manipulate 0-based. See how much simpler this is:</p>\n\n<pre><code>for (rowa in 0:(nrows-1))\n{\n for (cola in 0:(ncols-1))\n {\n a = rowa * ncols + cola\n for (rowb in 0:(nrows-1))\n {\n for (colb in 0:(ncols-1))\n {\n b = rowb * ncols + colb\n d = sqrt((rowa - rowb)^2 + (cola - colb)^2)\n Q[a+1, b+1] <- Qvariance * (Qrho^d)\n }\n }\n }\n}\n</code></pre>\n\n<p>Incidentally, since <code>Qvariance</code> is multiplied into every single element you could pull that out and post-multiply the final <span class=\"math-container\">\\$48 \\times 48\\$</span> matrix instead.</p>\n\n<hr>\n\n<p>Now, elimination of the matrix. We have <span class=\"math-container\">\\$(AB)_{i,j} = \\sum_k A_{i,k} B_{k,j}\\$</span>, so <span class=\"math-container\">$$(HQH^T)_{i,j} = \\sum_k H_{i,k}(QH^T)_{k,j} = \\sum_k H_{i,k} \\sum_l Q_{k,l} H^T_{l,j} = \\sum_k \\sum_l H_{i,k} H_{j,l} Q_{k,l}$$</span> which allows you to restructure the code so as to avoid creating <span class=\"math-container\">\\$Q\\$</span> in memory. However, it is at the cost of using the naïve algorithm for matrix multiplication, and your matrices are large enough that R is probably using a sub-cubic algorithm. So what you might want to do is to instead break it down into chunks: e.g. of size <code>nrows</code> <span class=\"math-container\">\\$\\times\\$</span> <code>nrows</code>. I don't know enough R to be certain, but I expect that its index range notation allows you to do this quite cleanly.</p>\n\n<p>Following up on some comments, we can expand <span class=\"math-container\">\\$k = r_1 C + c_1\\$</span>, <span class=\"math-container\">\\$l = r_2 C + c_2\\$</span> where <span class=\"math-container\">\\$C\\$</span> is <code>ncols</code>, and get\n<span class=\"math-container\">$$(HQH^T)_{i,j} = \\sum_{r_1} \\sum_{c_1} \\sum_{r_2} \\sum_{c_2} H_{i,r_1 C + c_1} H_{j,r_2 C + c_2} Q_{r_1 C + c_1,r_2 C + c_2} \\\\\n= \\sigma \\sum_{r_1=1}^R \\sum_{r_2=1}^R \\sum_{c_1=1}^C \\sum_{c_2=1}^C H_{i,r_1 C + c_1} H_{j,r_2 C + c_2} \\rho^{\\sqrt{(r_1-r_2)^2 + (c_1-c_2)^2}} $$</span></p>\n\n<p>Let <span class=\"math-container\">\\$Q^{(\\delta)}\\$</span> be a symmetric <span class=\"math-container\">\\$C \\times C\\$</span> matrix with <span class=\"math-container\">\\$Q^{(\\delta)}_{i,j} = \\rho^{\\sqrt{\\delta^2 + (i-j)^2}}\\$</span>. Then <span class=\"math-container\">$$(HQH^T)_{i,j} = \\sigma \\sum_{r_1=1}^R \\sum_{r_2=1}^R \\sum_{c_1=1}^C \\sum_{c_2=1}^C H_{i,r_1 C + c_1} Q^{(|r_1-r_2|)}_{c_1,c_2} H_{j,r_2 C + c_2} \\\\\nHQH^T = \\sigma \\sum_{r_1=1}^R \\sum_{r_2=1}^R H_{1..48,r_1 C .. (r_1+1)C} Q^{(|r_1-r_2|)} H_{1..48,r_2 C..(r_2+1)C}^T $$</span></p>\n\n<p>and the sum can be regrouped by <span class=\"math-container\">\\$|r_1 - r_2|\\$</span> to calculate each <span class=\"math-container\">\\$Q^{(\\delta)}\\$</span> only once. When calculating <span class=\"math-container\">\\$Q^{(\\delta)}\\$</span> you can exploit the symmetry without worrying too much about cache coherence, because the whole of <span class=\"math-container\">\\$Q^{(\\delta)}\\$</span> should fit in L2 cache.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:05:59.777",
"Id": "436005",
"Score": "0",
"body": "Thank you Peter Taylor for your code and insight! The code works great. I just have a quick question. The Q matrix is symmetric so essentially Q[a, b] = Q[b, a]. I wonder if we can save time in not generating the entire matrix rather generate only the lower triangular matrix and copy it to the upper triangular matrix. Would appreciate your comments or code for this? Much appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T06:20:25.800",
"Id": "436071",
"Score": "0",
"body": "@Ashok, the only way to know whether that would be faster is to try it. I suspect that it would be slower, because the inner loop only has about 6 floating point operations, but accessing both triangles of the matrix at the same time wouldn't be good for cache coherence. Also, in case it wasn't clear, the code was to make a point about readability. If you break the calculation into chunks of ncols by ncols then I think each chunk is symmetric and can be used multiple times, but should fit into L2 cache."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T08:51:26.050",
"Id": "224657",
"ParentId": "224536",
"Score": "3"
}
},
{
"body": "<p>Maybe if you have enough RAM this will be faster: (only the <code>Q</code> creation)</p>\n\n<pre><code>alpha <- matrix(rep(1:p, p), p, p)\nJJ <- (alpha - 1L) %% nrows + 1L\nII <- ((alpha - JJ)/ncols) + 1L\nLL <- t(JJ)\nKK <- t(II)\nd <- sqrt((LL - JJ)^2 + (KK - II)^2)\nQ2 <- Qvariance*(Qrho^d)\nall.equal(Q, Q2)\n# TRUE\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-29T21:29:59.403",
"Id": "437061",
"Score": "0",
"body": "Thank you @minem the code works great!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:06:41.900",
"Id": "224901",
"ParentId": "224536",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224657",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T07:31:02.203",
"Id": "224536",
"Score": "3",
"Tags": [
"time-limit-exceeded",
"matrix",
"statistics",
"r",
"memory-optimization"
],
"Title": "Generate a large block diagonal covariance matrix with exponential decay"
}
|
224536
|
<p>I've written what I think is a constant time implementation of a uniqueness check. I've seen many algorithms online, which run in linear time, but was wondering whether my conclusion that this runs in constant time was correct.</p>
<p>I've seen many linear versions of this algorithm, but I haven't seen any that run in O(1).</p>
<p>Any feedback on style, flaws in the code, or how to improve the algorithm would be greatly appreciated.</p>
<pre class="lang-py prettyprint-override"><code>from string import printable
def is_unique(string):
"""Checks whether a string is unique or not.
Big O:
O(S * C) - Constant Time
Where:
`S` is the characters of the string being checked for uniqueness
`C` is a set of all ASCII characters (not including the extended set)
"""
if len(string) == 1:
# A single character is always going to be unique
return True
if len(string) > len(printable):
# If there are more characters than the ASCII character set,
# then we know there are duplicates
return False
found_character = bytearray(len(printable))
for character in string:
for index, ascii_value in enumerate(printable):
if character == ascii_value:
if found_character[index] == True:
return False
# Set the index of the ASCII value in our bytearray to True
found_character[index] = 1
break
return True
is_unique(string='abc')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:21:50.163",
"Id": "435574",
"Score": "3",
"body": "your code is definitely not in \\$O(1)\\$. `for character in string` is a linear operation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:39:39.207",
"Id": "435577",
"Score": "0",
"body": "`string` has a maximum length of 100, since I return `False` if the length of the string exceeds 100. We know it cannot unique, since there are only 100 distinct ASCII characters. The notation, strictly speaking is \\$O(100 * 100)\\$. This isn't strictly true, however, since the worst case for this algorithm is passing in a reversed version of `printable` from the string module. Even then, it will only do 5,500 operations and not the full 10,000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:43:37.167",
"Id": "435578",
"Score": "1",
"body": "just because the problem statement allows you to define an upper limit, that doesn't mean the algorithm's complexity suddenly changes..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T14:06:53.843",
"Id": "435580",
"Score": "0",
"body": "So you're suggesting the runtime is \\$O(M * 100)\\$? Where _M_ has a length between 1 and 100 inclusive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T14:37:56.453",
"Id": "435700",
"Score": "0",
"body": "With a for in a for, it's probably worse. Might be quadratic. Besides, you're looking to eliminate N, not M."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T14:39:03.773",
"Id": "435701",
"Score": "0",
"body": "If you wrote this with the intention of it being constant time, it's not. Not even close. If that's what the spec called for, it's not up to spec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T17:47:08.550",
"Id": "435717",
"Score": "0",
"body": "While I see your point arguing that for a fixed alphabet (printable ASCII]) your result of O(1) holds, I'd characterise *String Uniqueness* by string length *s* and alphabet size *a*."
}
] |
[
{
"body": "<h2>Critique</h2>\n\n<p>You have to describe something for which your input scale, which in this would be the length of your string, so in this regard your implementation is still linear. The part where you try every single possible index for storing a specific character is overkill, since it is often possible to directly calculate it through some kind of hashing. It would therefore be much faster to use a dictionary or the equivalent.</p>\n\n<h2>Alternative</h2>\n\n<p>We can solve this problem very simply for a more general case (any sequence of items is unique) by turning it into a set:</p>\n\n<pre><code>is_unique = lambda xs: len(xs) == len(set(xs))\n</code></pre>\n\n<p>Note that you might want to do some extra work if you want to only have printable characters, such as by applying a filter first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T11:04:58.397",
"Id": "435552",
"Score": "0",
"body": "Thanks for this Ninetails. This was my initial brute force. I'm trying to optimise from this. Casting a string to a set() is a linear operation, as you have to go over the whole string. There are only 100 characters in the ASCII character set, so it's arguably a pointless optimisation, but imagine the input string is `aa`, this would take 2 operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T11:13:17.553",
"Id": "435554",
"Score": "0",
"body": "I did a quick benchmark. Using set() is an order of magnitude faster than using a Boolean array to keep track of seen characters, which surprises me, considering I was trying to improve upon the set() method. \n\n`267 µs` **- Above function** \n\n`2.21 µs` **- Using set()**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T11:42:09.497",
"Id": "435560",
"Score": "0",
"body": "It should be possible to do it faster than a full cast to sets in theory, since you can end early if you find subluxated, the problem is that sets are part of the core of the language, and it is therefore heavily optimized and likely written in a faster language, so even if you use strictly less operations a full cast to a set might still be faster for most cases."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T10:34:28.313",
"Id": "224551",
"ParentId": "224547",
"Score": "2"
}
},
{
"body": "<p>I like the way your function is documented by a doc string and comments.</p>\n\n<p>Why use the inner loop?<br>\nIf you want another \"early out\" compared to \"the set approach\", use a map and \"index\" that with the characters.</p>\n\n<p>You compare <code>found_character[index]</code> to True, but set it to <code>1</code>, which is all the more irritating as it is commented <code>Set […] to True</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T17:55:09.140",
"Id": "224621",
"ParentId": "224547",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "224551",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T09:53:29.523",
"Id": "224547",
"Score": "1",
"Tags": [
"python",
"algorithm"
],
"Title": "Constant Time implementation of String Uniqueness Algorithm"
}
|
224547
|
<p>I would like to write a little pet project using Clojure to study it, something like Stack Overflow client. </p>
<p>Here is a my first code to get list of new questions from site. I am in the very beginning in Clojure so any help will be appreciated.</p>
<p>core.clj:</p>
<pre><code>(ns stackify.core
(:require [clj-http.client :as client]
[clojure.data.json :as json]
[stackify.utils :as utils]
[stackify.configuration :as config]))
; TODO: move key to environment variables
(def ^:const stackKey "put-your-key-here")
(def ^:const baseUrl "https://api.stackexchange.com/2.2/questions?page=%d&pagesize=100&fromdate=%d&order=asc&sort=creation&site=%s&key=%s")
; Fetch questions
(defn fetch-json [url]
"fetch internet page by url and return JSON"
(let [data (client/get url)
body (get data :body)]
(json/read-str body)))
(defn fetch-questions [page from site accum]
"recursive function to get questions"
(let [url (format baseUrl page from site stackKey)
json-content (fetch-json url)
questions (get json-content "items")
has_more (get json-content "has_more")]
(println (format "Fetching page %d (has_more=%b)" page has_more))
(cond
(= has_more true) (fetch-question (+ page 1) from site (concat accum questions))
:else (concat accum questions))
))
(defn get-questions []
(let [from (config/read-time)
now (utils/current-time)]
(println from)
(config/save-time now)
(fetch-questions 1 from "stackoverflow" (vector))))
(defn print-questions [questions]
(doseq [q questions] (println (get q "title"))))
</code></pre>
<p>utils.clj:</p>
<pre><code>(ns stackify.utils
(:require [clj-time.core :as time]
[clj-time.coerce :as tc]))
(defn current-time []
"returns unix time"
(let [moment (tc/to-long (time/now))]
(int (/ moment 1000))))
(defn parse-int [s]
"convert string to int"
(Integer. (re-find #"\d+" s )))
</code></pre>
<p>configuration.clj:</p>
<pre><code>(ns stackify.configuration
(:require [stackify.utils :as utils]))
(def ^:const configFileName "last_sync_time")
(defn save-time [value]
"save value to configuration file; file will be overwritten"
(spit configFileName value))
(defn read-time []
"read last sync time from configuration file"
(let [value (slurp configFileName)]
(utils/parse-int value)))
(defn init []
"initiliza configuration file"
(save-time (utils/current-time)))
</code></pre>
|
[] |
[
{
"body": "<p>This is nice code for someone just learning Clojure. You haven't made any of the common pitfalls like trying to use <code>def</code> to create local variables. I'm going to just jump around and mention things as I see them.</p>\n\n<hr>\n\n<p>Your <code>parse-int</code> function is much slower (and arguably more manual) than it needs to be.</p>\n\n<p>If you run <code>lein check</code> on your project, you'll see the following warning:</p>\n\n<pre><code>call to java.lang.Integer ctor can't be resolved.\n</code></pre>\n\n<p>It's also highlighted in yellow in IntelliJ for the same reason. It can't tell what overload of <code>Integer.</code> to use since it doesn't know with certainty what type <code>re-find</code> returns. This is forcing it to use reflection at runtime to do lookups, which can be <em>very</em> slow. Add a type hint to tell it exactly what <code>re-find</code> returns:</p>\n\n<pre><code>(defn parse-int [s]\n \"convert string to int\"\n (Integer. ^String (re-find #\"\\d+\" s)))\n</code></pre>\n\n<p>Here's some timings using <a href=\"https://github.com/hugoduncan/criterium\" rel=\"nofollow noreferrer\">Criterium</a>, a great benchmarking library. Below, <code>cc</code> is an alias for <code>criterium.core</code>:</p>\n\n<pre><code>; Without type hints\n\n(cc/bench\n (parse-int \"1234567890\"))\n\nEvaluation count : 38179800 in 60 samples of 636330 calls.\n Execution time mean : 1.636166 µs ; <-----------------------\n Execution time std-deviation : 226.156823 ns\n Execution time lower quantile : 1.459082 µs ( 2.5%)\n Execution time upper quantile : 2.309723 µs (97.5%)\n Overhead used : 4.213229 ns\n\nFound 5 outliers in 60 samples (8.3333 %)\n low-severe 5 (8.3333 %)\n Variance from outliers : 82.3868 % Variance is severely inflated by outliers\n\n\n; With type hints\n\n(cc/bench\n (parse-int \"1234567890\"))\n\nEvaluation count : 187133520 in 60 samples of 3118892 calls.\n Execution time mean : 318.835981 ns ; <-----------------------\n Execution time std-deviation : 3.399965 ns \n Execution time lower quantile : 314.452726 ns ( 2.5%)\n Execution time upper quantile : 326.997655 ns (97.5%)\n Overhead used : 4.213229 ns\n\nFound 4 outliers in 60 samples (6.6667 %)\n low-severe 2 (3.3333 %)\n low-mild 2 (3.3333 %)\n Variance from outliers : 1.6389 % Variance is slightly inflated by outliers\n</code></pre>\n\n<p>That's over 5x faster just from adding type-hints.</p>\n\n<p>Here's a personal favorite of mine though that's <em>much</em> faster, and just falls back onto Java's <code>parseInt</code> implementation:</p>\n\n<pre><code>(defn my-parse-int [^String str-num]\n (try\n (Integer/parseInt str-num) ; Fall back onto Java\n\n (catch NumberFormatException _\n nil))) ; Return nil on a bad parse\n\n(cc/bench\n (my-parse-int \"1234567890\"))\nEvaluation count : 1531312920 in 60 samples of 25521882 calls.\n Execution time mean : 35.208889 ns ; <-----------------------\n Execution time std-deviation : 1.018581 ns\n Execution time lower quantile : 34.554978 ns ( 2.5%)\n Execution time upper quantile : 38.078887 ns (97.5%)\n Overhead used : 4.213229 ns\n\nFound 7 outliers in 60 samples (11.6667 %)\n low-severe 4 (6.6667 %)\n low-mild 3 (5.0000 %)\n Variance from outliers : 15.8023 % Variance is moderately inflated by outliers\n</code></pre>\n\n<p>35 ns!</p>\n\n<p>Note how I'm wrapping the parsing call in a <code>try</code> and returning <code>nil</code> in the event of an exception. In Clojure, it's common for <code>nil</code> to represent the absence of a valid value; like after a bad parse. It's similar to other language's notion of an <code>Optional</code> type. This concept allows you to do all sorts of nice things. Like, say you have a list of possible String numbers and you want to grab the first valid number:</p>\n\n<pre><code>(some my-parse-int [\"bad\" \"also bad\" \"123\" \"another bad\"])\n=> 123\n</code></pre>\n\n<p><code>some</code> ignores all the <code>nil</code>s because they're falsey.</p>\n\n<hr>\n\n<pre><code>(cond\n (= has_more true) (fetch-question (+ page 1) from site (concat accum questions))\n :else (concat accum questions))\n))\n</code></pre>\n\n<p>Isn't written ideally.</p>\n\n<ul>\n<li><p>A <code>cond</code> with only one condition should just be an <code>if</code> unless you have a strong suspicion that you'll need to add more cases later</p></li>\n<li><p><code>(= ... true</code>) is redundant. <code>if</code> is already checking if the condition evaluates to a truthy value.</p></li>\n<li><p><code>(+ page 1)</code> can be simply <code>(inc page)</code></p></li>\n<li><p>Trailing closing braces like that aren't generally considered to be idiomatic style. Ideally you're using a good IDE that uses par(enthesis)-infer. That lets you write Clojure code using indentation to indicate nesting like it's Python. I never worry about braces when writing Clojure, and never manually type closing braces.</p>\n\n<p>If you have a decent computer, I recommend the <a href=\"https://www.jetbrains.com/idea/download/#section=windows\" rel=\"nofollow noreferrer\">Community version of IntelliJ</a>, paired with the <a href=\"https://cursive-ide.com/\" rel=\"nofollow noreferrer\">Cursive plugin</a> that allows for writing Clojure (both are free for personal use). I've been using this setup for three years now, and it's excellent (heavy, but excellent).</p></li>\n</ul>\n\n<p>Anyways, I'd write that chunk just as</p>\n\n<pre><code>(if has-more\n (fetch-question (inc page) from site (concat accum questions))\n (concat accum questions))\n</code></pre>\n\n<p>That reads nicer anyways. You write <code>(concat accum questions)</code> twice though. I'd probably bind that to a name to reduce redundancy:</p>\n\n<pre><code>(let [...\n more-questions (concat accum questions)]\n ...\n\n (if has-more\n (fetch-question (inc page) from site more-questions)\n more-questions))\n</code></pre>\n\n<hr>\n\n<p>With</p>\n\n<pre><code>(defn print-questions [questions]\n (doseq [q questions] (println (get q \"title\"))))\n</code></pre>\n\n<p>I wouldn't shove everything onto one line like that. I would spread that out:</p>\n\n<pre><code>(defn print-questions [questions]\n (doseq [q questions]\n (println (get q \"title\"))))\n</code></pre>\n\n<hr>\n\n<p>I'm not sure if you know about Clojure's doc-strings, but you have yours in the wrong place. The doc-string comes before the argument list. <code>defn</code> actually expects a String to internalize to act as a doc-string (see the <a href=\"https://clojuredocs.org/clojure.core/defn\" rel=\"nofollow noreferrer\">docs of <code>defn</code></a>). Just move it up:</p>\n\n<pre><code>(defn save-time\n \"save value to configuration file; file will be overwritten\"\n [value]\n (spit config-file-name value))\n</code></pre>\n\n<p>Now good IDE's can show that documentation when requested.</p>\n\n<p>Also, most of your casing is correct, but remember Clojure using dash-casing like I changed it to, not camelCasing, or snake_casing like you're using elsewhere. Consistency is key for readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:46:36.927",
"Id": "435590",
"Score": "0",
"body": "Thank you very much for advice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:40:28.013",
"Id": "224567",
"ParentId": "224549",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T10:23:29.123",
"Id": "224549",
"Score": "3",
"Tags": [
"json",
"api",
"clojure",
"stackexchange",
"client"
],
"Title": "Get list of new questions from Stack Overflow"
}
|
224549
|
<p>create a function which predicts the next time a satellite image will be taken of a certain location.
When there is enough data to do so, the function should print a prediction for when the next picture will be taken.
and when there is no enough data then return error.
if prediction date is less than current date, then return send future date.</p>
<pre><code>import requests
from datetime import datetime
from datetime import timedelta
import math
import numpy as np
# NASA's API and API key
API = "https://api.nasa.gov/planetary/earth/assets"
API_KEY = "xxxxxxxxxxxxxxxxxx"
# Constants
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S'
# Error Constants
INVALID_COORDINATES = 'Invalid coordinate!'
INSUFFICIENT_DATA = 'Insufficient data recorded'
def flyby(latitude, longitude, place='not specified'):
print("place ", place)
# if invalid coordinate print invalid
if latitude < -90 or latitude > 90 or longitude < -180 or longitude > 180:
print(INVALID_COORDINATES)
return INVALID_COORDINATES
querystring = {"api_key": API_KEY, "lat": str(latitude),
"lon": str(longitude)}
response = requests.request("GET", API, params=querystring)
if response.status_code != 200:
return response.text
json_response = response.json()
total_records = json_response.get('count')
results = json_response.get('results')
# if count < 2, print insufficient
if total_records < 2:
print(INSUFFICIENT_DATA)
return INSUFFICIENT_DATA
avg_time_delta, last_date = latest_average_time_delta(results,
total_records)
sd = get_standard_deviation(results, total_records)
print("latest : {}".format(last_date))
print("ave_time_delta : {}".format(avg_time_delta))
dates_diff = datetime.today() - last_date
if dates_diff.total_seconds() < 0:
predicted = last_date
else:
dates_diff % avg_time_delta
predicted = datetime.today() + (dates_diff % avg_time_delta)
print("Next time: {}".format(predicted))
print("Next time also can be between {} : {}".format(
predicted - timedelta(seconds=sd),
predicted + timedelta(seconds=sd)))
print("-----------------------")
def latest_average_time_delta(results, count):
dates = map(lambda x: datetime.strptime(x['date'], DATE_FORMAT), results)
dates_list = list(dates)
oldest = min(dates_list)
youngest = max(dates_list)
# Average time taken is the duration between the youngest and oldest
# recorded date, divided by the number of periods (n - 1)
ave_time_delta = (youngest - oldest) / (count - 1)
return ave_time_delta, youngest
def get_standard_deviation(results, count):
str_dates = map(lambda x: x['date'], results)
mean_date = (np.array(list(str_dates), dtype='datetime64[s]')
.view('i8')
.mean()
.astype('datetime64[s]'))
print("Average Date ", mean_date)
dates = map(lambda x: datetime.strptime(x['date'], DATE_FORMAT), results)
dates_list = list(dates)
sd = 0.0
for date in dates_list:
date_diff = date - mean_date.astype(datetime)
sd += date_diff.seconds ** 2
sd = math.sqrt(sd / float(count - 1))
return sd
lat = 36.998979
lon = -109.045183
flyby(lat, lon)
flyby(0.000000, 0.000000, "GULF OF GUINEA")
flyby(36.098592, -112.097796, "GRAND CANYON")
flyby(43.078154, -79.075891, "NIAGARA FALLS")
flyby(36.998979, -109.045183, "FOUR CORNERS")
flyby(37.7937007, -122.4039064, "DELPHIX")
# BOUNDARY/EDGE
# MINIMUM LATITUDE
flyby(-90.000001, 0.000000, "MIN LAT 1")
flyby(-90.000000, 0.000000, "MIN LAT 2")
flyby(-89.999999, 0.000000, "MIN LAT 3")
# MAXIMUM LATITUDE
flyby(89.999999, 0.000000, "MAX LAT 1")
flyby(90.000000, 0.000000, "MAX LAT 2")
flyby(90.000001, 0.000000, "MAX LAT 3")
# MINIMUM LONGITUDE
flyby(0.000000, -180.000001, "MIN LON 1")
flyby(0.000000, -180.000000, "MIN LON 2")
flyby(0.000000, -179.999999, "MIN LON 3")
# MAXIMUM LONGITUDE
flyby(0.000000, 179.999999, "MAX LON 1")
flyby(0.000000, 180.000000, "MAX LON 2")
flyby(0.000000, 180.000001, "MAX LON 3")
# EDGES COMBINATION
flyby(-90.000000, -180.000000, "MIN LAT, MIN LON")
flyby(-90.000000, 180.000000, "MIN LAT, MAX LON")
flyby(90.000000, -180.000000, "MAX LAT, MIN LON")
flyby(90.000000, 180.000000, "MAX LAT, MAX LON")
</code></pre>
<p>Any feedback on style, flaws in the code, or how to improve the algorithm would be greatly appreciated.</p>
|
[] |
[
{
"body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>You never use the return value of <code>flyby</code>, so it might as well <code>return None</code> or <code>raise InvalidCoordinateError()</code>. Raising exceptions is generally the most useful way to provide information for users to act on, because it tells them not just what went wrong (\"Invalid coordinate!\") but <em>where</em> because of the stack trace.</li>\n<li>Ditto for <code>return response.text</code> - it would be more useful as something like <code>raise UnhandledResponseError(response.text)</code>.</li>\n<li>The API key should be configuration, not code. In general such keys should not be anywhere in your repository, for a host of reasons which should be spelled out in the license. This could include rate limiting, whether you are even allowed to share the key, and which groups of people it can be used by (for example, excluding commercial enterprises).</li>\n<li><code>dates_diff % avg_time_delta</code> doesn't actually do anything with the result of the calculation, so that line can be deleted.</li>\n<li>It is nice that you have test cases, but it would be better to put those in a real <code>TestCase</code> class and being explicit about what they should do. This will show that the code is hard to test because the main side effect is simply printing, and testing <code>print</code> statements is much hairier than testing return values. It seems a useful return value would be the tuple <code>(predicted, sd)</code> or an object.</li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>(That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. Conversely, on an ugly old piece of code I wrote without static analysis support I recently found the complexity reaches 87!)</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T12:16:50.130",
"Id": "435565",
"Score": "0",
"body": "Thanks @l0b0 for your valuable feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T07:42:47.497",
"Id": "437991",
"Score": "0",
"body": "Can you please share your suggestions if I want to convert it into object oriented design and any other suggestions If I can make it more modular."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T08:20:31.453",
"Id": "437993",
"Score": "0",
"body": "That would take a long time if you haven't had any exposure to OO, and is unfortunately not something I have time to do. The best thing you could do would be to find a meatspace mentor – someone at work or who you know well, and who can show you how and when to use OO, and how to transform your code step by step. If you end up studying OO you can submit your work here for further reviews; that would be one way of learning. Again, this is not a small task, and people learn best in different ways."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T11:18:26.990",
"Id": "224553",
"ParentId": "224550",
"Score": "2"
}
},
{
"body": "<p>code after some adding some exception handling.</p>\n\n<pre><code>import math\nfrom datetime import datetime\nfrom datetime import timedelta\n\nimport numpy as np\nimport requests\n\n# NASA's API and API key\nAPI = \"https://api.nasa.gov/planetary/earth/assets\"\n\n# This can go to some configuration file\nAPI_KEY = \"9Jz6tLIeJ0yY9vjbEUWaH9fsXA930J9hspPchute\"\n\n# Constants\nDATE_FORMAT = '%Y-%m-%dT%H:%M:%S'\n\n# Error Constants\nINVALID_COORDINATES = 'ERROR_INVALID_COORDINATE'\nINSUFFICIENT_DATA = 'ERROR_INSUFFICIENT_DATA_RECORDED'\nUNHANDLED_RESPONSE = 'ERROR_UNHANDLED_RESPONSE'\n\n\nclass BaseException(Exception):\n \"\"\"\n Base exception class\n \"\"\"\n err_code = None\n err_str = None\n\n def to_dict(self):\n \"\"\"\n return json object\n \"\"\"\n return {\n 'err_code': self.err_code,\n 'err_str': self.err_str\n }\n\n\nclass UnhandledResponseError(BaseException):\n \"\"\"\n Unhandled response\n \"\"\"\n err_code = 1000\n err_str = UNHANDLED_RESPONSE\n\n\nclass InvalidCoordinateError(BaseException):\n \"\"\"\n Invalid Coordinate exception\n \"\"\"\n err_code = 1001\n err_str = INVALID_COORDINATES\n\n\nclass InsufficientDataError(BaseException):\n \"\"\"\n Insufficient data recorded\n \"\"\"\n err_code = 1002\n err_str = INSUFFICIENT_DATA\n\n\ndef flyby(latitude, longitude):\n try:\n if latitude < -90 or latitude > 90 or longitude < -180 or longitude > 180:\n raise InvalidCoordinateError\n\n querystring = {\"api_key\": API_KEY, \"lat\": str(latitude),\n \"lon\": str(longitude)}\n\n response = requests.request(\"GET\", API, params=querystring)\n\n if response.status_code != 200:\n raise UnhandledResponseError\n\n json_response = response.json()\n total_records = json_response.get('count')\n results = json_response.get('results')\n\n if total_records < 2:\n raise InsufficientDataError\n\n avg_time_delta, last_date = \\\n get_last_date_and_average_time_delta(results, total_records)\n\n sd = get_standard_deviation(results, total_records)\n print(\"latest : {}\".format(last_date))\n print(\"average time delta : {}\".format(avg_time_delta))\n\n dates_diff = datetime.today() - last_date\n if dates_diff.total_seconds() < 0:\n predicted = last_date\n else:\n dates_diff % avg_time_delta\n predicted = datetime.today() + (dates_diff % avg_time_delta)\n\n print(\"Next time: {}\".format(predicted))\n print(\"Next time also can be between {} : {}\".format(\n predicted - timedelta(seconds=sd),\n predicted + timedelta(seconds=sd)))\n print(\"-----------------------\")\n return predicted\n\n except (InvalidCoordinateError, InsufficientDataError,\n UnhandledResponseError) as err:\n print(err.to_dict())\n print(\"-----------------------\")\n return err.to_dict()\n\n\ndef get_last_date_and_average_time_delta(results, count):\n dates = map(lambda x: datetime.strptime(x['date'], DATE_FORMAT), results)\n dates_list = list(dates)\n\n oldest = min(dates_list)\n youngest = max(dates_list)\n\n # Average time taken is the duration between the youngest and oldest\n # recorded date, divided by the number of periods (n - 1)\n ave_time_delta = (youngest - oldest) / (count - 1)\n return ave_time_delta, youngest\n\n\ndef get_standard_deviation(results, count):\n str_dates = map(lambda x: x['date'], results)\n mean_date = (np.array(list(str_dates), dtype='datetime64[s]')\n .view('i8')\n .mean()\n .astype('datetime64[s]'))\n dates = map(lambda x: datetime.strptime(x['date'], DATE_FORMAT), results)\n dates_list = list(dates)\n sd = 0.0\n for date in dates_list:\n date_diff = date - mean_date.astype(datetime)\n sd += date_diff.seconds ** 2\n sd = math.sqrt(sd / float(count - 1))\n return sd\n\n\nif __name__ == \"__main__\":\n print(\"GULF OF GUINEA\")\n result = flyby(0.000000, 0.000000)\n assert result['err_str'] == INSUFFICIENT_DATA\n\n print(\"GRAND CANYON\")\n result = flyby(36.098592, -112.097796)\n assert result is not None\n\n print(\"NIAGARA FALLS\")\n result = flyby(43.078154, -79.075891)\n assert result is not None\n\n print(\"FOUR CORNERS\")\n result = flyby(36.998979, -109.045183)\n assert result is not None\n\n print(\"DELPHIX\")\n result = flyby(37.7937007, -122.4039064)\n assert result is not None\n\n print(\"Invalid Latitude Negative\")\n result = flyby(-90.000001, 0.000000, )\n assert result['err_str'] == INVALID_COORDINATES\n print(\"Minimum Latitude\")\n result = flyby(-90.000000, 0.000000)\n assert result['err_str'] == INSUFFICIENT_DATA\n\n print(\"Invalid Latitude Positive\")\n result = flyby(90.000001, 0.000000, )\n assert result['err_str'] == INVALID_COORDINATES\n print(\"Maximum Latitude\")\n result = flyby(90.000000, 0.000000)\n assert result['err_str'] == INSUFFICIENT_DATA\n\n print(\"Invalid Longitude Negative\")\n result = flyby(0.000000, -180.000001)\n assert result['err_str'] == INVALID_COORDINATES\n print(\"Minimum Longitude\")\n result = flyby(0.000000, -180.000000)\n assert result['err_str'] == INSUFFICIENT_DATA\n\n print(\"Invalid Longitude Positive\")\n result = flyby(0.000000, 180.000001, )\n assert result['err_str'] == INVALID_COORDINATES\n print(\"Maximum Longitude\")\n result = flyby(0.000000, 180.000000, )\n assert result['err_str'] == INSUFFICIENT_DATA\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:32:19.660",
"Id": "444986",
"Score": "0",
"body": "Code-only answers are discouraged - the goal of asking questions here is to *learn,* not to receive a blob of code which may or may not be better than the original. You might want to explain *why* OP would want to add exception handling, where to get more information about exception handling, etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T07:15:03.937",
"Id": "225636",
"ParentId": "224550",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "224553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T10:32:45.473",
"Id": "224550",
"Score": "3",
"Tags": [
"python",
"numpy"
],
"Title": "Find the next predicted time a satellite is going to take picture of place"
}
|
224550
|
<p>I have the following code that I wrote in order to find the correct password by generating hashes out of all possible combinations and comparing each of them with the target. I'm trying to make <code>GetPasswordFromHash()</code> as efficient as possible, in regards to multi-threading, and I've decided to pick PLINQ for that.</p>
<p>Scrypt/Pbkdf2 functions come from <strong><a href="https://www.nuget.org/packages/CryptSharpStandard" rel="nofollow noreferrer"><code>CryptSharpStandard</code></a></strong> library and they're CPU-bound tasks that generate password hashes (returning <code>byte[]</code>). I've verified that this implementation works correctly for my use case (I'll be given only password hash and salt to work with), but if you have any other library recommendations, I'm also willing to check them out.</p>
<p>Right now, the correct result is generated in approx 1m30s on my machine, while single-threaded solution took at least 3x as much (approx 300s, both tested on my i7 7700k box).</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using CryptSharp.Utility;
namespace CryptTest {
internal static class Program {
// Those 3 are provided by third-party, they're not expected to be configurable
private const byte BlocksCount = 8;
private const ushort Pbkdf2IterationsCount = 10000;
private const ushort ScryptIterationsCount = 8192;
private static IEnumerable<byte[]> AllPasswordCodes {
get {
for (char a = '0'; a <= '9'; a++) {
for (char b = '0'; b <= '9'; b++) {
for (char c = '0'; c <= '9'; c++) {
for (char d = '0'; d <= '9'; d++) {
yield return new[] { (byte) a, (byte) b, (byte) c, (byte) d };
}
}
}
}
}
}
internal static string GetPasswordFromHash(byte[] passwordHash, byte[] salt, bool scrypt = true) {
if ((passwordHash == null) || (salt == null)) {
return null;
}
byte[] password = scrypt
? AllPasswordCodes.AsParallel().FirstOrDefault(passwordToTry => passwordHash.SequenceEqual(SCrypt.ComputeDerivedKey(passwordToTry, salt, ScryptIterationsCount, BlocksCount, 1, null, passwordHash.Length)))
: AllPasswordCodes.AsParallel().FirstOrDefault(
passwordToTry => {
using (HMACSHA1 hmacAlgorithm = new HMACSHA1(passwordToTry)) {
return passwordHash.SequenceEqual(Pbkdf2.ComputeDerivedKey(hmacAlgorithm, salt, Pbkdf2IterationsCount, passwordHash.Length));
}
}
);
return password != null ? Encoding.UTF8.GetString(password) : null;
}
private static void Main() {
// Main() is used for benchmarking and verification only, no need to focus on that besides correctness
byte[] salt = new byte[7];
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {
crypto.GetNonZeroBytes(salt);
}
byte[] password = { (byte) '1', (byte) '3', (byte) '3', (byte) '7' };
byte[] passwordHash = SCrypt.ComputeDerivedKey(password, salt, ScryptIterationsCount, BlocksCount, 1, null, 32);
Stopwatch watch = new Stopwatch();
watch.Start();
string generatedPassword = GetPasswordFromHash(passwordHash, salt);
watch.Stop();
Console.WriteLine("Verification: " + Encoding.UTF8.GetBytes(generatedPassword).SequenceEqual(password));
Console.WriteLine("Time elaped: " + watch.Elapsed);
Console.ReadLine();
}
}
}
</code></pre>
<p>I'm trying to balance the code readability/size with the performance benefits, and I'm quite happy with the current solution, although at the same time I'm wondering if there is anything else to improve in regards to that. I can (and will) make appropriate benchmarks myself, this is more about code analysis and ideas for improvements, rather than checking whether solution <code>X</code> will do better/worse than current one, I can check that myself. Please feel free to share your suggested code edits or ideas, I'll greatly appreciate and check all of them. Even if you can't think of anything better, I also value your response as it gives me feedback in terms of correct solution.</p>
<p>Thank you in advance for your time!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T14:23:15.887",
"Id": "435581",
"Score": "0",
"body": "Is there a use case for brute forcing hashes against this input? I just wonder why you want to implement such a function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T14:51:01.700",
"Id": "435583",
"Score": "0",
"body": "@dfhwze Yes, I'm using it as a recovery mechanism for lost passwords in a particular third-party service which provides me with hash and salt. No, I don't maintain that third-party service, I'm only providing the missing functionality based on a possibility. The service provides those credentials for the client to verify his password against the saved one. I could provide the exact service details but I don't think they're needed or appropriate. It's not used with any malicious intent, since the service provides those details intentionally upon request (which requires prior authorization)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T14:56:27.917",
"Id": "435584",
"Score": "0",
"body": "Interesting feature of that API. Seems like paradise for h3ckor²."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:02:57.610",
"Id": "435585",
"Score": "0",
"body": "Yes, I fully realize the loophole they've created, and I also have the same opinion as you. The only supportive argument is the fact that this is extra authorization (parental control) upon already authenticated account, which could be \"justified\" as \"it's just a stupid code to stop children from accessing several service features\", but it still could be done better, in at least several different ways. Well, I'm luckily not in charge of that API or service, just making a helper function for those in need (or script kiddies I guess...). In any case, thanks for your concern, I appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:28:02.843",
"Id": "435587",
"Score": "0",
"body": "I tried compiling using CryptSharp v1.3.0 (latest stable), but the method signatures don't match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:34:06.237",
"Id": "435588",
"Score": "0",
"body": "@dfhwze Thank you for your interest! I should point out that I used `CryptSharpStandard` as it's a `netcoreapp2.2` project, please give it a try: https://www.nuget.org/packages/CryptSharpStandard | I'm sorry for confusion, I should include that information in the OP. Thanks again!"
}
] |
[
{
"body": "<blockquote>\n <p><em>I'm trying to balance the code readability/size with the performance\n benefits, ..</em></p>\n</blockquote>\n\n<p>Your code could be optimized for readability and object-oriented design without introducing a performance penalty.</p>\n\n<hr>\n\n<p>The entropy generation could be written more elegantly.</p>\n\n<p>original code </p>\n\n<blockquote>\n<pre><code>for (char a = '0'; a <= '9'; a++) {\n for (char b = '0'; b <= '9'; b++) {\n for (char c = '0'; c <= '9'; c++) {\n for (char d = '0'; d <= '9'; d++) {\n yield return new[] { (byte) a, (byte) b, (byte) c, (byte) d };\n }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>refactored</p>\n\n<pre><code>static class EntropyGenerator\n{\n public static IEnumerable<byte> ValidChars => Enumerable.Range('0', 10).Select(c => (byte)c).ToList();\n\n public static IEnumerable<byte[]> GenerateEntropy()\n {\n return (from a in ValidChars\n from b in ValidChars\n from c in ValidChars\n from d in ValidChars\n select new[] { a, b, c, d });\n }\n}\n</code></pre>\n\n<hr>\n\n<p><code>GetPasswordFromHash</code> has repeating code and an ugly switch that could be refactored into a strategy pattern.</p>\n\n<p>First, we should create an enum and interface for the strategies. It would have helped if this API came with its own interface. </p>\n\n<pre><code>interface IHashProvider\n{\n byte[] ComputeDerivedKey(byte[] key, byte[] salt, int derivedKeyLength);\n}\n\nenum HashProviderAlgorithm\n{\n SCrypt,\n Pbkdf2\n}\n</code></pre>\n\n<p>We can then implement both strategies.</p>\n\n<pre><code>class ScryptHashProvider : IHashProvider\n{\n private const byte BlocksCount = 8;\n private const ushort IterationsCount = 8192;\n\n public byte[] ComputeDerivedKey(byte[] key, byte[] salt, int derivedKeyLength)\n {\n return SCrypt.ComputeDerivedKey(key, salt, IterationsCount, BlocksCount, 1, null, derivedKeyLength);\n }\n}\n\nclass Pbkdf2HashProvider : IHashProvider\n{\n private const ushort IterationsCount = 10000;\n\n public byte[] ComputeDerivedKey(byte[] key, byte[] salt, int derivedKeyLength)\n {\n using (var hmac = new HMACSHA1(key))\n {\n return Pbkdf2.ComputeDerivedKey(hmac, salt, IterationsCount, derivedKeyLength);\n }\n }\n}\n</code></pre>\n\n<p>So the password recovery mechanism can be written much more elegantly.</p>\n\n<pre><code>class PasswordRecovery\n{\n IEnumerable<byte[]> Entropy { get; }\n IDictionary<HashProviderAlgorithm, IHashProvider> Providers { get; }\n\n public PasswordRecovery(IEnumerable<byte[]> entropy)\n {\n Entropy = entropy ?? throw new ArgumentNullException(nameof(entropy));\n Providers = new Dictionary<HashProviderAlgorithm, IHashProvider>\n {\n { HashProviderAlgorithm.SCrypt, new ScryptHashProvider() },\n { HashProviderAlgorithm.Pbkdf2, new Pbkdf2HashProvider() }\n };\n }\n\n public string RecoverPassword(byte[] passwordHash, byte[] salt, HashProviderAlgorithm algorithm = default)\n {\n if (passwordHash == null)\n throw new ArgumentNullException(nameof(passwordHash));\n if (salt == null)\n throw new ArgumentNullException(nameof(salt));\n\n var entropy = Entropy.AsParallel();\n var provider = Providers[algorithm];\n var password = entropy.FirstOrDefault(\n pwd => passwordHash.SequenceEqual(provider.ComputeDerivedKey(pwd, salt, passwordHash.Length)));\n\n if (password == null)\n throw new ArgumentException(\"Unable to recover password given the specified entropy, hash and salt\");\n\n return Encoding.UTF8.GetString(password);\n }\n}\n</code></pre>\n\n<p>And our verification test:</p>\n\n<pre><code>// arrange\nvar salt = new byte[7];\nusing (var crypto = new RNGCryptoServiceProvider())\n{\n crypto.GetNonZeroBytes(salt);\n}\nvar password = new [] { (byte)'1', (byte)'3', (byte)'3', (byte)'7' };\nvar passwordHash = SCrypt.ComputeDerivedKey(password, salt, 8192, 8, 1, null, 32);\n\n// act\nvar entropy = EntropyGenerator.GenerateEntropy();\nvar passwordRecovery = new PasswordRecovery(entropy);\nvar generatedPassword = passwordRecovery.RecoverPassword(passwordHash, salt);\n\n// assert\nvar recovered = Encoding.UTF8.GetBytes(generatedPassword).SequenceEqual(password);\nAssert.IsTrue(recovered);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:33:25.320",
"Id": "435596",
"Score": "0",
"body": "Thanks a lot! I'll for sure make use of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:34:44.547",
"Id": "435597",
"Score": "1",
"body": "oh, and when the password is not found I would throw an exception like `PasswordNotFoundException`, `ArgumentException` is for arguments which in this case are technically correct but just the wrong guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:45:26.280",
"Id": "435599",
"Score": "1",
"body": "@t3chb0t I hate creating a new exception class for this :) I don't have DynamicException, so perhaps KeyNotFoundException or something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:35:25.123",
"Id": "435613",
"Score": "2",
"body": "+1; though I don't like the `HashProviderAlgorithm algorithm = default`: this doesn't really document the intention. I'd rather it was explicitly `HashProviderAlgorithm algorithm = HashProviderAlgorithm.Scrypt`, and that the `enum` options were assigned explicit values if they are going to be used as default values; otherwise, I'd probably make it non-optional and provide an overload, so that `HashProviderAlgorithm.Scrypt` isn't baked at compile-time. All that said, I'd probably drop the `enum` altogether and just pass in the `interface`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:38:19.530",
"Id": "435614",
"Score": "1",
"body": "@VisualMelon Good points. I took over the _default_ because the OP did the same thing (but I shouldn't have). My solution is an archaic SPI style, where an algorithm is specified by name (or enum), not by interface. Dropping the enum seems a more flexible and contemporary choice."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:21:01.127",
"Id": "224570",
"ParentId": "224558",
"Score": "6"
}
},
{
"body": "<p>dfhwze has addressed the structural and other issues with the code, so I will focus on eliminating the <em>pyramid of doom</em> in <code>AllPasswordCodes</code>:</p>\n\n<blockquote>\n<pre><code> private static IEnumerable<byte[]> AllPasswordCodes {\n get {\n for (char a = '0'; a <= '9'; a++) {\n for (char b = '0'; b <= '9'; b++) {\n for (char c = '0'; c <= '9'; c++) {\n for (char d = '0'; d <= '9'; d++) {\n yield return new[] { (byte) a, (byte) b, (byte) c, (byte) d };\n }\n }\n }\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>It can be done in a single loop in the following way:</p>\n\n<pre><code>public static IEnumerable<Byte[]> GetAllPasswords()\n{\n for (int i = 0; i < 1e4; i++)\n {\n yield return Encoding.ASCII.GetBytes(i.ToString(\"0000\"));\n }\n}\n</code></pre>\n\n<p>It's maybe a few milliseconds slower, but IMO more maintainable. </p>\n\n<p>Alternatively you can do:</p>\n\n<pre><code>public static IEnumerable<Byte[]> GetAllPasswords()\n{\n for (int i = 0; i < 1e4; i++)\n {\n yield return new byte[] \n {\n (byte)('0' + i / 1000),\n (byte)('0' + i % 1000 / 100),\n (byte)('0' + i % 100 / 10),\n (byte)('0' + i % 10)\n };\n }\n}\n</code></pre>\n\n<p>Which seems to have same performance as the original.</p>\n\n<p>As shown I've changed it from a property to a method, because IMO a property shouldn't execute code in this way to return. Alternatively you could make a class implementing <code>IEnumerable<T></code>:</p>\n\n<pre><code> class PasswordEnumerator : IEnumerable<byte[]>\n {\n public IEnumerator<byte[]> GetEnumerator()\n {\n for (int i = 0; i < 1e4; i++)\n {\n yield return new byte[] \n {\n (byte)('0' + i / 1000),\n (byte)('0' + i % 1000 / 100),\n (byte)('0' + i % 100 / 10),\n (byte)('0' + i % 10)\n };\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:21:03.863",
"Id": "224592",
"ParentId": "224558",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "224570",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T12:24:14.250",
"Id": "224558",
"Score": "5",
"Tags": [
"c#",
"performance",
"multithreading",
"linq",
"cryptography"
],
"Title": "PLINQ code analysis in terms of efficiency of cryptographic hashes generation"
}
|
224558
|
<p>This is an OOP version of <a href="https://codereview.stackexchange.com/questions/219489/lastest-version-of-my-blackjack-game">Lastest version of my Blackjack game</a>. Also, it now uses PostgreSQL as database.</p>
<pre><code>import random
import typing as t
from enum import Enum
from functools import partial
import os
from getpass import getpass
from re import match
import bcrypt
import psycopg2
import attr
lock = partial(attr.s, auto_attribs=True, slots=True)
State = Enum("State", "IDLE ACTIVE STAND BUST")
def clear_console():
os.system("cls" if os.name == "nt" else "clear")
def start_choice():
while True:
ans = input(
"\nWhat do you want to do?\n[1] - Start playing\n[2] - Display the top\n> "
)
if ans in ("1", "2"):
return ans == "1"
def ask_question(question):
while True:
print(f"{question} (y/n)?")
ans = input("> ").casefold()
if ans in ("y", "n"):
return ans == "y"
def ask_bet(budget):
clear_console()
print(f"Money: ${budget}")
print("How much money do you want to bet?")
while True:
money_bet = input("> ")
try:
cash_bet = int(money_bet)
except ValueError:
cash_bet = -1
if budget >= cash_bet > 0:
return cash_bet
print("Please input a valid bet.")
def get_user_credentials():
clear_console()
while True:
email = input("Email address (max. 255 chars.):\n> ")
password = getpass("Password (max. 1000 chars.):\n> ").encode("utf8")
hashed_pw = bcrypt.hashpw(password, bcrypt.gensalt()).decode("utf8")
if len(email) < 255 and len(password) < 1000:
if match(r"[^@]+@[^@]+\.[^@]+", email):
return email, password, hashed_pw
print("Please input a valid email address.")
def build_deck():
suits = ["Hearts", "Clubs", "Diamonds", "Spades"]
values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
cards = [Card(value, suit) for value in values for suit in suits]
return cards
@lock
class Card:
value: str
suit: str
def score(self):
if self.value in "JQK":
return 10
elif self.value == "A":
return 1
else:
return int(self.value)
def __str__(self):
return f"{self.value} of {self.suit}"
@lock
class Shoe:
cards: t.List[Card] = attr.ib(factory=build_deck)
def shuffle(self):
random.shuffle(self.cards)
def draw_card(self):
return self.cards.pop()
def __str__(self):
cards = [str(c) for c in self.cards]
return str(cards)
@lock
class Hand:
# A collection of cards that a player get from the dealer in a game
cards: t.List[Card] = attr.ib(default=[])
def add(self, card):
self.cards.append(card)
def score(self):
# Value of cards at hand
total = sum(card.score() for card in self.cards)
if any(card.value == "A" for card in self.cards) and total <= 11:
total += 10
return total
def __str__(self):
return "{} ({})".format(
"".join("[{}]".format(card.value) for card in self.cards), self.score()
)
@lock
class Player:
budget: int # Number of money for bets
bet: int = attr.ib(default=None) # Money bet
hand: Hand = attr.ib(factory=Hand) # Player's hand
state: State = attr.ib(default=State.IDLE) # can be IDLE, ACTIVE, STAND or BUST
def player_bet(self):
if self.is_broke():
raise Exception("Unfortunately you don't have any money.")
self.bet = ask_bet(self.budget)
""" Update self.state after self.hit
If player busted, self.state = State.BUST, etc.
"""
def update(self):
hand_score = self.hand.score()
if hand_score > 21:
self.state = State.BUST
elif hand_score == 21:
self.state = State.STAND
else:
self.state = State.ACTIVE
def is_busted(self):
return self.state == State.BUST
def is_standing(self):
return self.state == State.STAND
def is_idle(self):
return self.state == State.IDLE
def is_broke(self):
return self.budget == 0
def hit(self, dealer):
# Ask dealer to add a card to the hand (at their turn)
card = dealer.draw_card()
self.hand.add(card)
def play(self, dealer):
if ask_question("Do you want to hit"):
# Player hits
self.hit(dealer)
self.update()
else:
self.state = State.STAND
def __str__(self):
return f"Player Info:\nBudget: {self.budget}\nMoney bet: {self.bet}\nHand: {self.hand}"
@lock
class Dealer:
shoe: Shoe = attr.ib(factory=Shoe)
hand: Hand = attr.ib(factory=Hand)
state: State = attr.ib(default=State.IDLE)
def draw_card(self): # Delegate method
card = self.shoe.draw_card()
return card
def hit(self):
card = self.draw_card()
self.hand.add(card)
def update(self):
hand_score = self.hand.score()
if hand_score > 21:
self.state = State.BUST
elif hand_score >= 17:
self.state = State.STAND
else:
self.state = State.ACTIVE
def is_busted(self):
return self.state == State.BUST
def is_standing(self):
return self.state == State.STAND
def is_idle(self):
return self.state == State.IDLE
def play(self):
if self.hand.score() < 17:
self.hit()
self.update()
""" In this method, the dealer and player enter a loop
In which the player hits a card from the dealer until it stands or busts
"""
def deal(self, player, game):
while True:
player.play(self)
game.display_info()
if player.is_busted() or player.is_standing():
break
def display_cards(self, player, game):
if game.is_finished():
return f"Dealer Info:\nHand:{self.hand}"
elif player.state == State.ACTIVE:
return f"Dealer Info:\nHand: [{self.hand.cards[0]}][?]"
@lock
class Database:
sql_id: int = attr.ib(default=None)
email: str = attr.ib(default=None)
password: str = attr.ib(default=None)
hashed_pw: str = attr.ib(default=None)
budget: int = attr.ib(default=None)
conn: t.Any = attr.ib(
default=psycopg2.connect(
dbname="blackjack", user="postgres", password="12344321", host="localhost"
)
)
cur: t.Any = attr.ib(default=None)
def check_account(self):
self.cur.execute("SELECT id FROM users WHERE email=%s", (self.email,))
return bool(self.cur.fetchone())
def login(self):
self.cur.execute("SELECT password FROM users WHERE email=%s", (self.email,))
credentials = self.cur.fetchone()
correct_hash = credentials[0].encode("utf8")
if bcrypt.checkpw(self.password, correct_hash):
print("You have successfully logged-in!")
else:
raise Exception("You have failed logging-in!")
def register(self):
self.cur.execute(
"INSERT into users (email, password) VALUES (%s, %s)",
(self.email, self.hashed_pw),
)
def initialize(self):
with self.conn:
self.email, self.password, self.hashed_pw = get_user_credentials()
self.cur = self.conn.cursor()
checked = self.check_account()
if checked:
self.login()
else:
self.register()
print("You have successfully registered and received $1000 as a gift!")
self.cur.execute(
"SELECT ID, budget FROM users WHERE email=%s", (self.email,)
)
sql_id_budget = self.cur.fetchone()
self.sql_id = sql_id_budget[0]
self.budget = sql_id_budget[1]
def display_top(self):
self.cur.execute("SELECT email, budget FROM users ORDER BY budget DESC")
top = self.cur.fetchall()
places = range(1, len(top) + 1)
for (a, b), i in zip(top, places):
print(f"{i}. {a} - ${b}")
def update_budget(self):
self.cur.execute(
"UPDATE users SET budget=%s WHERE id=%s", (self.budget, self.sql_id)
)
self.conn.commit()
@lock
class Game:
player: Player
dealer: Dealer = attr.ib(factory=Dealer)
def reset_attributes(self):
self.player.hand.cards = []
self.player.state = State.IDLE
self.dealer.hand.cards = []
self.dealer.state = State.IDLE
self.dealer.shoe = Shoe()
def open(self):
self.player.player_bet()
self.dealer.shoe.shuffle()
c1 = self.dealer.draw_card()
c2 = self.dealer.draw_card()
self.player.hand = Hand([c1, c2])
self.player.update() # Update player state
# The dealer is the last one to get cards
c1 = self.dealer.draw_card()
c2 = self.dealer.draw_card()
self.dealer.hand = Hand([c1, c2])
self.dealer.update()
self.display_info()
def is_finished(self):
if self.dealer.hand.score() >= 21:
return True
if self.player.is_busted() or self.player.is_standing():
return True
""" Pay/charge the player according to cards result
Reset hands, states, shoe
"""
def close(self):
dealer_score = self.dealer.hand.score()
if not self.player.is_busted():
if self.dealer.state == State.BUST:
self.player.budget += self.player.bet * 2
else:
if self.player.hand.score() < dealer_score:
self.player.budget -= self.player.bet
elif self.player.hand.score() > dealer_score:
self.player.budget += self.player.bet * 2
else:
self.player.budget -= self.player.bet
self.display_info()
def run(self):
# Run a full game, from open() to close()
self.open()
# If the dealer has a blackjack, close the game
if self.is_finished():
self.close()
return
# The dealer deals with the player
self.dealer.deal(self.player, self)
# Now the dealer's turn to play ...
while True:
self.dealer.play()
if self.dealer.is_busted() or self.dealer.is_standing():
break
self.close()
def display_info(self):
clear_console()
print(f"{self.player}\n")
print(f"{self.dealer.display_cards(self.player, self)}\n")
player_score = self.player.hand.score()
dealer_score = self.dealer.hand.score()
if player_score == 21:
print("Blackjack! You won!")
elif dealer_score == 21:
print("Dealer has got a blackjack. You lost!")
elif self.player.is_busted():
print("Busted! You lost!")
elif self.player.is_standing():
if self.dealer.is_busted():
print("Dealer busted! You won!")
elif player_score > dealer_score:
print("You beat the dealer! You won!")
elif player_score < dealer_score:
print("Dealer has beaten you. You lost!")
else:
print("Push. Nobody wins or losses.")
def main():
database = Database()
database.initialize()
if start_choice():
player = Player(database.budget)
game = Game(player)
playing = True
while playing:
game.run()
database.budget = player.budget
database.update_budget()
playing = ask_question("\nDo you want to play again")
if playing:
game.reset_attributes()
else:
database.cur.close()
else:
database.display_top()
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>Here are a few things that caught my eye while quickly looking through your code:</p>\n\n<hr>\n\n<h2>Imports</h2>\n\n<p>As per the official Style Guide for Python Code (aka PEP8), <code>import</code>s <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">should best be grouped</a>. Imports from the standard library come first, then third-party modules, followed by any library/application specific imports. The groups should be seperated by blank lines. In your particular case, that might look like this:</p>\n\n<pre><code>import os\nimport random\nimport typing as t\nfrom enum import Enum\nfrom functools import partial\nfrom getpass import getpass\nfrom re import match\n\nimport attr\nimport bcrypt\nimport psycopg2\n</code></pre>\n\n<p>The order of the imports has also changed slightly. That's because I left grouping and sorting the imports to the according function of Visual Studio Code, which under the hood uses <a href=\"https://pypi.org/project/isort/\" rel=\"nofollow noreferrer\">isort</a> to automate the process.</p>\n\n<h2>Documentation</h2>\n\n<p>There are a few loose text blocks, that are likely meant to be seen as method documentation. I'm talking about the triple-quoted text above <code>Player.update</code> as well as <code>Dealer.deal</code> and <code>Game.close</code>. To really work as a documentation string, they should be placed properly indented inside the function body like so:</p>\n\n<pre><code>def update(self):\n \"\"\" Update self.state after self.hit\n\n If player busted, self.state = State.BUST, etc.\n \"\"\"\n ...\n</code></pre>\n\n<pre><code>def deal(self, player, game):\n \"\"\" In this method, the dealer and player enter a loop in which the \n player gets a card from the dealer until it stands or busts.\n \"\"\"\n ...\n</code></pre>\n\n<p>These now follow the <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">style guide recommendations on how to write proper docstrings</a>. Python's <code>help(...)</code> as well as most Python IDEs will now easily pick it up to help you out.</p>\n\n<p>In general, you should think about adding more documentation to your code. Often just a one-line description is sufficient to describe what the function is supposed to do. If there is more to say, say more. If you ever came back to your code after a longer pause, future-you will be really really grateful for the extra effort you spent back then.</p>\n\n<h2>Building the deck</h2>\n\n<p><code>build_deck</code> uses a double list comprehension to generate all possible combinations of values and suits. This function can also be rewritten using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a>:</p>\n\n<pre><code>from itertools import product\n\ndef build_deck():\n suits = (\"Hearts\", \"Clubs\", \"Diamonds\", \"Spades\")\n values = (\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\", \"A\")\n return [Card(value, suit) for value, suit in product(values, suits)]\n</code></pre>\n\n<p>It doesn't make a huge difference here, but it's always good to now about <code>itertools</code>, especially if you ever find yourself in a situation where you'd have to combine more than two or three iterables. I also changed <code>suits</code> and <code>values</code> to be tuples instead of lists, which is IMHO a nice way to express that you don't want to modify them, because <a href=\"https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences\" rel=\"nofollow noreferrer\"><code>tuple</code>s are immutable</a>.</p>\n\n<h2>Whatever <em>lock</em> is</h2>\n\n<p>You define <code>lock</code> to be a partial version of <code>attr.s</code>, but I'm not entirely sure if <code>lock</code> is a particularly good name for it. As I usually don't work with the <code>attr</code> module it could be just me, but at the moment, <code>lock</code> does not really seem to fit here. IMHO the name strongly hints towards authentication, but does not do anything in that regard if I'm not totally mistaken.</p>\n\n<h2><em>ask_question</em></h2>\n\n<p><code>casefold()</code> does seem to be a little bit \"overpowered\" here. A simple <code>lower()</code> would suffice and be less suprising to us mere mortal Python programmers out here looking at your code ;-)</p>\n\n<h2><em>Card.score</em></h2>\n\n<p><code>Card.score</code> breaks the pattern of listing all the elements you are willing to accept explicitly and give them all as a single string instead. I don't have strong arguments why you should or should not use either of those, but it's probably best to stick to one of them. Personally, I prefer the tuple version.</p>\n\n<h2>Credentials in code</h2>\n\n<p>Your <code>Database</code> class has all the database credentials hard-coded. That's usually not a great idea for several reasons. The first one is that if you ever push your code to a public repository (or Code Review), your credentials will also be public. That's usually not what you want. If you now think, that you will remember to remove them before doing that: You won't! The second one is that if you ever decided to change them or give the game code to someone else, you or, even worse they, will have to touch the code. </p>\n\n<p>There are also several ways on how to improve this, where I think putting the credentials in environment variables or an external configuration file are the most commonly used ones. The first variant might look like this:</p>\n\n<pre><code>conn: t.Any = attr.ib(default=psycopg2.connect(dbname=os.environ[\"BLACKJACK_DB_NAME\"],\n user=os.environ[\"BLACKJACK_DB_USER\"],\n password=os.environ[\"BLACKJACK_DB_PASS\"],\n host=os.environ[\"BLACKJACK_DB_HOST\"]))\n</code></pre>\n\n<hr>\n\n<p>That's it for now. Maybe I will find the time to extend the answer in a few days. Till then: Happy coding and good luck with the reviews!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T22:40:16.347",
"Id": "436604",
"Score": "0",
"body": "Hey, thank you for the tips, can't wait to see the extended answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T21:52:00.297",
"Id": "437624",
"Score": "0",
"body": "I awarded you, but I still hope you'll make that extended answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T22:29:03.610",
"Id": "224997",
"ParentId": "224561",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224997",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:06:53.710",
"Id": "224561",
"Score": "6",
"Tags": [
"python",
"object-oriented",
"sql",
"playing-cards",
"postgresql"
],
"Title": "OOP Python Blackjack game with player accounts in PostgreSQL"
}
|
224561
|
<p>Coming from a software engineering background I don't have so much experience developing games. Below is a simple 2d tile connect game.
What would people improve about it? What are some good practices that could be applied here and what would people suggest?</p>
<p><strong>Board.cs</strong> - main script that handles setting up and resetting the board.</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Board : MonoBehaviour {
// Board Lengths by Cells
public int width;
public int height;
public GameObject[] tilePrefabs; // array of different tiles which may be used (different colours)
public GameObject[,] allTiles; // a 2d array of all the tiles on the board
private TileAnimations tileAnimations;
// Use this for initialization
void Start () {
tileAnimations = this.GetComponent<TileAnimations>();
allTiles = new GameObject[width, height];
Setup ();
}
// Generate board of random tiles
private void Setup (){
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
Vector2 tempPosition = new Vector2(i, j);
// Create tiles
int tileToUse = Random.Range(0, tilePrefabs.Length);
GameObject tile = Instantiate(tilePrefabs[tileToUse], tempPosition, Quaternion.identity);
tile.transform.parent = this.transform;
tile.name = "(" + i + ", " + j + ")";
// Add tile to tiles array
allTiles[i, j] = tile;
}
}
//bool deadlock = this.GetComponent<DeadlockChecker>().CheckDeadlock();
}
// check for null spaces and populate them
public IEnumerator CollapseColumnCo(){
int nullCount = 0;
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
if(allTiles[i,j] == null){ // when you create a chain, there will be null spaces on the board (since the tiles disappear)
nullCount++;
}
else if (nullCount > 0){
allTiles[i, j].GetComponent<Tile>().tileY -= nullCount;
StartCoroutine(tileAnimations.SlideDown(allTiles[i,j], nullCount)); // slide down tiles above null spaces
allTiles[i, j - nullCount] = allTiles[i, j]; // update position in allTiles
allTiles[i, j] = null;
}
}
nullCount = 0;
}
yield return new WaitForSeconds(.3f);
StartCoroutine(FillBoardCo()); // refills board
}
private void RefillBoard() {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (allTiles[i, j] == null) {
Vector2 tempPosition = new Vector2(i, j);
int tileToUse = Random.Range(0, tilePrefabs.Length);
GameObject piece = Instantiate(tilePrefabs[tileToUse], tempPosition, Quaternion.identity);
piece.transform.localScale = new Vector3(0f, 0f, 0);
StartCoroutine(tileAnimations.ScaleTile(piece, "expand"));
allTiles[i, j] = piece;
}
}
}
//bool deadlock = this.GetComponent<DeadlockChecker>().CheckDeadlock();
}
private IEnumerator FillBoardCo() {
RefillBoard();
yield return new WaitForSeconds(.3f);
}
}
</code></pre>
<p><strong>Link.cs</strong> - state of a chain</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Link : MonoBehaviour
{
private Vector2 touchPosition;
public List<GameObject> chain = new List<GameObject>();
public GameObject chainHead;
private Board board;
private TileAnimations tileAnimations;
public bool chaining = false; // is the player in the middle of creating a chain?
// Start is called before the first frame update
void Start(){
board = FindObjectOfType<Board>();
tileAnimations = this.GetComponent<TileAnimations>();
}
// Update is called once per frame
void Update(){
}
// Pops tiles when chain is destroyed
public void DestroyChain(List<GameObject> linkedChain){
StartCoroutine(tileAnimations.PopIt(linkedChain));
}
}
</code></pre>
<p><strong>Tile.cs</strong></p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour
{
public int tileX;
public int tileY;
private Board board;
public bool inChain = false;
// Start is called before the first frame update
void Start(){
board = FindObjectOfType<Board>();
tileX = (int)transform.position.x; // column number
tileY = (int)transform.position.y; // row number
}
// Update is called once per frame
void Update() {
if (inChain == true) {
this.gameObject.transform.localScale = new Vector3(1.5f, 1.5f, 0);
} else {
this.gameObject.transform.localScale = new Vector3(1.0f, 1.0f, 0);
}
}
// Checks adjacency so you can only make chains with tiles which are next to each other
public bool IsAdjacentToHead() {
// if on left of head
if (tileX == (board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileX - 1)
&& tileY == board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileY) {
return true;
} else if (tileX == (board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileX + 1)
&& tileY == board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileY) {
// if on right of head
return true;
} else if (tileX == (board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileX)
&& tileY == (board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileY + 1)) {
// if on top of head
return true;
} else if (tileX == (board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileX)
&& tileY == (board.GetComponent<Link>().chainHead.GetComponent<Tile>().tileY - 1)) {
// if on bottom of head
return true;
} else {
return false;
}
}
private void OnMouseDown(){
board.GetComponent<Link>().chaining = true;
inChain = true;
board.GetComponent<Link>().chainHead = this.gameObject;
board.GetComponent<Link>().chain.Add(this.gameObject);
}
private void OnMouseUp(){
board.GetComponent<Link>().chaining = false;
if (board.GetComponent<Link>().chain.Count >= 3){
board.GetComponent<Link>().DestroyChain(board.GetComponent<Link>().chain);
board.GetComponent<Link>().chain.Clear();
} else {
// Remove all from chain
foreach (GameObject x in board.GetComponent<Link>().chain){
x.GetComponent<Tile>().inChain = false;
}
board.GetComponent<Link>().chain.Clear();
}
}
private void OnMouseEnter(){
// Only if we are chaining AND the tile does not alread exist in the chain
if(board.GetComponent<Link>().chaining == true && !board.GetComponent<Link>().chain.Contains(gameObject)){
// Make sure the tile to be connected is adjacent to the head AND have same colour (tag)
if (IsAdjacentToHead() && this.CompareTag(board.GetComponent<Link>().chainHead.tag)) {
board.GetComponent<Link>().chain.Add(this.gameObject);
board.GetComponent<Link>().chainHead = this.gameObject;
inChain = true;
}
}
// If the next tile is the one previous in the chain (penultimate element) - remove last element
if (board.GetComponent<Link>().chaining == true) {
if (this.gameObject == board.GetComponent<Link>().chain[board.GetComponent<Link>().chain.Count - 2]) {
board.GetComponent<Link>().chainHead = this.gameObject;
// remove last element from chain
board.GetComponent<Link>().chain[board.GetComponent<Link>().chain.Count - 1].GetComponent<Tile>().inChain = false;
board.GetComponent<Link>().chain.RemoveAt(board.GetComponent<Link>().chain.Count-1);
}
}
}
}
</code></pre>
<p><strong>TileAnimation.cs</strong></p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public class TileAnimations : MonoBehaviour
{
public GameObject destroyEffect;
private Board board;
void Start() {
board = FindObjectOfType<Board>();
}
// After chain disappears, tiles above slide down
public IEnumerator SlideDown(GameObject tile, int nullCount) {
var originalPos = tile.transform.position;
var finalPos = tile.transform.position -= new Vector3(0, nullCount, 0);
float t = 0f;
float timeToMove = 0.2f;
while (t < 1) {
t += Time.deltaTime / timeToMove;
tile.transform.position = Vector3.Lerp(originalPos, finalPos, t);
yield return null;
}
}
// Destroy each tile with a delay
public IEnumerator PopIt(List<GameObject> linkedChain) {
float destroyDelay = 0.1f;
foreach (GameObject tile in linkedChain) {
int tileX = tile.GetComponent<Tile>().tileX;
int tileY = tile.GetComponent<Tile>().tileY;
StartCoroutine(PopOut(tile, destroyDelay));
board.allTiles[tileX, tileY] = null;
destroyDelay += 0.1f;
}
yield return new WaitForSeconds((linkedChain.Count + 1f) * 0.1f);
StartCoroutine(board.CollapseColumnCo());
}
// Shrink tile down + Particle Effect
public IEnumerator PopOut(GameObject tile, float delay) {
yield return new WaitForSeconds(delay);
GameObject particle = Instantiate(destroyEffect, tile.transform.position, Quaternion.identity);
Destroy(particle, .6f);
StartCoroutine(ScaleTile(tile, "shrink"));
Destroy(tile,0.2f); // wait for shrink animation before destroying
}
public IEnumerator ScaleTile(GameObject tile, string action) {
var originalScale = tile.transform.localScale;
Vector3 finalScale = new Vector3(0f,0f,0f);
if (String.Equals(action, "shrink")) {
finalScale = new Vector3(0f, 0f, 0f);
} else if (String.Equals(action, "expand")) {
finalScale = new Vector3(1f, 1f, 1f);
} else {
Debug.LogError("Only expand and shrink actions can be used with ScaleTile script.");
}
float t = 0f;
float timeToMove = 0.2f;
while (t < 1) {
t += Time.deltaTime / timeToMove;
tile.transform.localScale = Vector3.Lerp(originalScale, finalScale, t);
yield return null;
}
yield return null;
}
}
</code></pre>
<p>Any tips/help/advice would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T18:49:54.847",
"Id": "435721",
"Score": "0",
"body": "Just curious--why did you remove the cool screen capture showing how the app works?"
}
] |
[
{
"body": "<p>I have some tips regarding C# conventions.</p>\n\n<ul>\n<li>Public fields should be replaced with public properties and should be title-cased. For insance <code>Board.width</code>, <code>Board.height</code>.</li>\n<li>Think about whether certain fields should be encapsulated within the instance and can only be mutated by methods on the instance. <code>Tile.tileX</code>, <code>Tile.tileY</code> are good candidates to encapsulate to avoid letting other classes changing these values out of bounds.</li>\n<li>Don't repeat class name in variable names. <code>Tile.tileX</code> should be called <code>Tile.X</code>.</li>\n<li>Use formatted string where possible: <code>$\"({i},{j})\"</code>. In this particular, case you could have used a <code>ValueTuple</code> <code>(i, j).ToString()</code> to get the same output.</li>\n<li>Be consistent with white space, parentheses: at one moment you have 3 consecutive methods with 3 different styles of white space <code>Setup (){</code>, <code>CollapseColumnCo(){</code>, <code>RefillBoard() {</code>.</li>\n<li>I don't get why you have an empty method <code>void Update(){</code> which is not an interface implementation.</li>\n<li>Some <em>if</em> statements could be replaced with ternary operators to avoid redundant code: see <code>this.gameObject.transform.localScale</code> in method <code>Update</code> and condition <code>inChain == true</code>.</li>\n<li>Conditions should not be checked against true/false: <code>if (inChain == true)</code> should be written as <code>if (inChain)</code>.</li>\n<li>Cache redundant calls in a local variable: <code>board.GetComponent<Link>().chainHead.GetComponent<Tile>()</code> should be cachec before all the <code>if</code> statements in <code>IsAdjacentToHead</code>.</li>\n<li>Some of your loops could be refactored to use LINQ: <code>foreach (GameObject x in board.GetComponent<Link>().chain)</code> <code>x.GetComponent<Tile>().inChain = false;</code>. See <code>IList<T>.ForEach(Action<T> action)</code> extension method.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:21:31.660",
"Id": "224573",
"ParentId": "224564",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T14:59:58.153",
"Id": "224564",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Tiles Game Best Practices"
}
|
224564
|
<p>I am writing a bootloader that needs to load a file from a FAT32 filesytem. Since I need to load both the root directory first to find the start of the file, and then the actual file, I wrote a function to load a sequence of clusters from the disk to 0x8000 in memory (since the bootloader is loaded from 0x7C00-0x7DFF and I use 0x7E00-0x7FFF to load sections of the FAT).</p>
<pre class="lang-lisp prettyprint-override"><code>loadClusterChain: ; ARGS: eax = first cluster number
pusha
; Set the memory location to load the file to 0x8000
mov dx, 0x8000
loadClusterChainLoop:
; Store the cluster number (eax) and additional offset (dx) for later
push dx
push eax
; Update the disk address packet
mov word [dapDataOffset], dx
; Account for the cluster numbers being shifted by 2
sub eax, 2
; Calculate how many sectors the cluster is from the start of the data area
xor ebx, ebx
mov bl, byte [bpbSectorsPerCluster]
mul ebx
; Add the start of data area to the root directory offset
add eax, dword [diskDataAreaStart]
; Update the disk address packet start sector
mov dword [dapStartSector], eax
; Update the disk address packet sector count
push eax
xor ax, ax
mov al, byte [bpbSectorsPerCluster]
mov word [dapSectorCount], ax
pop eax
; Load the file cluster
mov ah, 0x42
mov dl, byte [bpbDriveNumber]
mov si, diskAddressPacket
int 0x13
jc diskError
; Retrieve the value of eax but keep it in the stack
pop eax
push eax
; Divide by 128 to calculate the FAT sector to load
shr eax, 7
; Get the number of reserved sectors
xor ebx, ebx
mov bx, word [bpbReservedSectors]
; Add the reserved sectors to the FAT sector, so eax = relevant FAT sector
add eax, ebx
; Update the disk address packet start sector
mov dword [dapStartSector], eax
; Update the disk address packet sector count
mov word [dapSectorCount], 1
; Update the disk address packet data offset to load the fat to 0x7E00
mov word [dapDataOffset], 0x7E00
; Load the FAT sector
mov ah, 0x42
mov dl, byte [bpbDriveNumber]
mov si, diskAddressPacket
int 0x13
jc diskError
; Get the offset of clusters into the FAT sector by getting the remainder when divided by 128
pop eax
and ax, 0x007F
; Multiply offset by 4 to get it in bytes
shl ax, 2
; Calculate the memory address of the cluster in the FAT
add ax, 0x7E00
; Read cluster value
mov bx, ax
mov eax, dword [bx]
; Set bx = 512*bpbSectorsPerCluster
xor bx, bx
mov bl, byte [bpbSectorsPerCluster]
shl bx, 9
; Restore the value of dx and add bx to move dx to the memory location of the end of the file parts loaded so far
pop dx
add dx, bx
; See if this is the end of the chain
cmp eax, 0x0FFFFFFF
jne loadClusterChainLoop
; Ensure the file ends with 0, so when scanning the root entries we will definitely stop
mov bx, dx
mov [bx], byte 0
popa
ret
</code></pre>
<p>Here are some of the variables used. <code>diskDataAreaStart</code> is not 0 when the code runs as the actual value is calculated before the function is called. The other variable names are mostly self-explanatory.</p>
<pre><code>diskDataAreaStart dd 0
diskAddressPacket:
dapSize db 0x10
dapReserved db 0x00
dapSectorCount dw 0
dapDataOffset dw 0
dapDataSegment dw 0
dapStartSector dq 0
</code></pre>
<p>I know it's a fairly niche piece of code, but I would be very grateful if someone could give me feedback on it - if I could do something more efficiently or even feedback on how clear my comments were and how easy the code was to follow along would be highly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-17T14:02:06.380",
"Id": "439733",
"Score": "0",
"body": "You're actually using 386+ instructions and registers, albeit in Real 86 Mode. So although the default bitness of your CS is 16, you use 32-bit code."
}
] |
[
{
"body": "\n\n<h2>Style</h2>\n\n<blockquote>\n <p>feedback on how clear my comments were and how easy the code was to follow</p>\n</blockquote>\n\n<p>I'm not a big fan of <em>line comments</em>. I think they make the code a bit harder to follow. That's why I prefer <em>tail comments</em> along with a nice tabular layout of the labels, instructions, operands, and tail comments.<br>\nAnd of course don't write redundant comments like \"Update the disk address packet sector count\" when looking at the names of the identifiers already tells what is happening.</p>\n\n<p>You've got some pushes and pops that are fairly distant apart. If you would number these (or tag them somehow), verifying what the stack holds and whether the stack was correctly balanced becomes a bit easier.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>push dx ; (1)\npush eax ; (2)\n\n...\n\npush ax ; (3)\nmovzx ax, byte [bpbSectorsPerCluster]\nmov [dapSectorCount], ax\npop ax ; (3)\n\n...\n\npop eax ; -(2)-\npush eax ; -(2)-\n\n...\n\npop eax ; (2)\n\n...\n\npop dx ; (1)\n</code></pre>\n\n<h2>Optimizations</h2>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov word [dapDataOffset], dx\n</code></pre>\n</blockquote>\n\n<p>Most assemblers will not require you to write this <code>word</code> size tag because the use of the <code>DX</code> register made already clear that this has to be a word-sized operation. Not writing the redundant size tag makes your code a bit clearer.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mov [dapDataOffset], dx\n</code></pre>\n\n<p>You did this several times.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>xor ebx, ebx\nmov bl, byte [bpbSectorsPerCluster]\n</code></pre>\n</blockquote>\n\n<p>The instruction set has the <code>MOVZX</code> instruction for this kind of situations. It will also reduce the code's footprint which is important in a bootloader that is limited to just 512 bytes. Notice that here the <code>byte</code> size tag is required.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>movzx ebx, byte [bpbSectorsPerCluster]\n</code></pre>\n\n<p>You did this several times.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>push eax\nxor ax, ax\nmov al, byte [bpbSectorsPerCluster]\nmov word [dapSectorCount], ax\npop eax\n</code></pre>\n</blockquote>\n\n<p>Pushing and popping the 32-bit register <code>EAX</code> from real address mode uses an operand size prefix. In this case the high word was never changed and so you can shave off 2 bytes if you only push/pop <code>AX</code>. </p>\n\n<p>Better still, the program doesn't need you to preserve <code>AX</code> at this point. Again 2 bytes less.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>movzx ax, byte [bpbSectorsPerCluster]\nmov [dapSectorCount], ax\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>pop eax\nand ax, 0x007F\n\n; Multiply offset by 4 to get it in bytes\nshl ax, 2\n\n; Calculate the memory address of the cluster in the FAT\nadd ax, 0x7E00\n\n; Read cluster value\nmov bx, ax\nmov eax, dword [bx]\n</code></pre>\n</blockquote>\n\n<p>Here's another opportunity to shave off a byte. Pop the value directly in the register that you'll use to retrieve the cluster number: </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>pop ebx\nand bx, 0x7F\nshl bx, 2 ; Multiply offset by 4 to get it in bytes\nadd bx, 0x7E00 ; Calculate the memory address of the cluster in the FAT\nmov eax, [bx] ; Read cluster value\n</code></pre>\n\n<p>Exactly the same length but less instructions:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>pop ebx\nand ebx, 0x7F\nmov eax, [ebx*4 + 0x00007E00] ; Read cluster value\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>; Update the disk address packet sector count\nmov word [dapSectorCount], 1\n\n; Update the disk address packet data offset to load the fat to 0x7E00\nmov word [dapDataOffset], 0x7E00\n</code></pre>\n</blockquote>\n\n<p>The above instructions total 12 bytes. Because <em>dapSectorCount</em> and <em>dapDataOffset</em> follow each other in memory, you can combine the writes. The total then becomes 9 bytes.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; Update dapSectorCount=1 and dapDataOffset=0x7E00 together\nmov dword [dapSectorCount], 0x7E000001\n</code></pre>\n\n<p>This last optimization is of course killing readability in favor of code size. Your choice!</p>\n\n<h2>Beware</h2>\n\n<p>Your <em>loadClusterChain</em> routine uses some 32-bit registers. Given that this is 16-bit code the <code>pusha</code> and <code>popa</code> instructions will not preserve the high words. Maybe this can become a problem for the rest of your program!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:44:25.653",
"Id": "435841",
"Score": "1",
"body": "Wow - thank you so much for taking the time to write this! Very informative & I really appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:17:13.287",
"Id": "224674",
"ParentId": "224565",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "224674",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:00:24.317",
"Id": "224565",
"Score": "14",
"Tags": [
"file-system",
"assembly",
"x86"
],
"Title": "Loading a file from a FAT32 filesystem in 16 bit real mode on x86 (Intel syntax assembly)"
}
|
224565
|
<p>My Android app must request my Cloud Functions server to create in-app products at runtime ; then, the server responds with the created one-time product. I've written the server Cloud Function that creates the product. Here is how it works (<strong>full minimal, executable code is embedded at the end of the question</strong>):</p>
<ul>
<li><p>My function uses JavaScript, Node.JS (notable modules: request, uuid/v4), firebase-functions, firebase-admin, admin.firestore()</p></li>
<li><p>It checks that the Android app's user is allowed to request my server to create an in-app product, <em>i.e.</em> if the user exists and has the adequat rights</p>
<ul>
<li>(Note that I use Firebase Auth, and Firebase Firestore with Security Rules defined and enabled) </li>
</ul></li>
</ul>
<p>`</p>
<pre><code>if(!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
}
admin_firestore.collection('users').document(context.auth.uid).get().then(documentSnapshot => { // Is the client allowed to ask for the creation of a managed product?
if(!documentSnapshot.exists) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called with an existing account.');
}
if(documentSnapshot.getString('app') != 'main') {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated with your main account.');
}
if(documentSnapshot.getBoolean('deleted')) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated with an undeleted main account.');
}
</code></pre>
<p>`</p>
<ul>
<li>It checks that the in-app product can be created, <em>i.e.</em> if it does not already exist</li>
</ul>
<p>` </p>
<pre><code>request.get({url: remote_url}, function(error, response, body) { // Does a managed product with this SKU already exist? (querying Google Play Developer API Inapproducts.get)
if(error) {
throw new functions.https.HttpsError('unknown', error);
}
if(response.statusCode == 200) {
throw new functions.https.HttpsError('already-exists', 'A managed product with the SKU I\'ve generated myself already exists. You should query me again.');
}
if(response.statusCode != 404) {
throw new functions.https.HttpsError('unkown', 'Something went wrong. Status code : ' + response.statusCode + '.');
}
</code></pre>
<p>`</p>
<ul>
<li>It generates the required in-app product's details throughout the function (depending on the previous checks)</li>
</ul>
<p>`</p>
<pre><code>const managed_product_details = { // See https://developers.google.com/android-publisher/api-ref/inappproducts#resource
packageName: package_name,
sku: sku,
status: status,
purchaseType: purchase_type,
defaultPrice: {
currency: currency,
priceMicros: price_micros
},
listings: {
'en-US': {
title: title,
description: description
}
},
defaultLanguage: default_language
};
</code></pre>
<p>`</p>
<ul>
<li>It inserts (<em>i.e.</em> creates) the in-app product, providing Google Cloud Billing these details</li>
</ul>
<p>`</p>
<pre><code>request.post({url: remote_url, json: managed_product_details}, function(error, response, body) { // Creating the managed product (querying Google Play
// Developer API Inapproducts.insert)
if(error) {
throw new functions.https.HttpsError('unknown', error);
}
if(response.statusCode != 200) {
throw new functions.https.HttpsError('unkown', 'Something went wrong. Status code : ' + response.statusCode + '.');
}
const json_managed_product = body; // See https://developers.google.com/android-publisher/api-ref/inappproducts/insert
return json_managed_product;
});
</code></pre>
<p>`</p>
<p><strong>I am asking for a review that covers these three points:</strong></p>
<ol>
<li><p>Error-handling.</p>
<ul>
<li>In the <code>request.get</code> callbacks, I check if an <code>error</code> occurred (<code>request.get({url: remote_url}, function(error, response, body) { if (error) { throw new functions.https.HttpsError('unknown', error); } }</code>) . I didn't find anything more pertinent than the code <code>unkown</code> (see <a href="https://firebase.google.com/docs/reference/functions/functions.https.HttpsError" rel="nofollow noreferrer">https://firebase.google.com/docs/reference/functions/functions.https.HttpsError</a>) . Is it a good practice to throw <code>unkown</code> with the <code>error</code> sent by <code>request</code>?</li>
<li><p>The previous link is the Google doc about <code>HttpsError</code>. It says:</p>
<blockquote>
<p>Make sure to throw this exception at the top level of your function and not from within a callback, as that will not necessarily terminate the function with this exception.</p>
</blockquote></li>
<li><p>So do you know if it's good to <code>throw new HttpsError(code, my_message)</code> within the <code>request</code> and <code>admin-firestore</code> callbacks as it's done, for the moment?</p></li>
</ul></li>
<li><p>Security</p>
<ul>
<li>I don't really have precise questions about security. Do you think my function is unsecure and if yes, why? Concerning the network: normally, Android apps communicate with Cloud Functions servers in HTTPS so data are encrypted (because app would use the Firebase Functions SDK's <code>getHttpsCallable()</code> method).</li>
</ul></li>
<li><p>Asynchronous</p>
<ul>
<li>Since I use <code>request</code>, I use callbacks: do you think there are cases for which my function won't completely be executed (<em>e.g.</em> errors not thrown, code sections that should be executed but they are not, etc.) ?</li>
</ul></li>
</ol>
<h1>Full, minimal, executable code</h1>
<p><strong>To execute it:</strong> deploy this Cloud Function, then <em>e.g.</em> use your Android app's Firebase Functions client SDK to request the Cloud Functions server (that's off-topic, so please see <a href="https://firebase.google.com/docs/functions/callable" rel="nofollow noreferrer">https://firebase.google.com/docs/functions/callable</a> :) )</p>
<pre><code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
const uuidv4 = require('uuid/v4');
/**
* Creates a managed product (either a SEAL, or a slot).
* Call it at runtime in an Android application, e.g. using Firebase Functions' SDK.
* @param type the type of the managed product (either "seal", or "slot")
* @response json_managed_product the created (inserted) one-time managed product
*
* WORKFLOW OVERVIEW
* 1. Generates the following managed product's features:
* - SKU (built on the parametrized type)
* - package_name (constant)
* - title (built on parametrized type)
* - description (built on parametrized type)
* - currency (constant)
* - price_micros (constant)
* - status (constant)
* - purchase_type (constant)
* - default_language (constant)
* NB: the generation of these features is stopped whether a managed product with the parametrized SKU already exists (see 2.).
*
* 2. Checks that a managed product with the parametrized SKU does not already exist.
* 2.1. true: the server sends an error and stops.
* 2.2. false: the server continues the generation of the managed product's features and its creation.
*
* 3. The server creates (inserts) the managed product in Firebase.
* 3.1. error: the server sends an error and stops.
* 3.2. success: the server sends the generated SKU
*/
exports.createManagedProduct = functions.https.onRequest(async(req, res) => {
if(!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
}
const admin_firestore = admin.firestore();
const type = req.query.type;
const uuid_with_underscores_only = uuidv4().split('-').join('_');
const sku = type + '_' + uuid_with_underscores_only;
const package_name = 'com.XXX';
const remote_url = 'https://www.googleapis.com/androidpublisher/v3/applications/' + package_name + '/inappproducts/' + sku;
admin_firestore.collection('users').document(context.auth.uid).get().then(documentSnapshot => { // Is the client allowed to ask for the creation of a managed product?
if(!documentSnapshot.exists) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called with an existing account.');
}
if(documentSnapshot.getString('app') != 'main') {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated with your main account.');
}
if(documentSnapshot.getBoolean('deleted')) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated with an undeleted main account.');
}
const allowed_types = ['seal', 'slot'];
if(!allowed_types.includes(type)) {
throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an allowed type of managed product.');
}
request.get({url: remote_url}, function(error, response, body) { // Does a managed product with this SKU already exist? (querying Google Play Developer API Inapproducts.get)
if(error) {
throw new functions.https.HttpsError('unknown', error);
}
if(response.statusCode == 200) {
throw new functions.https.HttpsError('already-exists', 'A managed product with the SKU I\'ve generated myself already exists. You should query me again.');
}
if(response.statusCode != 404) {
throw new functions.https.HttpsError('unkown', 'Something went wrong. Status code : ' + response.statusCode + '.');
}
let title = 'A ';
let description = '';
switch(type) {
case 'seal':
const upper_cased_title = type.toUpperCase();
title += upper_cased_title;
description = 'Contains the slots in which your Instagram publications will be placed.';
break;
case 'slot':
title += type;
description = 'Contains your Instagram publication.';
break;
}
const currency = 'EUR';
const price_micros = 40e6;
const status = 'active';
const purchase_type = 'managedUser';
const default_language = 'en-US';
const managed_product_details = { // See https://developers.google.com/android-publisher/api-ref/inappproducts#resource
packageName: package_name,
sku: sku,
status: status,
purchaseType: purchase_type,
defaultPrice: {
currency: currency,
priceMicros: price_micros
},
listings: {
'en-US': {
title: title,
description: description
}
},
defaultLanguage: default_language
};
const remote_url = 'https://www.googleapis.com/androidpublisher/v3/applications/' + package_name + '/inappproducts';
request.post({url: remote_url, json: managed_product_details}, function(error, response, body) { // Creating the managed product (querying Google Play
// Developer API Inapproducts.insert)
if(error) {
throw new functions.https.HttpsError('unknown', error);
}
if(response.statusCode != 200) {
throw new functions.https.HttpsError('unkown', 'Something went wrong. Status code : ' + response.statusCode + '.');
}
const json_managed_product = body; // See https://developers.google.com/android-publisher/api-ref/inappproducts/insert
return json_managed_product;
});
});
});
});
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T15:47:01.000",
"Id": "224568",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"android",
"e-commerce",
"firebase"
],
"Title": "Google Play billing + Firebase functions: Creating a one-time product, server-side"
}
|
224568
|
<p>This is my first experience of designing classes with inheritance. I would like to get feedback on the interaction between the presented classes. It is unlikely that this code will seem complicated. But if you need a description of it, please specify in the comments.</p>
<p>There are several classes that describe the <code>model</code>.</p>
<ul>
<li><code>ToolStripUI</code> Сontains properties for configuring the UI.</li>
<li><code>SearchArgs</code> Inherited from <code>EventArgs</code>. Required to pass data to the search method.</li>
<li><code>PagedModelBase<T></code> It is necessary to implement the output of data on the page.</li>
<li><code>SearchModel<T></code> Extension for <code>PagedModelBase</code> in the search part.</li>
<li><code>TableModel<T></code> Extension for <code>PagedModelBase</code> in normal mode. Forces the <code>Find()</code> and <code>Delete()</code> methods to be implemented.</li>
</ul>
<p>They are used to create two models: <code>Contract</code> and <code>Worker</code>. They inherit <code>TableModel</code>. And each has a inner class <code>SearchModel</code> that inherits <code>SearchModel<T></code>.</p>
<p>A change in the <code>PagedModelBase<T></code> properties causes a change in <code>ToolStripUI</code>. Thus, <code>ToolStripUI</code> always contains relevant data for UI.</p>
<p>The following code shows how the <code>Contract model</code> methods are used.</p>
<pre><code>private void OnButtonToolStripClick(object sender, TSButton btn)
{
switch (form.CurrentTable)
{
case TableName.CONTRACT:
if (model.GetContractModel.GetSearch.IsSearch)
{
SearchTableContract(btn);
}
else
{
TableContract(btn);
}
break;
case TableName.WORKER:
if (model.GetWorkerModel.GetSearch.IsSearch)
{
SearchTableWorker(btn);
}
else
{
TableWorker(btn);
}
break;
}
}
private void SearchTableContract(TSButton btn)
{
List<ContractTableRow> list;
ToolStripUI ui;
switch (btn)
{
case TSButton.SEARCH:
list = model.GetContractModel.Find(form.GetSearchItem());
break;
case TSButton.RESET:
list = model.GetContractModel.ReloadPage();
break;
case TSButton.FIRST:
list = model.GetContractModel.GetSearch.FirstPage();
break;
case TSButton.LAST:
list = model.GetContractModel.GetSearch.LastPage();
break;
case TSButton.NEXT:
list = model.GetContractModel.GetSearch.NextPage();
break;
case TSButton.PREVIOUS:
list = model.GetContractModel.GetSearch.PreviousPage();
break;
default:
list = null;
break;
}
if (btn == TSButton.RESET)
{
ui = model.GetContractModel;
}
else
{
ui = model.GetContractModel.GetSearch;
}
if (list.Count > 0)
{
contractUC.FillPage(list);
form.SetToolStipUI(ui);
}
else
{
ShowMessage.Information("Не найдено");
}
}
private void TableContract(TSButton btn)
{
List<ContractTableRow> list;
ToolStripUI ui;
switch (btn)
{
case TSButton.SEARCH:
list = model.GetContractModel.Find(form.GetSearchItem());
break;
case TSButton.RESET:
list = model.GetContractModel.ReloadPage();
break;
case TSButton.FIRST:
list = model.GetContractModel.FirstPage();
break;
case TSButton.LAST:
list = model.GetContractModel.LastPage();
break;
case TSButton.NEXT:
list = model.GetContractModel.NextPage();
break;
case TSButton.PREVIOUS:
list = model.GetContractModel.PreviousPage();
break;
default:
list = null;
break;
}
if (btn == TSButton.SEARCH)
{
ui = model.GetContractModel.GetSearch;
}
else
{
ui = model.GetContractModel;
}
contractUC.FillPage(list);
form.SetToolStipUI(ui);
}
</code></pre>
<p>And the full code of all described classes. Perhaps more convenient to watch via <a href="https://github.com/c0rkin/StackShare/blob/master/CCC_MainModel.cs" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code>public ContractModel GetContractModel { get; private set; }
public WorkerModel GetWorkerModel { get; private set; }
public MainModel()
{
GetContractModel = new ContractModel();
GetWorkerModel = new WorkerModel();
}
public class ContractModel : TableModel<ContractTableRow>
{
internal SearchModel GetSearch { get; set; }
public ContractModel()
{
Size = Properties.Settings.Default.TableContractSize;
GetSearch = new SearchModel();
}
internal override bool Delete(int id)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
bool result = true;
try
{
using (ModelContext model = new ModelContext())
{
Contracts c = model.Contracts.Single(x => x.Id == id);
model.Remove(c);
model.SaveChanges();
}
Count--;
}
catch (Exception ex)
{
result = false;
ShowMessage.Error(string.Format(
"Во время удаления договора из базы данных произошла ошибка. ID договора: {0}\n\n{1} {2}",
id, ex.Message, ex.InnerException.Message), "Исключение - MainModel.DeleteContract");
}
stopwatch.Stop();
logger.Debug("DeleteContract(): {0}", stopwatch.Elapsed);
return result;
}
internal override List<ContractTableRow> LoadPage()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<ContractTableRow> source = null;
try
{
using (ModelContext model = new ModelContext())
{
Count = model.Contracts.Count();
IEnumerable<ContractTableRow> rows = model.Contracts
.OrderByDescending(r => r.Id)
.Skip(Page * Size)
.Take(Size)
.Select(c => new ContractTableRow
{
IdContract = c.Id,
Num = c.Num,
DateConclusion = c.DateConclusion.ToLongDateString(),
DateStartWork = c.DateStartWork.ToLongDateString(),
DateEndWork = c.DateEndWork.ToLongDateString(),
Salary = c.Salary,
Worker = new Item { Id = c.Worker, Value = c.WorkerNavigation.FullName },
KindWork = c.ListKindWorks.Select(y => new ItemLong { Id = y.IdKindWork, Title = y.IdKindWorkNavigation.Title, Short = y.IdKindWorkNavigation.Short }),
Subject = c.ListSubjects.Select(y => new ItemLong { Id = y.IdSubject, Title = y.IdSubjectNavigation.Title, Short = y.IdSubjectNavigation.Short })
});
source = rows.ToList();
}
}
catch (Exception ex)
{
source = null;
ShowMessage.Error(string.Format(
"Во время загрузки страницы с договорами произошла ошибка. Номер страницы: {0} (отсчет от {1})\n\n{2} {3}",
Page, MinPage, ex.Message, ex.InnerException.Message), "Исключение - MainModel.LoadPage");
}
stopwatch.Stop();
logger.Debug("Load page: {0}", stopwatch.Elapsed);
return source;
}
internal override List<ContractTableRow> Find(SearchArgs e)
{
return GetSearch.FirstPage(e);
}
internal override List<ContractTableRow> ReloadPage()
{
GetSearch.IsSearch = false;
return base.ReloadPage();
}
internal class SearchModel : SearchModel<ContractTableRow>
{
public SearchModel()
{
Size = Properties.Settings.Default.TableSearchSize;
ListTypeSearch = new List<ItemSearch>
{
new ItemSearch { Value = "Num", Display = "Номер" },
new ItemSearch { Value = "DateConclusion", Display = "Заключен" },
new ItemSearch { Value = "Worker", Display = "Работник [ФИО]" },
new ItemSearch { Value = "IdWorker", Display = "Работник [ID]"},
new ItemSearch { Value = "KindWork", Display = "Вид работы" },
new ItemSearch { Value = "Subject", Display = "Объект" },
new ItemSearch { Value = "DateStartWork", Display = "Начало" },
new ItemSearch { Value = "DateEndWork", Display = "Окончание" },
new ItemSearch { Value = "Salary", Display = "Зарплата" }
};
GetItemIdWorker = ListTypeSearch[3];
}
internal override List<ContractTableRow> LoadPage()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string pattern = GetPattern(GetArgs.IsExactMatch, GetArgs.Keyword);
List<ContractTableRow> list = null;
try
{
using (var model = new ModelContext())
{
IQueryable<Contracts> query = model.Contracts;
if (GetArgs.ItemSearch.Value == "Num")
{
query = query
.Where(c => EF.Functions.Like(c.Num, pattern))
.Order(c => c.Num, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "Salary")
{
query = query
.Where(c => EF.Functions.Like(c.Salary.ToString(), pattern))
.Order(c => c.Salary, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "DateConclusion")
{
query = query
.Where(c => EF.Functions.Like(c.DateConclusion.ToLongDateString(), pattern))
.Order(c => c.DateConclusion, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "DateStartWork")
{
query = query
.Where(c => EF.Functions.Like(c.DateStartWork.ToLongDateString(), pattern))
.Order(c => c.DateStartWork, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "DateEndWork")
{
query = query
.Where(c => EF.Functions.Like(c.DateEndWork.ToLongDateString(), pattern))
.Order(c => c.DateEndWork, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "Worker")
{
query = query
.Where(c => EF.Functions.Like(c.WorkerNavigation.FullName, pattern))
.Order(c => c.WorkerNavigation.FullName, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "IdWorker")
{
query = query
.Where(c => EF.Functions.Like(c.WorkerNavigation.Id.ToString(), pattern))
.Order(c => c.WorkerNavigation.Id, GetArgs.SortOrder);
}
else if (GetArgs.ItemSearch.Value == "KindWork")
{
query = model.ListKindWorks
.Where(c => EF.Functions.Like(c.IdKindWorkNavigation.Short, pattern))
.Order(c => c.IdKindWorkNavigation.Short, GetArgs.SortOrder)
.Select(c => c.IdContractNavigation);
}
else if (GetArgs.ItemSearch.Value == "Subject")
{
query = model.ListSubjects
.Where(c => EF.Functions.Like(c.IdSubjectNavigation.Short, pattern))
.Order(c => c.IdSubjectNavigation.Short, GetArgs.SortOrder)
.Select(c => c.IdContractNavigation);
}
Count = query.Count();
list = query
.Skip(Page * Size)
.Take(Size)
.Select(c => new ContractTableRow
{
IdContract = c.Id,
Num = c.Num,
DateConclusion = c.DateConclusion.ToLongDateString(),
DateStartWork = c.DateStartWork.ToLongDateString(),
DateEndWork = c.DateEndWork.ToLongDateString(),
Salary = c.Salary,
Worker = new Item { Id = c.Worker, Value = c.WorkerNavigation.FullName },
KindWork = c.ListKindWorks.Select(y => new ItemLong { Id = y.IdKindWork, Title = y.IdKindWorkNavigation.Title, Short = y.IdKindWorkNavigation.Short }),
Subject = c.ListSubjects.Select(y => new ItemLong { Id = y.IdSubject, Title = y.IdSubjectNavigation.Title, Short = y.IdSubjectNavigation.Short })
}).ToList();
}
}
catch (Exception ex)
{
ShowMessage.Error(string.Format("Во время поиска произошла ошибка.\n\n{0} {1}",
ex.Message, ex.InnerException.Message));
}
stopwatch.Stop();
logger.Debug("Поиск договора: {0}", stopwatch.Elapsed);
return list;
}
}
}
public class WorkerModel : TableModel<WorkerTableRow>
{
internal SearchModel GetSearch { get; set; }
public WorkerModel()
{
Size = Properties.Settings.Default.TableWorkerSize;
GetSearch = new SearchModel();
}
internal override bool Delete(int id)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
bool result = true;
try
{
using (ModelContext model = new ModelContext())
{
Workers w = model.Workers.Single(x => x.Id == id);
model.Remove(w);
model.SaveChanges();
}
Count--;
}
catch (Exception ex)
{
result = false;
ShowMessage.Error(string.Format(
"Во время удаления данных работника из базы данных произошла ошибка. ID работника: {0}\n\n{1} {2}",
id, ex.Message, ex.InnerException.Message), "Исключение - MainModel.DeleteContract");
}
stopwatch.Stop();
logger.Debug("DeleteWorker(): {0}", stopwatch.Elapsed);
return result;
}
internal override List<WorkerTableRow> LoadPage()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<WorkerTableRow> source = null;
try
{
using (ModelContext model = new ModelContext())
{
Count = model.Workers.Count();
IEnumerable<WorkerTableRow> rows = model.Workers
.OrderByDescending(r => r.Id)
.Skip(Page * Size)
.Take(Size)
.Select(w => new WorkerTableRow
{
IdWorker = w.Id,
FullName = w.FullName,
PassportNumber = w.PassportNumber,
PassportSeries = w.PassportSeries,
Address = w.Address,
BankAccount = w.BankAccount,
DateIssued = w.DateIssued.ToLongDateString(),
Issued = new ItemLong { Id = w.IssuedNavigation.Id, Short = w.IssuedNavigation.ShortTitle, Title = w.IssuedNavigation.Title },
BankItem = new ItemLong { Id = w.BankNavigation.Id, Short = w.BankNavigation.ShortTitle, Title = w.BankNavigation.Title },
});
source = rows.ToList();
}
}
catch (Exception ex)
{
source = null;
ShowMessage.Error(string.Format(
"Во время загрузки страницы с данными работников произошла ошибка. Номер страницы: {0} (отсчет от {1})\n\n{2} {3}",
Page, MinPage, ex.Message, ex.InnerException.Message), "Исключение - MainModel.LoadPage");
}
stopwatch.Stop();
logger.Debug("Load page: {0}", stopwatch.Elapsed);
return source;
}
internal override List<WorkerTableRow> Find(SearchArgs e)
{
return GetSearch.FirstPage(e);
}
internal override List<WorkerTableRow> ReloadPage()
{
GetSearch.IsSearch = false;
return base.ReloadPage();
}
internal class SearchModel : SearchModel<WorkerTableRow>
{
public SearchModel()
{
Size = Properties.Settings.Default.TableSearchSize;
ListTypeSearch = new List<ItemSearch>
{
new ItemSearch { Value = "Id", Display = "ID" },
new ItemSearch { Value = "FullName", Display = "ФИО" },
new ItemSearch { Value = "PassportSeries", Display = "Серия паспорта" },
new ItemSearch { Value = "PassportNumber", Display = "Личный номер" },
new ItemSearch { Value = "DateIssued", Display = "Дата выдачи" },
new ItemSearch { Value = "Address", Display = "Адрес" },
new ItemSearch { Value = "BankAccount", Display = "Счет" }
};
GetItemIdWorker = ListTypeSearch[0];
}
internal override List<WorkerTableRow> LoadPage()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string pattern = GetPattern(GetArgs.IsExactMatch, GetArgs.Keyword);
List<WorkerTableRow> list = null;
try
{
using (ModelContext model = new ModelContext())
{
IQueryable<Workers> query = model.Workers;
if (GetArgs.ItemSearch.Value == "Id")
query = query
.Where(w => EF.Functions.Like(w.Id.ToString(), pattern))
.Order(w=>w.Id, GetArgs.SortOrder);
else if (GetArgs.ItemSearch.Value == "FullName")
query = query
.Where(w => EF.Functions.Like(w.FullName, pattern))
.Order(w=>w.FullName, GetArgs.SortOrder);
else if (GetArgs.ItemSearch.Value == "PassportSeries")
query = query
.Where(w => EF.Functions.Like(w.PassportSeries, pattern))
.Order(w => w.PassportSeries, GetArgs.SortOrder);
else if (GetArgs.ItemSearch.Value == "PassportNumber")
query = query
.Where(w => EF.Functions.Like(w.PassportNumber, pattern))
.Order(w => w.PassportNumber, GetArgs.SortOrder);
else if (GetArgs.ItemSearch.Value == "Address")
query = query
.Where(w => EF.Functions.Like(w.Address, pattern))
.Order(w => w.Address, GetArgs.SortOrder);
else if (GetArgs.ItemSearch.Value == "BankAccount")
query = query
.Where(w => EF.Functions.Like(w.BankAccount, pattern))
.Order(w => w.BankAccount, GetArgs.SortOrder);
else if (GetArgs.ItemSearch.Value == "DateIssued")
query = query
.Where(w => EF.Functions.Like(w.DateIssued.ToLongDateString(), pattern))
.Order(w => w.DateIssued, GetArgs.SortOrder);
Count = query.Count();
list = query
.Skip(Page * Size)
.Take(Size)
.Select(w => new WorkerTableRow
{
IdWorker = w.Id,
FullName = w.FullName,
PassportNumber = w.PassportNumber,
PassportSeries = w.PassportSeries,
Address = w.Address,
BankAccount = w.BankAccount,
DateIssued = w.DateIssued.ToLongDateString(),
Issued = new ItemLong { Id = w.IssuedNavigation.Id, Short = w.IssuedNavigation.ShortTitle, Title = w.IssuedNavigation.Title },
BankItem = new ItemLong { Id = w.BankNavigation.Id, Short = w.BankNavigation.ShortTitle, Title = w.BankNavigation.Title },
}).ToList();
}
}
catch (Exception ex)
{
ShowMessage.Error(string.Format("Во время поиска произошла ошибка.\n\n{0} {1}",
ex.Message, ex.InnerException.Message));
}
stopwatch.Stop();
logger.Debug("Поиск работника: {0}", stopwatch.Elapsed);
return list;
}
}
}
public abstract class TableModel<T> : PagedModelBase<T>
{
internal void Added()
{
Count++;
}
internal abstract bool Delete(int id);
internal abstract List<T> Find(SearchArgs e);
}
public abstract class SearchModel<T> : PagedModelBase<T>
{
private bool isSearch;
internal bool IsSearch
{
get { return isSearch; }
set
{
isSearch = value;
Button[2] = IsSearch;
}
}
internal ItemSearch GetItemIdWorker { get; set; }
internal List<ItemSearch> ListTypeSearch { get; set; }
internal string GetSeachResultText
{
get
{
string text;
if (Count == 0)
{
text = string.Empty;
}
else
{
text = string.Format("Найдено: {0}", Count);
}
return text;
}
}
internal List<T> FirstPage(SearchArgs e)
{
GetArgs = e;
List<T> list = FirstPage();
if (list.Count > 0)
{
IsSearch = true;
PageNumText = GetPageNumText;
ResultSearchText = GetSeachResultText;
}
return list;
}
internal string GetPattern(bool exactMatch, string text)
{
if (!exactMatch)
{
text = string.Format("%{0}%", text);
}
return text;
}
}
public abstract class PagedModelBase<T> : ToolStripUI
{
internal Logger logger = NLog.LogManager.GetCurrentClassLogger();
internal event EventHandler InnerChangePageEvent;
private int count;
private int page = -1;
private int maxPage = 1;
internal int MaxPage
{
get { return maxPage; }
set
{
maxPage = value;
if (Page >= MaxPage)
{
Page = MaxPage - 1;
InnerChangePageEvent?.Invoke(this, EventArgs.Empty);
}
else if (Page == MaxPage - 1)
{
Button[1] = false;
}
else
{
Button[1] = true;
}
}
}
internal int MinPage { get; }
internal int Count
{
get { return count; }
set
{
count = value;
if (Count > 0)
{
MaxPage = GetMaxPage();
}
PageNumText = GetPageNumText;
}
}
internal int Size { get; set; }
internal int Page
{
get { return page; }
set
{
if (value <= MinPage)
{
page = MinPage;
Button[0] = false;
}
else
{
page = value;
Button[0] = true;
}
}
}
private int GetMaxPage()
{
return Convert.ToInt32(Math.Ceiling((double)Count / Size));
}
internal string GetPageNumText
{
get { return string.Format("{0} из {1}", Page + 1, MaxPage); }
}
internal virtual List<T> ReloadPage()
{
return LoadPage();
}
internal List<T> FirstPage()
{
return CustomPage(MinPage);
}
internal List<T> LastPage()
{
return CustomPage(MaxPage - 1);
}
internal List<T> NextPage()
{
return CustomPage(Page + 1);
}
internal List<T> PreviousPage()
{
return CustomPage(Page - 1);
}
internal List<T> CustomPage(int customPage)
{
List<T> list;
Page = customPage;
list = LoadPage();
return list;
}
internal abstract List<T> LoadPage();
}
public class ToolStripUI
{
public bool[] Button { get; set; } = new bool[3];
public SearchArgs GetArgs { get; set; } = new SearchArgs(null, Properties.Settings.Default.ResultSearch_SortDirectionDefault, false, string.Empty);
public string PageNumText { get; set; }
public string ResultSearchText { get; set; } = string.Empty;
}
public class SearchArgs : EventArgs
{
public ItemSearch ItemSearch;
public SortOrder SortOrder;
public bool IsExactMatch;
public string Keyword;
public SearchArgs(ItemSearch item, SortOrder order, bool match, string keyword)
{
ItemSearch = item;
SortOrder = order;
IsExactMatch = match;
Keyword = keyword;
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>In connection with the continuation of the development, updated the classes code to the actual state. The changes affect part of the search and have almost no effect on the interaction of classes. In addition to reducing duplicate values. So in <code>ToolStripUI</code> appeared one property <code>GetArgs</code>, which contains data from <code>SearchArgs</code>.</p>
<p><strong>UPDATE</strong></p>
<p>My topic don't correct? No any comment and answer on theme.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T09:56:29.443",
"Id": "435665",
"Score": "1",
"body": "There is something missing here: `... // Likewise` - please post all code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T10:03:07.567",
"Id": "435667",
"Score": "1",
"body": "Please tag the relevant technology (winforms,...) instead of using such general tags as \"object oriented\" or \"inheritance\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T10:30:32.703",
"Id": "435669",
"Score": "0",
"body": "@BCdotWEB this is really winforms, but others are specific (e.g., LINQ), are not relevant to the subject matter. It should be specified?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T10:32:46.573",
"Id": "435670",
"Score": "0",
"body": "@t3chb0t `SearchTable*` and `Table*` - are essentially the same. The difference is in referring to another table whose names differ according to `Contract` and `Worker`"
}
] |
[
{
"body": "<h3>Inheritance</h3>\n\n<ul>\n<li>the point of inheritance and <code>abstract</code> base classes or <code>interface</code>s is to have a common API that each type implements in its own way. Your inhertiance model doesn't do that. Classes that are inherited from the <code>PageModelBase</code> add a lot new APIs like the <code>SearchModel</code>. Some of them like the <code>FirstPage</code> method even gets a new overload. This is very confusing. It's difficult to figre out how these models are used but they definitely shouldn't be based on <code>PageModelBase</code>.</li>\n<li>the <code>abstract class PagedModelBase</code> doesn't have any <code>abstract</code> or <code>virtual</code> methods so there is not reason for it to be <code>abstract</code> because you don't <code>override</code> anything. It looks like it should be a <code>PageNavigator</code> that other classes use as a service/dependency. In other words, you cannot use the <code>SearchModel</code> where you currently use <code>TableModel</code> because even though they share a common base class, they are not exchangable as they use additionl and specialized APIs.</li>\n</ul>\n\n<h3>Repetitions</h3>\n\n<blockquote>\n<pre><code>internal override List<ContractTableRow> LoadPage()\n{\n Stopwatch stopwatch = new Stopwatch();\n stopwatch.Start();\n\n // do soemthing...\n\n stopwatch.Stop();\n logger.Debug(\"Поиск договора: {0}\", stopwatch.Elapsed);\n\n return list;\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li>you use this pattern in a lot of places. It'd better to create a benchmark-helper or even a decorator for your models that would add this layer outside the core APIs. </li>\n<li>you can instantly start with <code>Stopwatch.StartNew()</code></li>\n<li>there's no need to stop it, just call <code>stopwatch.Elapsed</code></li>\n</ul>\n\n<h3>Misc</h3>\n\n<ul>\n<li>some of the names are confusing like where you write <code>SearchArgs GetArgs</code>. This property should also be called <code>SearchArgs</code></li>\n<li>I cannot find any <code>event SearchChanged<SearchArgs></code> so I think you are not using it with an event. If this is true, then you shouldn't be using <code>EventArgs</code> as its base class because there is no benefit in doing so.</li>\n<li>using <code>var</code> instead of full types would make your code less verbose and consequently easier to read</li>\n<li><code>ContractModel.Delete</code> (and others) returns a <code>bool</code> but more useful would be to return the number of affected rows that <code>SaveChanges</code> returns. <code>bool</code> doesn't tell me whether anything has actually been deleted, only that the method didn't fail. This is rarely useful.</li>\n<li>you decrease <code>Count--</code> after a deletion without actually checking if anything has been really deleted. You should check what <code>SaveChanges</code> returs.</li>\n<li>I don't think that models should use the static <code>ShowMessage</code> type. It should be a service that is injected via the constructor.</li>\n<li>you should use constants for all the magic-strings like <code>\"Num\"</code> or <code>\"Salary\"</code> etc.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T18:18:14.847",
"Id": "436721",
"Score": "0",
"body": "The first item came out in my opinion too general. I don't quite understand him. Regarding the second, there is `abstract List<T> LoadPage()` and `virtual List<T> ReloadPage()`. About `Stopwatch`: I don't have enough skills to create such 'helpers'. Event `SearchArgs` really missing. Due to the modification of the code, which was discussed in the topic update. `Count--` has no checks because the method `Delete()` is called based on the result `true` from another method `Delete()` (outside this model)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T19:13:15.130",
"Id": "436731",
"Score": "0",
"body": "@Owl oh, I now see the [tag:beginner] tag... I'll try to improve my answer..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T16:52:11.283",
"Id": "225045",
"ParentId": "224569",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225045",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:15:22.690",
"Id": "224569",
"Score": "5",
"Tags": [
"c#",
"beginner",
"object-oriented",
"winforms",
"inheritance"
],
"Title": "Page-by model of data output and search results with values for UI"
}
|
224569
|
<p>I'm attempting a practice problem in Codeforces that requires you to find the number of multiples of 3 less than or equal to a given number. I have written the following code but it gives a TLE once the test case reaches the order of 10<sup>8</sup>.</p>
<pre><code>int x = Reader.nextInt();
int count = 0;
for(int i = 3; i<=x; i++){
if(i%3 == 0){
count++;
}
}
System.out.println(count);
</code></pre>
<p>Is there any way I can further optimize this code? The test cases max out at 10<sup>9</sup>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:58:14.620",
"Id": "435603",
"Score": "6",
"body": "Can you think of a simple mathematical formula which computes the result directly, without the need for a loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:04:23.743",
"Id": "435605",
"Score": "12",
"body": "Is it dividing the given number by 3? Oh no"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T16:16:49.900",
"Id": "435711",
"Score": "1",
"body": "It might be better to include the entire program if this is most of the program. We have a lot of space for code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T19:37:46.030",
"Id": "435726",
"Score": "0",
"body": "TLE? What's that? Time limit exception?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T19:38:20.963",
"Id": "435727",
"Score": "1",
"body": "Ignoring the closed-form solution of this particular problem, I would suggest you use [`IntStream.iterate(3, i -> i+3)`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#iterate-int-java.util.function.IntUnaryOperator-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T21:49:31.400",
"Id": "435733",
"Score": "0",
"body": "@Alexander Why would you recommend this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:49:19.220",
"Id": "435737",
"Score": "0",
"body": "@gnasher729 You can do much more with it than obtain the final count."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:21:55.490",
"Id": "435830",
"Score": "1",
"body": "@Evorlor Time limit error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:24:02.967",
"Id": "435831",
"Score": "0",
"body": "@Alexander I have never used the IntStream interface before before. I will definitely look into it, thanks for the suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:24:06.050",
"Id": "436184",
"Score": "0",
"body": "@Evorlor; TLE is an abbreviation of [tag:time-limit-exceeded] ."
}
] |
[
{
"body": "<p>Use your brain, not brute force. How would you solve the problem if it were presented in a math test, and you couldn't use a computer?</p>\n\n<p>Your solution requires <span class=\"math-container\">\\$O(x)\\$</span> time; it should be possible in <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:28:52.773",
"Id": "435608",
"Score": "1",
"body": "The title does state _counting_, not _computing_ :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:29:14.293",
"Id": "435609",
"Score": "2",
"body": "Yep, I figured. I'll keep the question up as a reminder to me that most simple problems will have simple solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T23:07:00.367",
"Id": "435642",
"Score": "6",
"body": "@dfhwze That's only since someone butchered the title. It originally said *finding*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:22:46.113",
"Id": "224574",
"ParentId": "224571",
"Score": "11"
}
},
{
"body": "<p>If you are insisting on counting, instead of computing the answer, you can optimize your counting loop by just looping over the multiples of 3:</p>\n\n<pre><code>for(int i = 3; i <= x; i += 3) {\n count++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:41:41.773",
"Id": "435615",
"Score": "0",
"body": "you missed a trick here, appending count++ in the loop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:41:42.747",
"Id": "435616",
"Score": "0",
"body": "Yeah this works. I needed to count it as it was mentioned explicitly in the question. But I hadn't even figured the simple computation until a few minutes ago."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:42:14.150",
"Id": "435617",
"Score": "0",
"body": "@dfhwze how would that work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:42:51.713",
"Id": "435618",
"Score": "2",
"body": "for(int i = 3; i <= x; i += 3, count++);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:48:30.990",
"Id": "435621",
"Score": "0",
"body": "Thanks for pointing out this trick! I haven't messed around with loop parameters like this before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T19:22:52.273",
"Id": "435628",
"Score": "5",
"body": "@dfhwze That “trick” doesn’t make the code run any faster, and can lead to errors if you forget/don’t notice the trailing semicolon. I would call it out reviewing other people’s code here on Code Review. I certainly didn’t “miss” it, and highly recommend against it. When iterating over a non-trivial body, with two or more iterators, incrementing all of them in the increment portion of the `for()` statement is proper, and can improve readability of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T19:25:50.797",
"Id": "435629",
"Score": "1",
"body": "That \"trick\" was a lightweight joke. Didn't mean to step on anyone's toes here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T21:51:40.487",
"Id": "435734",
"Score": "1",
"body": "@dfhwze My compiler would refuse to compile it. It gives a warning when a semicolon immediately follows an if or for because it is most likely a bug, and any warning is turned into an error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T08:15:26.350",
"Id": "435772",
"Score": "0",
"body": "@gnasher729 You can configure whether warnings are compile errors. Feel free to play around with this. But in the end, it's all just semantic shenanigans. Go with the solution as provided in the answer."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:34:55.913",
"Id": "224575",
"ParentId": "224571",
"Score": "8"
}
},
{
"body": "<p>If I were to compute the answer, I'd do (language shown is C#):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var n = 1e8;\nint v = n / 3;\n</code></pre>\n\n<p>6 has two multiples of three less than or equal to it: <code>6 / 3 == 2</code>\n127 has 42: <code>127 / 3 == 42.3333</code>, thus <code>Math.floor(127 / 3) == 42</code>.</p>\n\n<p>Likewise, <code>3 * n</code> will have <code>n</code> multiples of three, including three itself.</p>\n\n<hr>\n\n<p>Rather than having to iterate <code>1e8 - 2</code> times in a for-loop (similar amounts are often used for benchmarking tests), we just have to boil it down to a single integer division.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:51:27.530",
"Id": "435651",
"Score": "1",
"body": "I'm using Java here. Doing long/int division in Java ignores the decimal section anyways. But thanks for the answer, I'll keep it in mind for a later use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T07:23:51.293",
"Id": "435767",
"Score": "0",
"body": "You're welcome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:45:44.100",
"Id": "435880",
"Score": "2",
"body": "You know, in java 11, that actually compiles :P we have autotyping now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T01:42:33.110",
"Id": "435921",
"Score": "0",
"body": "I've been noticing Java lags behind on new features. Lambdas weren't introduced until Java 8 whilst they were a part of C# for much longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:21:54.053",
"Id": "436183",
"Score": "1",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:24:16.383",
"Id": "224593",
"ParentId": "224571",
"Score": "3"
}
},
{
"body": "<p>Using lambdas you can use multithread easily, it should improve your results:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>IntStream.rangeClosed(3, x).parallel().filter(n -> n%3 == 0).count()\n</code></pre>\n\n<p>or, in case you need long values:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>LongStream.rangeClosed(3L, x).parallel().filter(n -> n%3L == 0L).count()\n</code></pre>\n\n<hr>\n\n<p>I tested it with the following example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n\n Instant start, end;\n long x = 24923869024L;\n long count = 0;\n\n // normal loop\n start = Instant.now();\n for (long n=3L; n<=x; n++) {\n if (n%3L==0L) count++;\n }\n end = Instant.now();\n System.out.println(\"method 1, result = \"+count+\", time = \"+Duration.between(start, end));\n\n // non-parallel stream\n start = Instant.now();\n count = LongStream.rangeClosed(3L, x).filter(n -> n%3L == 0L).count();\n end = Instant.now();\n System.out.println(\"method 2, result = \"+count+\", time = \"+Duration.between(start, end));\n\n // parallel stream\n start = Instant.now();\n count = LongStream.rangeClosed(3L, x).parallel().filter(n -> n%3L == 0L).count();\n end = Instant.now();\n System.out.println(\"method 3, result = \"+count+\", time = \"+Duration.between(start, end));\n\n }\n</code></pre>\n\n<p>with the results:</p>\n\n<pre><code>method 1, result = 8307956341, time = PT33.55S\nmethod 2, result = 8307956341, time = PT40.611S\nmethod 3, result = 8307956341, time = PT12.637S\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:58:09.750",
"Id": "436157",
"Score": "0",
"body": "Could you be specific about *what* is better? I'm guessing you mean the elapsed time, rather than (say) memory usage or energy consumed. Also, *why* this improves it is also worth mentioning (given that the parallelisation overhead is probably fairly high compared with the work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:06:43.377",
"Id": "436171",
"Score": "0",
"body": "I was talking only about total time, it's true that I've not taken into account any other factor like memory or energy. Also, it's possible that results may vary according the computer. I'm sure there would be a way more clever and optimized solution (and I'll be glad to know it); however, in my opinion, simpler solutions are good enough in some cases."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:23:57.093",
"Id": "224808",
"ParentId": "224571",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "224575",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T16:51:26.673",
"Id": "224571",
"Score": "6",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Counting multiples of 3 up to a given number"
}
|
224571
|
<p>I was coding the problem <a href="https://www.codechef.com/problems/KOL16L" rel="nofollow noreferrer">here</a>. I think I have solved it, but I ran into time limit exceeded issues. I am new in Competitive Programming, so I was looking for a better, time efficient logic for solving the same. </p>
<p>Time limit: 1 secs</p>
<p>My time: 3.01 secs</p>
<p>The problem in short:</p>
<blockquote>
<p>Given the numbers [1 .. N ] to be put in a binary search tree and a sequence of m searches (<span class="math-container">\$s_1\$</span> , <span class="math-container">\$s_2\$</span> , . . . , <span class="math-container">\$s_m\$</span> ), solve the optimal BST problem
with the cost as the sum of the distances between every two
consecutive searches <span class="math-container">\$s_i\$</span> and <span class="math-container">\$s_{i+1}\$</span> on the BST.</p>
<p>Cost(T,S) = Depth(<span class="math-container">\$s_1\$</span>) + Distance(<span class="math-container">\$s_1\$</span>, <span class="math-container">\$s_2\$</span>) + Distance(<span class="math-container">\$s_2\$</span>, <span class="math-container">\$s_3\$</span>) + ... +
Distance(<span class="math-container">\$s_{m-1}\$</span>, <span class="math-container">\$s_m\$</span>).</p>
</blockquote>
<pre><code>import sys
def getLevel(node, data):
if (node.key == data) :
return 1
downlevel= 1+getLevel(node.left, data)
if (downlevel != 0) :
return downlevel
downlevel = 1+getLevel(node.right,data)
return downlevel
def pathToNode(node, path, k):
path.append(node.key)
if node.key == k :
return True
if ((node.left != None and pathToNode(node.left, path, k)) or
(node.right!= None and pathToNode(node.right, path, k))):
return True
path.pop()
return False
def distance(node, x, y):
path1 = []
pathToNode(node, path1, x)
path2 = []
pathToNode(node, path2, y)
i=0
while i<len(path1) and i<len(path2):
if path1[i] != path2[i]:
break
i = i+1
return (len(path1)+len(path2)-2*i)
class newNode:
def __init__(self, item):
self.key=item
self.left = None
self.right = None
def constructTrees(start, end):
list = []
if (start > end) :
list.append(None)
return list
for i in range(start, end + 1):
leftSubtree = constructTrees(start, i - 1)
rightSubtree = constructTrees(i + 1, end)
for j in range(len(leftSubtree)) :
left = leftSubtree[j]
for k in range(len(rightSubtree)):
right = rightSubtree[k]
node=newNode(i)
node.left = left
node.right = right
list.append(node)
return list
if __name__ == '__main__':
b1,c1=input().split(' ')
b1=int(b1)
c1=int(c1)
ar = input() # 1 3 2 1 2
ar = ar.split(' ')
ar = [int(x) for x in ar]
min= sys.maxsize
totalTreesFrom1toN = constructTrees(1, b1)
for i in range(len(totalTreesFrom1toN)):
dist = getLevel(totalTreesFrom1toN[i],1)-1
for j in range(len(ar)-1):
dist=dist+distance(totalTreesFrom1toN[i], ar[j], ar[j+1])
if(dist<min):
min=dist
print(min)
</code></pre>
<p>Can anyone tell me where I can possibly refine the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T18:10:36.630",
"Id": "435625",
"Score": "3",
"body": "Links can rot or become broken. [Please include a description of the challenge here in your question.](https://codereview.meta.stackexchange.com/a/1994)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:51:29.043",
"Id": "435652",
"Score": "0",
"body": "Maybe I don't understand the code, but I don't see how it could work. For example, neither `getlevel()` nor `pathtonode()` handle the case where node is None or alternatively don't recurse if node.left or node.right are None."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T14:56:53.590",
"Id": "435704",
"Score": "0",
"body": "@RootTwo for `pathnode()` if node has no left or right child, it will pop the node value and return `False` signifying that there is no path ahead to go. For `getlevel()` I think I missed the back recursion condition. Thanks for pointing it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T14:59:04.357",
"Id": "435705",
"Score": "0",
"body": "@dfhwze yes you are right, I will edit the question accordingly."
}
] |
[
{
"body": "<h3>Use the properties of a BST</h3>\n\n<p>In a BST, if the value being search for is less than the key of the current node, then it is in the left subtree and if the value is greater than the key of the current node, then it is in the right subtree. Your code always searches the left subtree first and then searches the right subtree if needed. This code only searches one subtree:</p>\n\n<pre><code>def pathToNode(node, path, k):\n path.append(node.key) \n if node.key == k : \n return True\n\n elif k < node.key:\n if node.left and pathToNode(node.left, path, k):\n return True\n\n else:\n if node.right and pathToNode(node.right, path, k): \n return True\n\n path.pop() \n return False\n</code></pre>\n\n<p>The same applies to <code>getlevel()</code>.</p>\n\n<p><code>distance()</code> determines the path from the root to each node. Then determines the common prefix of each path. This can be simplified as observing that if both nodes are in the same subtree, then the root of the current tree isn't on the path between the nodes.</p>\n\n<pre><code>def distance(node, x, y):\n if x < node.key and y < node.key:\n return distance(node.left, x, y)\n\n elif node.key < x and node.key < y:\n return distance(node.right, x, y)\n\n else:\n path1 = []\n pathToNode(node, path1, x) \n path2 = [] \n pathToNode(node, path2, y)\n\n return len(path1) + len(path2) - 2\n</code></pre>\n\n<p>Note: you don't actually need the path of a node, just it's depth.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T18:23:20.983",
"Id": "224624",
"ParentId": "224576",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T17:54:17.227",
"Id": "224576",
"Score": "0",
"Tags": [
"python",
"time-limit-exceeded",
"tree",
"dynamic-programming"
],
"Title": "Optimal BST challenge"
}
|
224576
|
<p>I'm in the process of independently learning Generics as a way to build on a college assignment for Binary Search Tree. I've completed this program without Generics first and now I've converted over but I wanted to get some peer review. It seems to be working well and I've run a few tests already.</p>
<p>Would you do anything differently and why?</p>
<p>My main():</p>
<pre><code>public class Assign3 {
public static void main(String[] args){
String choice = new String();
Scanner in = new Scanner(System.in);
Contact newContact;
BinaryTree<Contact> tree = new BinaryTree<Contact>();
while(!choice.equals("7") ){
System.out.println("\nPlease select option:\n1: Display the Tree\n2: Add to the List\n3: Add from a File\n4: Save to a File\n5: Determine if a Person is in the List\n6: List out who calls whom\n7: To Exit");
choice = in.next(); in.nextLine();
switch(choice){
case "1":
tree.displayInOrder();
break;
case "2":
newContact = new Contact();
if(newContact.addContact(in, false))
tree.insertInTree(newContact);
break;
case "3":
System.out.println("Enter name of file to write to: ");
Scanner f = readFile(in.next());
if(f!=null){
while(f.hasNext()) {
newContact = new Contact();
if(newContact.addContact(f, true))
tree.insertInTree(newContact);
else System.out.println("Unable to add contact from file. Proceeding to next contact..");
}
f.close();
}
break;
case "4":
System.out.println("Specify a filename to save: ");
FileWriter o = writeFile(in.next());
if(o != null)
writeToFile(o, tree.root);
try {
o.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case "5":
newContact = new Contact();
if(newContact.addContact(in, false))
tree.searchTree(newContact);
break;
case "6":
if(tree.root != null)
callWhom(tree.root);
break;
case "7":
System.out.println("Exiting…");
break;
default:
System.out.println("Invalid input... please try again.");
break;
}
}
}
public static Scanner readFile(String fileName){
File file = new File(fileName);
Scanner rF = null;
try {
rF = new Scanner(file);
return rF;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("File does not exist..");
return null;
}
}
public static FileWriter writeFile(String fileName){
FileWriter wF = null;
try {
wF = new FileWriter(fileName);
return wF;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Unable to write file..");
return null;
}
}
public static void callWhom(BinaryTreeNode<Contact> subRoot){
System.out.print(subRoot.getData().getName() + " calls ");
if(subRoot.getLeft() != null){
System.out.print(subRoot.getLeft().getData().getName());
if(subRoot.getRight() != null)
System.out.println(" and " + subRoot.getRight().getData().getName());
else
System.out.println();
}
else if(subRoot.getRight() != null)
System.out.println(subRoot.getRight().getData().getName());
else
System.out.println("No Contact");
if(subRoot.getLeft() != null)
callWhom(subRoot.getLeft());
if(subRoot.getRight() != null)
callWhom(subRoot.getRight());
}
public static void writeToFile(FileWriter o, BinaryTreeNode<Contact> subRoot){
try {
if(subRoot.getLeft() != null)
writeToFile (o, subRoot.getLeft());
o.append(subRoot.getData().getName() + "\n" + subRoot.getData().getPhone() + "\n");
if(subRoot.getRight() != null)
writeToFile (o, subRoot.getRight());
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
</code></pre>
<p>My BT class:</p>
<pre><code>public class BinaryTree<F extends Comparable<F>> {
BinaryTreeNode<F> root = null;
public boolean insertInTree (F data) {
BinaryTreeNode<F> item = new BinaryTreeNode<F>(data);
if (root == null)
root = item;
else
return root.insert(data);
return true;
}
public void displayInOrder () {
System.out.println("Phone List");
if (root == null){
System.out.println("List is Empty");
return;
}
else
displayInOrder (root);
}
private void displayInOrder (BinaryTreeNode<F> subRoot){
if(subRoot.getLeft() != null)
displayInOrder (subRoot.getLeft());
System.out.println(subRoot.getData() + " ");
if(subRoot.getRight() != null)
displayInOrder (subRoot.getRight());
}
public boolean searchTree(F temp){
if (root == null)
return false;
else
return root.search(temp);
}
}
</code></pre>
<p>My Node class:</p>
<pre><code>public class BinaryTreeNode<F extends Comparable<F>> {
private F data;
private BinaryTreeNode<F> left, right;
public BinaryTreeNode() {
this(null);
}
public BinaryTreeNode(F data) {
left = null;
right = null;
this.data = data;
}
public F getData() {
return data;
}
public void setValue(F value) {
this.data = value;
}
public BinaryTreeNode<F> getLeft() {
return left;
}
public void setLeft(BinaryTreeNode<F> left) {
this.left = left;
}
public BinaryTreeNode<F> getRight() {
return right;
}
public void setRight(BinaryTreeNode<F> right) {
this.right = right;
}
public boolean insert (F newData) {
if (data.compareTo(newData) < 0) {
if (left == null){
left = new BinaryTreeNode<F>(newData);
return true;
}
else
return left.insert(newData);
} else if (this.data.compareTo(newData) > 0) {
if (this.right == null){
this.right = new BinaryTreeNode<F>(newData);
return true;
}
else
return right.insert(newData);
} else
System.out.println("Duplicate - not adding " + newData);
return false;
}
public boolean search(F findData){
if(data.compareTo(findData) < 0){
if(left == null){
System.out.println("Contact not in List");
}
else
left.search(findData);
}
else if(data.compareTo(findData) > 0){
if(right == null)
System.out.println("Contact not in List");
else
right.search(findData);
}
else{
System.out.println("Contact found in List");
return true;
}
return false;
}
}
</code></pre>
<p>My Contact class:</p>
<pre><code>public class Contact implements Comparable<Contact> {
private String phone;
private String name;
public Contact(){
phone = null;
name = null;
}
/**
* Reads a valid date from the input provided
* @param in Specifies the input to retrieve the date from
* @param fromFile Boolean to notify the method if data is being read from a file
* @return <code>true</code> if the method succeeds, <code>false</code> otherwise
*/
public boolean addContact(Scanner in, boolean fromFile){
if(!fromFile)
System.out.print("Enter name of contact: ");
if(in.hasNextLine()){
name = in.nextLine();
}
if(!fromFile)
System.out.print("Enter phone number for contact: ");
if(in.hasNextLine()){
phone = in.nextLine();
while(!Pattern.matches("^(\\d{1})?[\\(-]??\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{4}$", phone) && !fromFile){
System.out.println("Invalid number, please try again.. Example: 613-333-3333, 1(613)333-3333, 6133333333, (613) 444 5555");
phone = in.nextLine();
}
if(!Pattern.matches("^(\\d{1})?[\\(-]??\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{4}$", phone) && fromFile){
System.out.println("Invalid telephone number");
return false;
}
phone = phone.replaceAll("[\\D]", "");
if(phone.length() == 10)
phone = phone.replaceFirst("(\\d{3})(\\d{3})(\\d{4})", "1-$1-$2-$3");
else if(phone.length() == 11)
phone = phone.replaceFirst("(\\d{1})(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3-$4");
}
return true;
}
/**
* Prints the contact name and phone
* @return String that represents the contact stored in this object.
*/
public String toString(){
return name + ": " + phone;
}
/**
* The method compares the Contact name. If the names are the same, the phone numbers are compared.
* @return int value representing the comparison between two object's attribute (==0 means the objects attribute are the same)
*/
@Override
public int compareTo(Contact o) {
// TODO Auto-generated method stub
if(o.name.toUpperCase().compareTo(this.name.toUpperCase()) == 0){
return o.phone.toUpperCase().compareTo(this.phone.toUpperCase());
}
return o.name.toUpperCase().compareTo(this.name.toUpperCase());
}
/**
* The function is used to retrieve the Contact name.
* @return String that represents the Contact name
*/
public String getName(){
return name;
}
/**
* The function is used to retrieve the Contact phone number.
* @return String that represents the Contact phone number
*/
public String getPhone() {
// TODO Auto-generated method stub
return phone;
}
}
</code></pre>
<p>I'm a student and welcome all feedback but please give details.</p>
|
[] |
[
{
"body": "<p>Here are my comments:</p>\n\n<h2>Apply the <a href=\"https://www.geeksforgeeks.org/visitor-design-pattern/\" rel=\"nofollow noreferrer\">Visitor Design Pattern</a></h2>\n\n<p>There are several methods that perform similar process: recursively traverse the tree, and perform specific action on each node. (insert(), search(), write to file(), etc) this is a good fit for the visitor design pattern. In short, this pattern defines how you can implement the traversal of the tree in one place, and have it work with multiple operations on individual nodes. </p>\n\n<h2>Observe the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a></h2>\n\n<p><code>addContact()</code> in the Contact class is responsible for getting a contact from user input from the console, or read a contact from a file. it further carries some elaborate and fairly complex validation rules. now what will happen when you want to read a contact from a database? or have a nice html form for user input? what if you wish to support foreign telephone numbers, where the placement of a dash can vary?</p>\n\n<h2>Avoid literals (a.k.a <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic numbers</a>)</h2>\n\n<p>while we are on the subject of telephone number validation: I do not know exactly why, but regex that validates telephone number is specified twice. now imagine that you find a bug in the regex. it is possible you will fix it in one place and forget to fix in the other. the principal also applies to user choice menu, what if you wish to add another choice? will you keep the ordering? what if you wish to change the choices from numbers to letters \"a\" through \"f\"?</p>\n\n<h2><code>Comparable</code> and <code>Comparator</code></h2>\n\n<p>When if you will want to store objects that are not <code>Comparable</code> in your spiffy binary tree? what if you will want to give the user an option of choosing whether the contacts will be sorted by number <em>first</em>, then by name? or perhaps the user wil have favorite contacts that will want to sort out first? for this wealth of options to be supported, you will want to have an overloaded insert() and search() that accept a comparator. this is analogous to the JDK <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List)\" rel=\"nofollow noreferrer\"><code>Collections.sort()</code></a> having an overloaded option that accepts a comparator.</p>\n\n<p>lastly,</p>\n\n<h2>Observe naming conventions</h2>\n\n<p>The Java collections (your tree can be regarded as a collection) are parameterized with the generic <code>T</code> that is short for <code>Type</code>. The <code>Map</code> collection is parameterized with <code>K</code> and <code>V</code> . why did you choose <code>F</code> as the generic symbol? it is confusing for the programmer who is aware of the naming conventions. observing these conventions establishes a common language between Java developers and helps communication between them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:55:19.230",
"Id": "435891",
"Score": "0",
"body": "I'll do a little more research on the feedbacks and tackle it 1 at a time. For \"Observe naming conventions\" - honestly, I just failed to consider the next person trying to read my code and randomly selected F. I agree that it can be confusing to anyone familiar with the naming convention. It's good feedback and something I should consider, specially when I start working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T21:06:33.007",
"Id": "435906",
"Score": "0",
"body": "\" Avoid literals (a.k.a magic numbers) \" I see what you mean. In terms of the regex, there's really no need to have in there twice. A simple if condition (if reading data from a file) in the loop would allow me to break out of the loop in case of bad data in the file. No point in writing additional lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T06:29:01.420",
"Id": "435933",
"Score": "0",
"body": "@suMmGuy, if you find the answer useful, you are welcome to accept and/or upvote"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T06:54:06.310",
"Id": "224655",
"ParentId": "224578",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "224655",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T18:25:01.640",
"Id": "224578",
"Score": "2",
"Tags": [
"java",
"tree",
"generics"
],
"Title": "Implementation of Generic Binary Tree Code"
}
|
224578
|
<p>I am given 8 positive 32-bit integer numbers. The task is to write program to count all X-bits.</p>
<p>X-bits are groups of 9 bits (3 rows x 3 columns) forming the letter "X". task is to count all X-bits and print their count on the console. Valid X-bits consist of 3 numbers where their corresponding bit indexes are exactly {"101", "010", "101"}. All valid X-bits can be part of multiple X-bits (with overlapping).</p>
<p>Expected input and output:
<a href="https://i.stack.imgur.com/3u9j2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3u9j2.png" alt="enter image description here"></a></p>
<p>Bellow is my solution, for any of the inputs it prints out the correct value, and it passes every test in our judge system, which makes me think that it's a valid solution to the problem.
The idea of my approach is simple, the array is treated as if it was a 2d array and each group of 9 bits across 3 ints of the array is compared to the required pattern.</p>
<pre><code>import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int xCount = 0;
int nums[] = new int[8];
for(int i = 0; i < nums.length; i++) {
nums[i] = Integer.parseInt(stdin.nextLine());
}
for (int i = 0; i < nums.length - 2; i++) { // nums.length - 2 because in validX(...) we have index (passed as i) + 2
for (int j = 0; j < 29; j++) { // 31 (index of the leftmost bit) - 2 because we have startingPosition + 2
if(validX(nums, i, j) == true) {
xCount++;
}
}
}
System.out.println(xCount);
}
public static int get_bit(int num, int pos) {
return ((num >> pos) & 1);
}
public static boolean validX(int nums[], int index, int startingPosition) {
if(get_bit(nums[index], startingPosition) == 1 && get_bit(nums[index], startingPosition + 1) == 0
&& get_bit(nums[index], startingPosition + 2) == 1 &&
get_bit(nums[index + 1], startingPosition) == 0 && get_bit(nums[index + 1], startingPosition + 1) == 1
&& get_bit(nums[index + 1], startingPosition + 2) == 0 &&
get_bit(nums[index + 2], startingPosition) == 1 && get_bit(nums[index + 2], startingPosition + 1) == 0 &&
get_bit(nums[index + 2], startingPosition + 2) == 1) {
return true;
}
return false;
}
/*
* in actuality what this function is doing is getting each individual bit and comparing it to the pattern
* we need, which is:
* {"101",
* "010",
* "101"}
*/
}
</code></pre>
<p>The issue I have with this code is that it's ugly. Truth be told I'm slightly ashamed of my <code>validX(...)</code> method, but I can't think of a quicker way or one that would take even less memory. The idea of my approach is simple, the array is treated as if it was a 2d array and each group of 9 bits is compared to the required pattern.</p>
<p>And just to get a few things out of the way, nobody assigned me this problem, I'm doing it to get better in Java. Whatever code I receive (if any at all) won't be submitted anywhere. Quite frankly I'm interested to know if there's a more elegant, readable solution which avoids hardcoded values. The reason I'm not happy with the default solution is because I don't think 0.2 s allowed runtime and 16 MB allowed memory is adequate for a problem like this.</p>
|
[] |
[
{
"body": "<p>I think the main issue is that you took a bit-by-bit approach to a problem that seems to be designed to elicit approaches that take advantage of bitwise operations, which made the solution less elegant(?) than intended. There is a lot of code to extract individual bits and testing them, and an extra loop to go over the <code>startingPosition</code>, and we can do away with that. I don't expect a performance problem with your solution though, 0.2 seconds is a <em>ton</em> of time (running literally a billion instructions in that time is not unreasonable) and barely any memory is allocated.</p>\n\n<p>As you already discovered, the question of \"is there an X here\" can be answered by ANDing \n together the bits that make up the X and also ANDing that with the complements of the bits at the positions that must be zero. Rather than working with booleans, we could work with entire 32bit masks at once, and get an entire 32bit mask as a result, which will then indicate the positions where an X is found. The Xs that are present can be counted using <code>Integer.bitCount</code>.</p>\n\n<p>Forming that mask is really the same idea as the code you already wrote, but instead of adding offsets to the <code>startingPosition</code> there will be some bit-shifts. For example:</p>\n\n<pre><code>private static int calculateXMask(int top, int middle, int bottom) {\n return (top >>> 1) & ~top & (top << 1) &\n (~middle >>> 1) & middle & (~middle << 1) &\n (bottom >>> 1) & ~bottom & (bottom << 1);\n}\n</code></pre>\n\n<p>Which can then be applied to every \"window\" of 3 successive integers in <code>num</code>, with the results bitCounted and added up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T22:22:15.347",
"Id": "224583",
"ParentId": "224581",
"Score": "3"
}
},
{
"body": "<p>Well. It's ugly because of the unnecessary <code>if</code> statement. And if you re-format your code, it's not as ugly anymore, and directly clear what it does:</p>\n\n<pre><code>public static boolean validX(int nums[], int index, int startingPosition) {\n\n return ( get_bit(nums[index] , startingPosition ) == 1 && \n get_bit(nums[index] , startingPosition + 1) == 0 &&\n get_bit(nums[index] , startingPosition + 2) == 1 &&\n get_bit(nums[index + 1] , startingPosition ) == 0 && \n get_bit(nums[index + 1] , startingPosition + 1) == 1 &&\n get_bit(nums[index + 1] , startingPosition + 2) == 0 &&\n get_bit(nums[index + 2] , startingPosition ) == 1 && \n get_bit(nums[index + 2] , startingPosition + 1) == 0 &&\n get_bit(nums[index + 2] , startingPosition + 2) == 1) ;\n\n}\n</code></pre>\n\n<p>This might not be as fast as needed, but (IMHO) much better readable. </p>\n\n<p>If you need raw speed, you could generate a (8x32)=256 bit <code>BitSet</code> and a <code>BitSet</code> of the mask. You can then just linearly slide that mask over the input bitset and <code>and()</code> them. Check the bits that are left <code>true</code> with <code>BitSet#cardinality()</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:51:14.003",
"Id": "224724",
"ParentId": "224581",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224583",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T21:41:29.720",
"Id": "224581",
"Score": "6",
"Tags": [
"java",
"bitwise"
],
"Title": "Count all X-shaped bits from 8 integers"
}
|
224581
|
<p>I have this, I guess, new Ruby syntax in my method but Rubocop are warning me that the second last line is too long. Could you please help me to refactor this method?</p>
<pre><code>def show
identification_document = IdentificationDocument.find(params[:id])
authorize identification_document
return unless identification_document
#this line below is to too long
document = params[:size] == 'resized' ? identification_document.id_document_resized : identification_document.id_document
send_data(document.file.read, filename: identification_document.file_name)
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T00:27:12.687",
"Id": "435647",
"Score": "0",
"body": "What does your `IdentificationDocument` class look like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T00:31:27.847",
"Id": "435648",
"Score": "0",
"body": "It's a model, you think there is some other space to improve than @dfhwze provide?"
}
] |
[
{
"body": "<h2>Guidelines Rubocop</h2>\n\n<p>The <a href=\"https://github.com/rubocop-hq/ruby-style-guide\" rel=\"nofollow noreferrer\">guidelines</a> favor if/case over multi-line ternary operator when a line is too long.</p>\n\n<blockquote>\n <ul>\n <li><p><strong><em>Maximum Line Length</strong> Limit lines to 80 characters.</em></p></li>\n <li><p><strong><em>No Multi-line Ternary</strong> Avoid multi-line ?: (the ternary operator); use if/unless instead.</em></p></li>\n <li><p><strong><em>Use if/case Returns</strong> Leverage the fact that if and case are expressions which return a result.</em></p></li>\n </ul>\n</blockquote>\n\n<h2>Refactored Code</h2>\n\n<pre><code>def show\n identification_document = IdentificationDocument.find(params[:id])\n authorize identification_document\n return unless identification_document\n\n document =\n if params[:size] == 'resized'\n identification_document.id_document_resized\n else\n identification_document.id_document\n end\n\n send_data(document.file.read, filename: identification_document.file_name)\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T23:09:06.977",
"Id": "224586",
"ParentId": "224585",
"Score": "1"
}
},
{
"body": "<p>Rubocop warns about lines that are over 80 characters long, its too easy to not notice code that is hiding off to the right hand side of the screen.</p>\n\n<p>Apart from dfhwze's suggestion it might be worth modifying your model code to take a resize parameter, something like:</p>\n\n<pre><code>class IdentificationDocument\n def id_document(resized: false)\n ...\n end\n</code></pre>\n\n<p>And in your controller</p>\n\n<pre><code> #this line below is to too long\n document = identification_document.id_document(resized: params[:size])\n</code></pre>\n\n<p>Another alternative is just to use a shorter variable name and/or use an intermediate variable for <code>params[:size]</code>. i.e.</p>\n\n<pre><code>def show\n id_doc = IdentificationDocument.find(params[:id])\n authorize identification_document\n return unless id_doc\n\n #this line below is to too long\n resize = params[:size] == 'resized'\n doc = resize ? id_doc.id_document_resized : id_doc.id_document\n send_data(doc.file.read, filename: id_doc.file_name)\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T17:05:54.560",
"Id": "224689",
"ParentId": "224585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224586",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T22:59:13.153",
"Id": "224585",
"Score": "0",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Ruby if block refactor from new synthax needed"
}
|
224585
|
<blockquote>
<p>Consider all integer combinations of a<sup>b</sup> for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:</p>
<p>2 ** 2 = 4, 2 ** 3 = 8, 2 ** 4 = 16, 2 ** 5 = 32
3 ** 2 = 9, 3 ** 3 = 27, 3 ** 4 = 81, 3 * 5 = 243
4 ** 2 = 16, 4 ** 3 = 64, 4 ** 4 = 256, 4 ** 5 = 1024
5 ** 2 = 25, 5 ** 3 = 125, 5 ** 4 = 625, 5 ** 5 = 3125</p>
<p>If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:</p>
<p>4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125</p>
<p>How many distinct terms are in the sequence generated by a<sup>b</sup> for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?</p>
</blockquote>
<pre><code>from time import time
def distinct_terms(n):
"""Assumes n an integer > 1.
returns the sequence generated of a ** b for a and b in range(n)"""
return (x ** y for x in range(2, n + 1) for y in range(2, n + 1))
if __name__ == '__main__':
time1 = time()
print((len(set(distinct_terms(100)))))
print(f'Time: {time() - time1}')
</code></pre>
|
[] |
[
{
"body": "<p>Your docstring is misleading.</p>\n\n<ul>\n<li>The function does not return a sequence; it returns a generator.</li>\n<li>It states “<code>for a and b in range(n)</code>”, which is incorrect. They are <code>in range(2, n+1)</code>. If you don’t want to confuse the issue with <code>range()</code> excluding the last value, say “<code>for a and b in the range from 2 to n, inclusive</code>”.</li>\n<li>The problem refers to a “sequence”, where the values are in ascending order and duplicates have been removed, which is completely different from the sequence of values produced by the generator, which is not sorted and can have duplicates.</li>\n</ul>\n\n<hr>\n\n<p><code>time1</code> is a terrible variable name; there is no <code>time2</code>. Perhaps use <code>start_time</code>.</p>\n\n<hr>\n\n<p><code>print((len(...)))</code> has an unnecessary extra pair of parenthesis.</p>\n\n<hr>\n\n<p>Is <code>distinct_terms(n)</code> too specific of a function? Perhaps <code>distinct_terms(m, n)</code> could be more general, where you can generate terms for <code>m <= a,b <= n</code>, instead of always the lower limit of m=2. Or with separate limits for the <code>a</code> and <code>b</code> values.</p>\n\n<hr>\n\n<p>Python is an easy language to solve this problem in, because <span class=\"math-container\">\\$100^{100}\\$</span> is just another integer in Python, despite having 201 digits. If you were to solve this in another programming language, one where integers were restricted to (say) 128 bits, what would you do?</p>\n\n<p>With 99 different values for <code>a</code> and <code>b</code>, you have <span class=\"math-container\">\\$99^2 = 9801\\$</span> different <span class=\"math-container\">\\$a^b\\$</span> expressions. How many of those will be equivalent? Ie, <span class=\"math-container\">\\$a^b = c^d\\$</span>? For example, <span class=\"math-container\">\\$2^4 = 2^{2*2} = {(2^2)}^2 = 4^2\\$</span>. Can you generalize that? Can you count the number of occurrences where that happens, and subtract that from 9801?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:15:54.603",
"Id": "224590",
"ParentId": "224588",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T01:02:34.557",
"Id": "224588",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 29: Distinct powers in Python"
}
|
224588
|
<p><a href="https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup" rel="nofollow noreferrer">Problem Statement</a></p>
<blockquote>
<p>Emma is playing a new mobile game that starts with consecutively
numbered clouds. Some of the clouds are thunderheads and others are
cumulus. She can jump on any cumulus cloud having a number that is
equal to the number of the current cloud plus <strong>1</strong> or <strong>2</strong>. She must
avoid the thunderheads. Determine the minimum number of jumps it will
take Emma to jump from her starting postion to the last cloud. It is
always possible to win the game.</p>
<p>For each game, Emma will get an array of clouds numbered <strong>0</strong> if they
are safe or <strong>1</strong> if they must be avoided. For example,
<strong>c=[0,1,0,0,0,1,0]</strong> indexed from <strong>0...6</strong>. The number on each cloud is its index in the list so she must avoid the clouds at indexes <strong>1</strong>
and <strong>5</strong> . She could follow the following two paths:<br>
<strong>0 -> 2 -> 4 -> 6</strong> or <strong>0 -> 2 -> 3 -> 3 -> 4 -> 6</strong> . The first path takes
<strong>3</strong> jumps while the second takes <strong>4</strong>.</p>
<p><strong>Function Description</strong></p>
<p>Complete the jumpingOnClouds function in the editor below. It should
return the minimum number of jumps required, as an integer.</p>
<p>jumpingOnClouds has the following parameter(s):</p>
<ul>
<li>c: an array of binary integers</li>
</ul>
<p><strong>Input Format</strong></p>
<p>The first line contains an integer <strong>n</strong>, the total number of clouds.
The second line contains <strong>n</strong> space-separated binary integers
describing clouds <strong>c[i]</strong> where <strong>0 <= i < n</strong>.</p>
<p><strong>Output Format</strong></p>
<p>Print the minimum number of jumps needed to win the game.</p>
<p>Sample Input 0</p>
<pre><code>7
0 0 1 0 0 1 0
</code></pre>
<p>Sample Output 0</p>
<pre><code>4
</code></pre>
<p>Explanation 0: Emma must avoid <strong>c[2]</strong> and <strong>c[5]</strong>. She can win the
game with a minimum of <strong>4</strong> jumps. Sample Input 1</p>
<pre><code>6
0 0 0 0 1 0
</code></pre>
<p>Sample Output 1</p>
<pre><code>3
</code></pre>
<p>Explanation 1: The only thundercloud to avoid is c[4]. Emma can win
the game in <strong>3</strong> jumps.</p>
</blockquote>
<p><strong>Imperative style Solution:</strong></p>
<pre><code>// Complete the jumpingOnClouds function below.
def jumpingOnClouds(c: Array[Int]): Int = {
var i=0
var length = c.length
var jumps = 0
while(i < length -1) {
if(i < length-2 && c(i+2) == 0 ) i+=2
else i+=1
jumps +=1
}
jumps
}
</code></pre>
<p><strong>Functional-programming style Solution using Recursion:</strong> </p>
<pre><code> def jumpingOnClouds(c: Array[Int]): Int = {
val limit = c.length -2
def rec(jumps: Int, index: Int): Int = {
if (index > limit) jumps
else {
val jumpingOffset: Int = if(index < limit && c(index + 2) == 0 ) 2 else 1
rec(jumps+1, index + jumpingOffset)
}
}
rec(0,0)
}
</code></pre>
|
[] |
[
{
"body": "<p>The thing about these \"story\" problems is that the story is often distracting, if not outright misleading, from the underlying problem to be solved.</p>\n\n<p>In this case your code solves the challenge by calculating and counting the number of jumps it takes to get from the beginning to the end. More or less the way the story is layed out. But it's worth noting:</p>\n\n<ol>\n<li>The minimum number of jumps for a sequence of N zeros is always N/2.</li>\n<li>At the end of every sequence of zeros is a <code>1</code> to be jumped over, except at the very end.</li>\n</ol>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def jumpingOnClouds(c :Array[Int]) :Int =\n c.mkString.split(\"1\").foldLeft(0)(_ + _.length/2 + 1) - 1\n</code></pre>\n\n<p>This isn't the most efficient solution possible but since the input <code>Array</code> is limited to no more than 100 elements I decided to go for brevity over efficiency.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T07:58:51.070",
"Id": "224601",
"ParentId": "224591",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224601",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:20:32.683",
"Id": "224591",
"Score": "0",
"Tags": [
"programming-challenge",
"comparative-review",
"scala"
],
"Title": "Imperative and functional-programming solutions for Jumping on the Cloud challenge"
}
|
224591
|
<blockquote>
<p>Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:</p>
<ul>
<li><span class="math-container">\$1634 = 1^4 + 6^4 + 3^4 + 4^4\$</span></li>
<li><span class="math-container">\$8208 = 8^4 + 2^4 + 0^4 + 8^4\$</span></li>
<li><span class="math-container">\$9474 = 9^4 + 4^4 + 7^4 + 4^4\$</span></li>
</ul>
<p>As 1 = 1^4 is not a sum it is not included.</p>
<p>The sum of these numbers is <span class="math-container">\$1634 + 8208 + 9474 = 19316\$</span>.</p>
<p>Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.</p>
</blockquote>
<pre><code>from time import time
def powers(n, power):
"""Assumes n and power integers > 0.
generates all numbers up to n if total(n digits ** power) = number."""
nums_pows = {number: sum(int(digit) ** power for digit in str(number)) for number in range(2, n)}
return (x for x, y in nums_pows.items() if x == y)
if __name__ == '__main__':
start_time = time()
print(sum(powers(1000000, 5)))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Your comprehensions are hard to understand, as you have two on one line. I recomend you spread them over multiple lines to increase readability.</li>\n<li><p>There is no benifit to using a dictionary comprehension, and only makes me think you're abusing comprehensions.</p>\n\n<p>Just use a normal <code>for</code> loop and use <code>yield</code>.</p></li>\n<li><p>You don't need to pass <code>n</code>, you can find the limit by using <code>power * 9**power</code>.<br>\nThis causes the program to run in a quarter of the time.</p></li>\n</ul>\n\n<pre><code>def powers(power):\n for number in range(2, power * 9**power):\n total = sum(int(digit) ** power for digit in str(number))\n if total == number:\n yield number\n</code></pre>\n\n<p>If you change from using <code>range</code> to just digits and checking that the total is an anagram of the input then you can get the code to run in ~5% the time of the previous code.</p>\n\n<pre><code>def powers(power):\n for size in range(1, len(str(power * 9**power)) + 1):\n for digits in itertools.combinations_with_replacement(range(10), size):\n total = sum(int(digit) ** power for digit in digits)\n if (sorted(str(total)) == sorted(str(digit) for digit in digits)\n and total != 1\n ):\n yield total\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T06:45:33.370",
"Id": "224599",
"ParentId": "224594",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224599",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T04:33:52.967",
"Id": "224594",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 30 Digits fifth power in Python"
}
|
224594
|
<p>I have a Qt tree view which has a custom tree header. The tree has a so called mode, by default there are two. During each of the modes a different tree is shown. The mode switcher is presented as a context menu of the tree header.</p>
<p>Having a context menu on tree header isn't that hard. But in my case I need to make a tree header such that the user of my code should be able to add new modes are their corresponding tree view pointers, and an action in context menu to switch to the new mode.</p>
<p>Below is my code for the tree header. Please let me know if you have any comments.</p>
<pre><code>class TreeHeader : public QHeaderView
{
public:
TreeHeader(QWidget *parent = nullptr) noexcept;
QAction *getModeAction(const QString &sActionTitle) const;
void addModeAction(QAction *action, eTreeMode mode, QAction *before = nullptr);
protected:
/// Override the context menu event
void contextMenuEvent(QContextMenuEvent *event) override;
/// The context menu
QMenu *m_pContextMenu = nullptr;
private:
/// Setups connections and necessary data for the given action
void setupAction(QAction *action, eTreeMode eMode) const;
}; // class TreeHeader
TreeHeader::TreeHeader(QWidget *parent /* = nullptr */) noexcept
: QHeaderView(Qt::Horizontal, parent)
, m_pContextMenu(new QMenu(this))
{
std::vector<std::pair<eTreeMode, QString>> mapModeToName;
mapModeToName.emplace_back(eTreeMode::Mode1, QString("By %1").arg(mode1));
mapModeToName.emplace_back(eTreeMode::Mode2, QString("By %1").arg(mode2));
// create the default actions
for (const auto &pair : mapModeToName)
{
// add the action to the menu and setup necessary properties to it
setupAction(m_pContextMenu->addAction(pair.second), pair.first);
}
setTextElideMode(Qt::ElideRight);
setStretchLastSection(true);
}
QAction *TreeHeader::getModeAction(const QString &sActionTitle) const
{
for (const auto pAction : m_pContextMenu->actions())
{
if (pAction->text() == sActionTitle)
return pAction;
}
return nullptr;
}
void TreeHeader::addModeAction(QAction *action, eTreeMode mode, QAction *before /* = nullptr */)
{
if (!action) return;
// add the action at appropriate position
if (before)
m_pContextMenu->insertAction(before, action);
else
m_pContextMenu->addAction(action);
// setup necessary properties to the action
setupAction(action, mode);
}
void TreeHeader::contextMenuEvent(QContextMenuEvent *event)
{
if (auto pTree = static_cast<TreeView *>(parentWidget()))
{
// make sure we have a populated tree
if (!(pTree->getTreeModel() && pTree->getTreeModel()->hasChildren())) return;
// show the context menu only for the first column which specifies the grouping mode
if (logicalIndexAt(event->pos()) == 0)
{
// get the current mode
auto eMode = pTree->getMode();
// set correct checked states of the actions
for (const auto pAction : m_pContextMenu->actions())
pAction->setChecked(eMode == static_cast<eTreeMode>(pAction->data().toInt()));
// and show the menu
m_pContextMenu->exec(event->globalPos());
}
}
}
void TreeHeader::setupAction(QAction *action, eTreeMode eMode) const
{
// make the action checkable and check it, if necessary
action->setCheckable(true);
// set the action's checked state and make necessary connections
if (auto pTree = dynamic_cast<TreeView *>(parentWidget()))
{
action->setChecked(pTree->getMode() == eMode);
// set up a connection to process to mode change
if (auto pView = dynamic_cast<TreeViewContainer *>(pTree->parentWidget()))
{
// setup a connection to process mode change
connect(action, &QAction::triggered, pView, &TreeViewContainer::onModeChanged);
}
}
// set the mode as data
action->setData(eMode);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T05:12:04.647",
"Id": "224596",
"Score": "1",
"Tags": [
"c++",
"gui",
"extension-methods",
"qt"
],
"Title": "Extensible tree header context menu"
}
|
224596
|
<blockquote>
<p>145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.</p>
<p>Find the sum of all numbers which are equal to the sum of the factorial of their digits.</p>
<p>Note: as 1! = 1 and 2! = 2 are not sums they are not included.</p>
</blockquote>
<pre><code>from time import time
def fact(n):
"""returns factorial of n."""
total = 1
for number in range(2, n + 1):
total *= number
return total
def fact_curious(n, factorials={1:1, 2:2}):
"""Assumes n is the range to check for curious numbers.
generates curious numbers within n range."""
for number in range(3, n):
try:
if sum(factorials[int(digit)] for digit in str(number)) == number:
yield number
except KeyError:
for digit in str(number):
factorials[int(digit)] = fact(int(digit))
if sum(factorials[int(digit)] for digit in str(number)) == number:
yield number
if __name__ == '__main__':
start_time1 = time()
print(sum(fact_curious(100000)))
print(f'Time: {time() - start_time1}')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T06:49:31.423",
"Id": "435654",
"Score": "3",
"body": "Please tag all Python questions with [tag:python], if you only have [tag:python-3.x] then your question is more likely to go unanswered."
}
] |
[
{
"body": "<ol>\n<li>There is <code>math.factorial</code> function. So no need to reinvent it.</li>\n<li>Using <code>try/except</code> for control flow is a bad practice. It's better to explicitly check whether a list contains a value using the condition <code>if int(digit) in factorials</code>. It also will eliminate the code duplication in <code>except</code> branch.</li>\n<li>It's even better to pre-calculate all factorials for digits from 0 to 9. Anyway, you will reuse them all a lot of times.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T07:37:59.977",
"Id": "224600",
"ParentId": "224598",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224600",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T06:17:36.783",
"Id": "224598",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler 34 # Digit Factorials in Python"
}
|
224598
|
<blockquote>
<p>The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.</p>
<p>There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.</p>
<p>How many circular primes are there below one million?</p>
</blockquote>
<p>Here's my implementation in Python 3. Awaiting feedback.</p>
<pre><code>from time import time
def is_prime(number):
"""returns True for a prime number, False otherwise."""
factor = 2
while factor * factor <= number:
if number % factor == 0:
return False
factor += 1
return True
def circulate(number):
"""returns all circulations of a number."""
for n in str(number):
if not int(n) % 2:
return False
circulations = []
digits = list(str(number))
for i in range(len(str(number))):
last = digits.pop()
circulations.append(last + ''.join(digits))
digits = [last] + digits
return [int(x) for x in circulations]
def circular_primes(limit):
"""returns all circular primes below limit."""
all_circulations = [2]
for num in range(3, limit, 2):
if is_prime(num):
check = 0
if circulate(num):
circulations = circulate(num)
for circulation in circulations:
if not is_prime(circulation):
check += 1
if not check:
all_circulations.extend(circulations)
return all_circulations
if __name__ == '__main__':
start_time = time()
print(len(set(circular_primes(200000))))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T13:04:39.727",
"Id": "435691",
"Score": "0",
"body": "@dariogithub Comments are for seeking clarification to the question, and may be deleted. Please put all suggestions for improvements in answers, even trivial ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:03:21.680",
"Id": "435793",
"Score": "1",
"body": "If you add the tag _beginner_ to your posts, reviewers should be aware of your lack of experience and should review your code from a different perspective: https://codereview.stackexchange.com/questions/tagged/beginner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:08:32.323",
"Id": "435794",
"Score": "1",
"body": "The problem is i got several consecutive unexplained downvotes for no apparent reasons, code does what it is created for in a timely manner and a downvote is misleading without a feedback. I'll add the tag in future posts anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:15:14.107",
"Id": "435795",
"Score": "3",
"body": "I noticed at one point you were asking question after question after question every 2 hours. And someone gently suggested you to take a little break :) Perhaps you should take a bit more time for each question, focus on quality rather than quantity. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:17:25.453",
"Id": "435796",
"Score": "0",
"body": "I think if there is a problem with quality, any suggestions will be appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:19:30.110",
"Id": "435797",
"Score": "3",
"body": "I found this post which might be interesting for you: https://codereview.meta.stackexchange.com/questions/590/is-it-okay-to-post-a-series-of-exercises-massively"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:06:54.080",
"Id": "435807",
"Score": "2",
"body": "One of the problems people may have with your questions, is you won't learn as much by rushing through the exercises and posting multiple on the same day. After all, you'll be making the same mistake over and over before it gets reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:18:08.027",
"Id": "435811",
"Score": "1",
"body": "I'll try to slow down my pace and take some time to review the feedbacks if any. Thank you for letting me know that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:45:25.717",
"Id": "435821",
"Score": "1",
"body": "@dfhwze Also possibly related: https://codereview.meta.stackexchange.com/questions/6050/is-code-ever-clean-enough-can-there-be-too-many-follow-up-questions"
}
] |
[
{
"body": "<p>Let's start with a quick analysis of your current algorithm. For each number less than <code>n</code> (<code>1000000</code> in your case) it does <code>sqrt(n)log(n)</code> operations (<code>sqrt</code> for <code>is_prime</code>*<code>log</code>cycles). However, some fairly simple things about this problem make it much easier to solve.</p>\n\n<p>As you probably know, any 2 digit or greater number ending in 2,4,6,8 or 5 is not prime since it is divisible by 2 or 5. Thus when constructing circular primes, you don't even have to check numbers that have these digits in them (and add 2 to the result for 2,5)</p>\n\n<p>Thus by changing the main bit of code to only generate reasonable candidates, you do significantly less work.</p>\n\n<pre><code>def digit_combinations(digit_list, n):\n if n == 1:\n for digit in digit_list:\n yield digit\n return\n for digit in digit_list:\n for part in digit_combinations(digit_list, n-1):\n yield digit + 10*part\n\n\ndef circular_primes(digits):\n if digits == 1:\n return 4 # 2,3,5,7\n\n all_circulations = [2,3,5,7]\n for i in range(2, digits):\n for num in digit_combinations((1,3,7,9), i):\n if is_prime(num):\n check = 0\n if circulate(num):\n circulations = circulate(num)\n for circulation in circulations:\n if not is_prime(circulation):\n check += 1\n if not check:\n all_circulations.extend(circulations)\n return all_circulations\n</code></pre>\n\n<p>By my timings, this code can return the 8 digit or less ones in 3 seconds, where yours took 7 seconds to do only up to 1 million.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:44:28.980",
"Id": "224673",
"ParentId": "224602",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224673",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T08:40:04.393",
"Id": "224602",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 35 Circular primes in Python"
}
|
224602
|
<p>I'm a C++ dev, and I've recently started working my way through <em>Clean Code</em>*. Whenever I encounter an example I think I could improve, I try to re-implement it in C++.</p>
<p>On pp. 28-29 there is an example with a message building class, which looks like this when implemented in C++ (includes and namespaces omitted):<br>
.h</p>
<blockquote>
<pre><code>class GuessStatisticsMessage
{
public:
GuessStatisticsMessage() = default;
~GuessStatisticsMessage() = default;
std::string make(char candidate, int count);
private:
void createPluralDependentMessageParts(int count);
void createThereAreManyLetters(int count);
void createThereIsOneLetter();
void createThereAreNoLetters();
std::string number;
std::string verb;
std::string pluralModifier;
};
</code></pre>
</blockquote>
<p>.cpp</p>
<blockquote>
<pre><code>std::string GuessStatisticsMessage::make(char candidate, int count)
{
createPluralDependentMessageParts(count);
return fmt::format("There {} {} {}{}", verb, number, candidate, pluralModifier);
}
void GuessStatisticsMessage::createPluralDependentMessageParts(int count)
{
if (count == 0) {
createThereAreNoLetters();
} else if (count == 1) {
createThereIsOneLetter();
} else {
createThereAreManyLetters(count);
}
}
void GuessStatisticsMessage::createThereAreManyLetters(int count)
{
verb = "are";
number = std::to_string(count);
pluralModifier = "s";
}
void GuessStatisticsMessage::createThereIsOneLetter()
{
verb = "is";
number = "one";
pluralModifier = "";
}
void GuessStatisticsMessage::createThereAreNoLetters()
{
verb = "are";
number = "no";
pluralModifier = "s";
}
</code></pre>
</blockquote>
<p>In an attempt to make this code more functional I ended up with the following:<br>
.h</p>
<pre><code>class GuessStatisticsMessageAlt
{
public:
GuessStatisticsMessageAlt() = default;
~GuessStatisticsMessageAlt() = default;
std::string make(char candidate, int count);
private:
struct MessageComponents
{
std::string verb;
std::string number;
std::string pluralModifier;
};
MessageComponents createPluralDependentMessageParts(int count);
MessageComponents createThereAreManyLetters(int count);
MessageComponents createThereIsOneLetter();
MessageComponents createThereAreNoLetters();
};
</code></pre>
<p>.cpp</p>
<pre><code>std::string GuessStatisticsMessageAlt::make(char candidate, int count)
{
auto messageComponents = createPluralDependentMessageParts(count);
return fmt::format("There {} {} {}{}", messageComponents.verb, messageComponents.number,
candidate, messageComponents.pluralModifier);
}
GuessStatisticsMessageAlt::MessageComponents GuessStatisticsMessageAlt::createPluralDependentMessageParts(int count)
{
if (count == 0) {
return createThereAreNoLetters();
} else if (count == 1) {
return createThereIsOneLetter();
} else {
return createThereAreManyLetters(count);
}
}
GuessStatisticsMessageAlt::MessageComponents GuessStatisticsMessageAlt::createThereAreManyLetters(int count)
{
return { "are", std::to_string(count), "s" };
}
GuessStatisticsMessageAlt::MessageComponents GuessStatisticsMessageAlt::createThereIsOneLetter()
{
return { "is", "one", "" };
}
GuessStatisticsMessageAlt::MessageComponents GuessStatisticsMessageAlt::createThereAreNoLetters()
{
return { "are", "no", "s" };
}
</code></pre>
<p>Since at this point there was no real need for a class, I continued, reaching the final result:<br>
.h</p>
<pre><code>std::string makeGuessStatisticsMessage(char candidate, int count);
</code></pre>
<p>.cpp</p>
<pre><code>namespace {
struct MessageComponents
{
std::string verb;
std::string number;
std::string pluralModifier;
};
MessageComponents createThereAreManyLetters(int count)
{
return { "are", std::to_string(count), "s" };
}
MessageComponents createThereIsOneLetter()
{
return { "is", "one", "" };
}
MessageComponents createThereAreNoLetters()
{
return { "are", "no", "s" };
}
MessageComponents createPluralDependentMessageParts(int count)
{
if (count == 0) {
return createThereAreNoLetters();
}
else if (count == 1) {
return createThereIsOneLetter();
}
else {
return createThereAreManyLetters(count);
}
}
}
std::string makeGuessStatisticsMessage(char candidate, int count)
{
auto messageComponents = createPluralDependentMessageParts(count);
return fmt::format("There {} {} {}{}", messageComponents.verb, messageComponents.number,
candidate, messageComponents.pluralModifier);
}
</code></pre>
<p>The point is, I grapple a bit with when to apply different programming paradigms and find it difficult to decide if my re-implementation is actually an improvement in this case. In particular, hiding so much stuff in the anonymous namespace is something that bothers me somewhat. </p>
<p>So the primary question is - is this really an improvement? And the secondary - how can I learn to judge this better?</p>
<p>I hope it isn't too opinion-based, as this is a real struggle for me.</p>
<hr>
<p>* <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>, Robert C. Martin</p>
|
[] |
[
{
"body": "<ul>\n<li><p>Getting rid of the class is definitely a step in the right direction.</p></li>\n<li><p>Assuming <code>count</code> can never be negative, we should use an <code>unsigned</code> integer type for it.</p></li>\n<li><p>I don't think the <code>MessageComponents</code> class is a good idea. It makes the design very inflexible. If we ever want to change the message, we'll have to change every single function there.</p></li>\n<li><p>We're programming a very specific output message, and the code doesn't seem to be intended for re-use, so I don't think we need the named functions either.</p></li>\n</ul>\n\n<hr>\n\n<p>I'd suggest something more like:</p>\n\n<pre><code>std::string makeStatisticsMessage(char letter, unsigned int count)\n{\n auto const verb = (count == 1) ? \"is\" : \"are\";\n auto const number = (count == 0) ? \"no\" : (count == 1) ? \"one\" : std::to_string(count);\n auto const plural = (count == 1) ? \"\" : \"s\";\n return fmt::format(\"There {} {} '{}'{}.\", verb, number, letter, plural);\n}\n</code></pre>\n\n<p>Although we now check <code>count</code> multiple times, I'd argue that it's much easier to follow the logic for each component separately.</p>\n\n<p>It also means that we can abstract or change the behavior for each component later (e.g. if we decide we want to print all the numbers as words instead of digits).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T12:15:08.397",
"Id": "435687",
"Score": "1",
"body": "One reason to use a class rather than a simple function could be a redesign to allow multiple languages for the output. In this case I would define a interface with a virtual function `makeStatisticsMessage()` and several inherited classes for the specific languages which should be supported."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T12:22:07.193",
"Id": "435688",
"Score": "4",
"body": "Also to enhance readability of your conditional logic, I'd recommend to avoid nested ternary operations in favor of `if` / `else` statements. The result would be the same and it's much better to follow for anyone (beginner or expert)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T18:19:58.097",
"Id": "435999",
"Score": "0",
"body": "I've accepted this answer since the other one builds on it. Both of them were helpful, though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T11:25:09.603",
"Id": "224610",
"ParentId": "224603",
"Score": "10"
}
},
{
"body": "<p>While I am supporting <a href=\"https://codereview.stackexchange.com/a/224610/52802\">@user673679's approach</a> a lot in terms that putting everything into a single function, I still have concerns:</p>\n\n<ol>\n<li><p>Using an interface might be better if you want to refactor the functionality to support multiple languages:</p>\n\n<pre><code>struct IGuessStatisticsMessage {\n virtual std::string makeStatisticsMessage(char letter, unsigned int count) = 0;\nvirtual ~IGuessStatisticsMessage() {}\n};\n</code></pre>\n\n<p>This would allow to provide implementations for different languages easier:</p>\n\n<pre><code>struct GuessStatisticsMessage_EN() : public IGuessStatisticsMessage {\n std::string makeStatisticsMessage(char letter, unsigned int count) {\n auto const verb = (count == 1) ? \"is\" : \"are\";\n auto const number = (count == 0) ? \"no\" : (count == 1) ? \"one\" : \n std::to_string(count);\n auto const plural = (count == 1) ? \"\" : \"s\";\n return fmt::format(\"There {} {} '{}'{}.\", verb, number, letter, plural);\n } \n};\n\nstruct GuessStatisticsMessage_DE() : public IGuessStatisticsMessage {\n std::string makeStatisticsMessage(char letter, unsigned int count) {\n auto const number = (count == 0) ? \"kein\" : (count == 1) ? \"ein\" : \n std::to_string(count);\n auto const plural = (count == 1) ? \"\" : \"s\";\n return fmt::format(\"Es gibt {} '{}'{}.\", number, letter, plural);\n } \n};\n</code></pre></li>\n<li><p>Also I am not a friend of nested ternary expressions, they generally tend to be hard to read. I'd rather use some code like this:</p>\n\n<pre><code>std::string makeStatisticsMessage(char letter, unsigned int count) {\n auto const verb = (count == 1) ? \"is\" : \"are\";\n std::string number;\n if(count == 0) { \n number = \"no\";\n else if (count == 1) { \n number = \"one\";\n }\n else { \n number = std::to_string(count);\n }\n auto const plural = (count == 1) ? \"\" : \"s\";\n return fmt::format(\"There {} {} '{}'{}.\", verb, number, letter, plural);\n} \n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T18:16:36.753",
"Id": "435998",
"Score": "0",
"body": "Thanks for the contribution. Would it make sense to go a step further by getting rid of the `verb`/`number`/`plural` vars altogether and returning a complete string depending on the `count` (having multiple `return` statements), or would you insist on keeping the vars?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T18:21:45.983",
"Id": "436000",
"Score": "0",
"body": "@SG_90 The (local) variables are a minor point. Keeping a replacable interface is a major."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T13:00:34.343",
"Id": "224614",
"ParentId": "224603",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "224610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T09:48:12.300",
"Id": "224603",
"Score": "15",
"Tags": [
"c++",
"object-oriented",
"functional-programming",
"comparative-review",
"formatting"
],
"Title": "Message-formatting code with pluralization, revised to be more functional"
}
|
224603
|
<p>I am very new to concurrent programming in general and want to know if my implementation is thread-safe. </p>
<p>I'm currently working on implementing a TCP client in golang. The service listens on a port and accepts HTTP requests. On a parallel, the service also establishes a connection to an outside TCP server to which it will send binary data.</p>
<p>While I got this to work, I'm unsure if this is the correct approach or should I be adding something more.</p>
<p>The sequence of steps is this</p>
<p>I start my webserver which first tries to establish a connection with a TCP server. On a successful connection, I start listening for incoming HTTP requests</p>
<p><em>note</em>: Successful connection to the TCP server involves me sending a <code>login</code> packet to this TCP server which authenticates me</p>
<pre><code>type TCPconnector struct {
Conn net.Conn
DataChannel chan []byte
reconnectAttempt int
reconnectMaxRetries int
reconnectMaxDelay time.Duration
autoReconnect bool
lastOrderSent time.Time
}
const addr string = "xx.xx.xx.xx"
const defaultReconnectMaxAttempts int = 10
const defaultReconnectMaxDelay time.Duration = 60000 * time.Millisecond
func NewTCPConnector() (*TCPconnector, error) {
dataChannel := make(chan []byte)
return &TCPconnector{
DataChannel: dataChannel,
reconnectMaxDelay: defaultReconnectMaxDelay,
reconnectMaxRetries: defaultReconnectMaxAttempts,
reconnectAttempt: 0,
autoReconnect: true,
}, nil
}
func Server() {
TCPconnector, err := NewTCPConnector()
if err != nil {
fmt.Println("error")
}
err = TCPconnector.Connect()
if err != nil {
fmt.Println("error")
}
defer TCPconnector.Conn.Close()
r := chi.NewRouter()
r.Post("/placeOrder", PlaceOrder(TCPconnector))
err = http.ListenAndServe(":8080", r)
}
</code></pre>
<p>The connect method tries to establish a connection to the TCP server and responsible to spawning goroutines responsible for writing packets, sending heartbeat packets and reading responses from the server.</p>
<pre><code> func (t *TcpConnector) Connect() {
for {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if t.reconnectAttempt > t.reconnectMaxRetries {
t.onNoReconnect(t.reconnectAttempt)
return
}
if t.reconnectAttempt > 0 {
t.onReconnect()
}
c, err := net.Dial("tcp", t.Url)
if err != nil {
t.AppState.Log.Errorf("Connection to tcp server failed with error : %+v", err)
if t.autoReconnect {
t.reconnectAttempt++
continue
}
return
}
t.Log.Infof("Connection established @ %s", time.Now())
t.Conn = c
defer t.Conn.Close()
var wg sync.WaitGroup
wg.Add(1)
go t.SendHeartbeat(ctx)
go t.Write(&wg, cancel)
go t.RecieveResponse()
err = t.SendLoginPacket()
if err != nil {
continue
}
wg.Wait()
}
}
</code></pre>
<p>The sendLoginPacket is pretty straightforward, we form the packet and sends it across the DataChannel which is then picked up by the Write goroutine</p>
<pre><code>func (t *TcpConnector) SendLoginPacket() error {
loginRequestBody := dto.LoginRequest{
VersionNo: 24,
}
finalPacketToBeSent, err := t.getFinalPacketToBeSent(1, loginRequestBody)
if err != nil {
return err
}
t.DataChannel <- finalPacketToBeSentToMOSL
return nil
}
</code></pre>
<p>The Write() goroutine works like this</p>
<pre><code>func (t *TcpConnector) Write(wg *sync.WaitGroup, cancel context.CancelFunc) {
for {
select {
case data := <-t.DataChannel:
_, err := t.Conn.Write(data)
if err != nil {
t.Conn.Close()
wg.Done()
cancel()
return
}
}
}
}
</code></pre>
<p>The <code>Recieve</code> goroutine is also a straightforward loop that returns on any error</p>
<pre><code>func (t *TcpConnector) RecieveResponse() {
for {
// Get the first 45 bytes of the response and check the messageLength for the remaining length of the message
headerBuff := make([]byte, 45)
_, err := t.Conn.Read(headerBuff)
if err != nil {
t.AppState.Log.Errorf("Couldnt read tcp header response from MOSL : %+v ", err)
return
}
headerResponse := dto.MessageHeader{}
err = binary.Read(bytes.NewReader(headerBuff), binary.LittleEndian, &headerResponse)
if err != nil {
t.AppState.Log.Errorf("Couldnt convert bytes header to struct : %+v ", err)
return
}
// Get remaining bytes from server and decrypt it (remaining bytes = messageLength - 45 bytes for the header)
bodyBuff := make([]byte, headerResponse.MessageLength-45)
_, err = t.Conn.Read(bodyBuff)
if err != nil {
t.AppState.Log.Errorf("Couldnt read tcp body response from MOSL : %+v ", err)
return
}
decryptedResponseBody, err := DecryptAESCFB(bodyBuff, t.Key, t.IV)
if err != nil {
t.AppState.Log.Errorf("Couldnt decrypt body response from MOSL : %+v ", err)
return
}
go t.handleMOSLResponse(headerResponse, decryptedResponseBody)
}
}
</code></pre>
<p>And lastly, the heartbeat request which is fired every 30 seconds to the TCP server</p>
<pre><code>func (t *TcpConnector) SendHeartbeat(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case x := <-ticker.C:
messageHeader, err := getMessageHeaderInBytes(129, 0, 0, t.AppState.Config.Username)
if err != nil {
t.AppState.Log.Errorf("Error Converting heartbeat request data to bytes: %+v, with seconds: %s", err, x)
return
}
t.DataChannel <- messageHeader
case <-ctx.Done():
fmt.Println("Exiting hearbeat goroutine")
return
}
}
}
</code></pre>
<p>My main concern over this implementation is if i'm handling the error cases well?</p>
<ol>
<li>Are my goroutines being shutdown properly in case the TCP server closes the connection?</li>
<li>Is there a better way to start and stop the goroutines?</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T10:17:41.307",
"Id": "224605",
"Score": "6",
"Tags": [
"go",
"tcp"
],
"Title": "Implementing a TCP client in Golang"
}
|
224605
|
<blockquote>
<p>The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.</p>
<p>Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.</p>
<p>(Please note that the palindromic number, in either base, may not include leading zeros.)</p>
</blockquote>
<p>Awaiting feedback.</p>
<pre><code>def is_palindrome(n):
"""returns True if palindrome, False otherwise."""
to_str = str(n)
if to_str == to_str[::-1]:
return True
return False
def find_palindromes(n):
"""generates all numbers if palindrome in both bases 2, 10 in range n. """
decimal_binary = {decimal: bin(decimal)[2:] for decimal in range(1, n) if is_palindrome(decimal)}
for decimal, binary in decimal_binary.items():
if is_palindrome(binary) and not binary[0] == 0:
yield decimal
if __name__ == '__main__':
print(sum(list(find_palindromes(1000000))))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T11:05:38.043",
"Id": "435675",
"Score": "3",
"body": "Can you add the correct tags, as I requested in one of your previous questions. You may want to reduce the amount of questions you're posting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T11:25:37.027",
"Id": "435682",
"Score": "0",
"body": "there is a problem with the tags, I usually tag something such as 'python3.x' or whatever and I end up getting less tags. Anyway the 'python3.x' is checked what's wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T11:26:32.497",
"Id": "435683",
"Score": "1",
"body": "https://codereview.stackexchange.com/questions/224598/project-euler-34-digit-factorials-in-python#comment435654_224598"
}
] |
[
{
"body": "<p><strong>Code review</strong></p>\n\n<ul>\n<li><p>The sequence of</p>\n\n<pre><code> if condition:\n return True\n return False\n</code></pre>\n\n<p>is a long way to say</p>\n\n<pre><code> return condition\n</code></pre>\n\n<p>Consider instead</p>\n\n<pre><code>def is_palindrome(n):\n return to_str == to_str[::-1]:\n</code></pre></li>\n<li><p>Generator vs list.</p>\n\n<p>A list takes space. The entire point of a generator is to <em>not</em> take space. Your <code>find_palindrome</code> does <code>yield</code>, that is produces one palindrome at a time. Very well suited to sum them as they are produced. Your code collects them all in a list for no reason.</p>\n\n<p>Even more curious is that your code</p>\n\n<ul>\n<li>builds a dictionary</li>\n<li>then yields each entry</li>\n<li>to build the list</li>\n<li>which is sent to <code>sum</code> to traverse it.</li>\n</ul>\n\n<p>I see at least 4 traversals over the same data. Seems excessive.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Efficiency</strong></p>\n\n<p>Thou shalt not brute force.</p>\n\n<p>There are just 1000 decimal palindromes below 1000000: they are all in form <code>abccba</code>. In fact, we are not interested in all of them: if <code>a</code> is even, the binary representation would have a trailing 0, and to be a palindrome it would have a leading 0 as well. We may immediately disqualify such numbers. What remains, is just 500 candidates.</p>\n\n<p>So, we only need to iterate over 500 numbers, instead of 1000000 your code does. A 2000-fold speedup, immediately. In fact, a bit more, because there is no need to test wether a decimal representation is a palindrome anymore, and such test is quite expensive. There is also no need to test for the parity, but it is peanuts.</p>\n\n<p>The fun part is to design test that the binary representation is palindromic. The usually recommended</p>\n\n<pre><code> binary = bin(n)\n return binary == binary[-1:1:-1]\n</code></pre>\n\n<p>works well <em>in general</em>. In this particular setting you know <strong>a lot</strong> about the numbers and their binary representation (at the very least you know how many bits the number takes), and there are few more performant solutions.</p>\n\n<hr>\n\n<p><strong>Rant</strong></p>\n\n<p>Please keep in mind that solving Project Euler problems will not make you a better programmer. Project Euler is designed for programmers striving to be better mathematicians.</p>\n\n<p>And no matter what, do not brute force.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:41:12.647",
"Id": "435736",
"Score": "0",
"body": "And what do you suggest for improving my programming skills other than project Euler given that 2 months ago i didn't know what programming is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:53:57.513",
"Id": "435739",
"Score": "0",
"body": "@emadboctor It is a huge question you ask. An obvious - and very vague - answer is to sign up to some class, pick a teacher, and study. Just as you'd study for an artist, a doctor, or a lawyer. Studying solo is a recipe to failure. Consider asking at [CS educators](https://cseducators.stackexchange.com)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:32:31.967",
"Id": "224634",
"ParentId": "224607",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224634",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T10:41:58.233",
"Id": "224607",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 36 Double-base palindromes in Python"
}
|
224607
|
<p>It's a task from a Ruby-course, in which I'm currently enrolled:
<a href="https://open.hpi.de/courses/ruby2018/items/5AKyBqWnJw9dLP7xQdImmj" rel="nofollow noreferrer">Ruby Course - Page</a></p>
<p>Precisely it's one of the assignments for the first week.</p>
<p>Following idea:
Your are given a list in which finished work-tasks are logged.
<code>[
{work: "item 1", date: "2017-04-26", time: 20},
{work: "item 2", date: "2017-04-27", time: 27},
...</code></p>
<p>You shall write a function which computes the daily work-time for the different months.
Means: The average daily work-time in April, avg. time in May, ... in June. And so on ...</p>
<p>A data-structure, to work upon, was given. Even the result, which is expected for that data-structure: <code>{ "2017-04" => 40, "2017-05" => 14 }</code>.</p>
<p>I was able to write a function, which passed all unit-tests.
Here it is:</p>
<pre><code>#!/usr/bin/ruby
tasks = [
{work: "item 1", date: "2017-04-26", time: 20},
{work: "item 2", date: "2017-04-27", time: 27},
{work: "item 3", date: "2017-04-27", time: 33},
{work: "item 4", date: "2017-05-05", time: 20},
{work: "item 5", date: "2017-05-06", time: 12},
{work: "item 6", date: "2017-05-14", time: 10},
]
# Expected result : { "2017-04" => 40, "2017-05" => 14 }
def work_per_month(tasks)
days_aggregate = {}
tasks.each do | task |
key = task[:date]
if days_aggregate.key?(key)
days_aggregate[key][0] = days_aggregate[key][0] + task[:time]
else
arr = []
arr[0] = task[:time]
days_aggregate[key] = arr
end
end
months_aggregate = {}
days_aggregate.each do | key, task |
parts = key.split("-")
k = "#{parts[0]}-#{parts[1]}"
if months_aggregate.key?(k)
months_aggregate[k][0] = months_aggregate[k][0] + task[0]
months_aggregate[k][1] = months_aggregate[k][1] + 1
else
arr = []
arr[0] = task[0]
arr[1] = 1
months_aggregate[k] = arr
end
end
avg_hours_month = {}
months_aggregate.each do | key, data |
avg_hours_month[key] = data[0] / data[1]
end
avg_hours_month
end
puts work_per_month(tasks) # Returns {"2017-04"=>40, "2017-05"=>14}
</code></pre>
<p>Please take into account that I started Ruby programming just a week ago.</p>
<p>It works and it has passed the tests. But I'm aware that it is clumsy.</p>
<p><strong>Is there are more elegant way to solve the described task?</strong></p>
<p>Without having this sequence of loops? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:13:26.157",
"Id": "447957",
"Score": "0",
"body": "The example result seems wrong: the average of `(20 + 27 + 33) / 3` is `26.666..`, not `40`. Now, I don't know about elegant, especially for the first week (!), but `tasks.group_by {|h| h[:date][0..6]}.reduce({}) {|out, (k, v)| out[k] = v.reduce(0.0) {|sum, h| sum + h[:time] } / v.size; out}` should do it as a one-liner. Not that it should be a one-liner, reason here is just so it fits in a comment box."
}
] |
[
{
"body": "<h2>Rubocop Report</h2>\n\n<p><a href=\"https://github.com/rubocop-hq/rubocop\" rel=\"nofollow noreferrer\">Rubocop</a> was able to solve minor layout issues regarding the use of white spaces. One note-worthy change it proposed is:</p>\n\n<ul>\n<li>[Corrected] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.</li>\n</ul>\n\n<blockquote>\n<pre><code>days_aggregate.each do | key, task |\n parts = key.split(\"-\")\n</code></pre>\n</blockquote>\n\n<pre><code> parts = key.split('-')\n</code></pre>\n\n<p>A bigger complexity issue it found was:</p>\n\n<ul>\n<li>Metrics/AbcSize: Assignment Branch Condition size for work_per_month is too high. [33/15]</li>\n<li>Metrics/MethodLength: Method has too many lines. [30/10]</li>\n</ul>\n\n<p>This means your method <code>work_per_month</code> is doing way too much. It has more than double the <a href=\"https://www.rubydoc.info/gems/rubocop/0.27.0/RuboCop/Cop/Metrics/AbcSize\" rel=\"nofollow noreferrer\">AbcSize</a> than the suggested threshold <code>[33/15]</code>. You should split this method in sub-routines.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T12:03:22.693",
"Id": "435685",
"Score": "0",
"body": "Thanks a lot for your answer. You are of course right. 41 lines is indeed too much. Normally it should be 30 lines maximal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T12:05:20.847",
"Id": "435686",
"Score": "0",
"body": "The default is set even lower than 30: it's 10 https://rubocop.readthedocs.io/en/latest/cops_metrics/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T11:52:48.733",
"Id": "224612",
"ParentId": "224608",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224612",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T11:20:25.020",
"Id": "224608",
"Score": "2",
"Tags": [
"beginner",
"ruby",
"statistics"
],
"Title": "Statistical function which computes the average work time in different months"
}
|
224608
|
<p>I need to make an unknown number of api calls, up to 5 max probably. But most samples I've seen show only a couple of async calls so are effectively hard coded to the number of calls being made.</p>
<p>This is what I came up with as a demonstration, it has an array with three sleep times in it to simulate an API call of variable duration. The main function should wait until all three calls are finished. </p>
<p>It works but is this the right way to go about it?</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 sleep = async(milliseconds) => {
await sleepMain(milliseconds);
console.log(`Awake: ${milliseconds}`);
let value = {
sleep: milliseconds
};
return value;
}
const sleepMain = (milliseconds) => {
console.log(`Sleeping ${milliseconds}`)
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const asyncTest = async() => {
arrayTest = [1000, 3000, 5000];
arrayTestResult = Array();
arrayTest.forEach(function(element) {
console.log('Start Sleep: ' + element);
arrayTestResult.push(sleep(element));
});
const syncThing = await Promise.all(arrayTestResult);
console.log(syncThing);
return syncThing;
}
const main = async() => {
console.log('Start Main');
document.getElementById('message').innerHTML = 'Running...';
await asyncTest();
console.log('Finish Main');
document.getElementById('message').innerHTML = 'Finished - See Console Log';
}
main();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Multi Thread Async Test</h1>
<p>Runs the array of sleep lengths (in async) and completes when all done</p>
<p>sleep and sleepMain are used to simulate an API call of variable response time</p>
<h2 id='message'></h2></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/kanineAU/yv21Leqf/" rel="nofollow noreferrer">https://jsfiddle.net/kanineAU/yv21Leqf/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T12:24:05.850",
"Id": "435676",
"Score": "0",
"body": "Side note: You can't do multi-threading in JS environments. What you're doing here is parallel async calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T12:32:30.743",
"Id": "435677",
"Score": "3",
"body": "Passing array of promises to Promise.all() is quite common...yes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T12:52:31.427",
"Id": "435678",
"Score": "0",
"body": "Title edited to avoid confusion relating to the definition of multi-threading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T12:55:35.813",
"Id": "435679",
"Score": "0",
"body": "can use `async.queue` if you want (and like the `async` library)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T13:19:03.693",
"Id": "435680",
"Score": "0",
"body": "It's fine to use Promise.all(), but if you have \"unknown\" number of API calls, you may not want to run them all in parallel. If you only want to have e.g. 2 running at once, but queue them all up at the same time, look into the `async` library's `queue`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T14:16:49.870",
"Id": "435681",
"Score": "0",
"body": "Using the `Array()` constructor, a `forEach` loop and `push` is a bit weird - you should just have used `map`. But the usage of `await` and `Promise.all` is really fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T15:50:00.687",
"Id": "435708",
"Score": "0",
"body": "@NikKyriakides You can do multi threading in JS environments using webWorkers https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T17:52:54.863",
"Id": "435718",
"Score": "0",
"body": "@Blindman67 That's *multiprocessing* not multithreading. Multithreading implies shared memory, which WebWorkers don't allow (you can only copy and send messages back and forth). WebWorker contexts are isolated, separate processes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T18:50:13.103",
"Id": "435722",
"Score": "2",
"body": "@NikKyriakides SharedArrayBuffers provide shared memory across workers. https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T18:51:40.740",
"Id": "435723",
"Score": "1",
"body": "@Blindman67 I stand corrected"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T12:20:19.570",
"Id": "224609",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"async-await"
],
"Title": "Example Multiple Async Await Calls Javascript"
}
|
224609
|
<p>As you probably know, Python slices like <code>arr[1:3]</code> etc. do NOT provide a view onto list and instead creates a copy of the list, what can be not optimal performance if array is big and you make for example <code>arr[1:]</code> (copies all exept first)
the idea of a view to an array is like :</p>
<pre><code>class ylist_view():
def __init__(self,lst, begin, end):
self.list = lst
self.len = end - begin
self.begin = begin
self.end = end
def __getitem__(self, i):
if i<0: i += self.len
return self.list[self.begin + i]
def __setitem__(self, i,value):
if i<0: i += self.len
self.list[self.begin + i] = value
def __str__(self):
return '[' + ', '.join( str(self.list[i]) for i in range(self.begin, self.end)) + ']'
class inbox():
def __init__(self, value):
self.value = value
def __str__(self):
return '<' + str(self.value) + '>'
def __repr__(self):
return '<' + str(self.value) + '>'
a = [ inbox(x) for x in [1,2,3,4,5]]
b = a [1:3]
b[0] = 20 # creates a copy
print('list a is unchanged:', a)
print('b = a [1:3] is a copy of a :', b)
c = ylist_view(a,1,3)
c[0] = 20
print('ylist_view c is a view to a:', a)
</code></pre>
<p>Inbox class is a dummy class for illustration.
As you can see, <code>b = a [1:3]</code> is a copy, whereas <code>c = ylist_view(a,1,3)</code> references the original array.
Does it make sense to use this approach in a real Python project or there is some built-in in Python to do that?</p>
|
[] |
[
{
"body": "<p>If you are dealing with number lists, then <a href=\"https://docs.python.org/3/library/array.html#array.array\" rel=\"nofollow noreferrer\"><code>array.array</code></a> has a compact memory representation and implements the buffer protocol which allows <a href=\"https://docs.python.org/3/library/stdtypes.html#memoryview\" rel=\"nofollow noreferrer\"><code>memoryview</code></a>’s to be created, which directly support views like you are creating.</p>\n\n<p>For lists which can hold other things (tuples, dictionaries, lambdas, ...), Python has no built in support, and your view class can be appropriate.</p>\n\n<hr>\n\n<h2>PEP8 guidelines</h2>\n\n<p>Your class name should begin with a capital letter. I’d suggest <code>ListView</code> as an option. I don’t know what the ‘y’ is intended to mean.</p>\n\n<p>There should be one space after every comma. There shouldn’t be any spaces between a variable name and the <code>[</code> character (<code>b = a[1:3]</code>).</p>\n\n<p>Private members (<code>self.begin</code>, etc) should begin with an underscore (<code>self._begin</code>, etc).</p>\n\n<p>Use a pylint, pyflakes, ... to ensure PEP8 compliance. </p>\n\n<hr>\n\n<p>You could implement <code>__repr__</code> in terms of <code>__str__</code>:</p>\n\n<pre><code> def __repr__(self):\n return str(self)\n</code></pre>\n\n<hr>\n\n<p>Extension: Your list view could support a view slice with a step size other than <code>1</code>.</p>\n\n<hr>\n\n<p>You don’t protect against indexing beyond the length of your view. <code>i >= self.len</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T17:24:18.017",
"Id": "435716",
"Score": "0",
"body": "thanks got guidelines, its just a dummy example. but are you sure its good to use camel notation in python? 'y' just stand for m'y' i mark own utils with that.\n\nYou could implement __repr__ in terms of __str__: -< YES\nExtension: Your list view could support a view slice with a step size other than 1. <- YES, also 2d view may be possible\n\nYou don’t protect against indexing beyond the length of your view <- i would say it should be allowed, i dont want extra check and then python list make anotehr check.\nalso"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T18:51:59.260",
"Id": "435724",
"Score": "0",
"body": "`CapWord` is good for type names; `snake_case` is preferred for methods & variable names. Accessing the 10th element of a view of length 5 is a logical error, even if the backing list contains that element."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T16:14:13.567",
"Id": "224619",
"ParentId": "224613",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "224619",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T12:39:39.487",
"Id": "224613",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"design-patterns"
],
"Title": "A view for Python list slices"
}
|
224613
|
<blockquote>
<p><a href="https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays" rel="nofollow noreferrer">Problem Statement:</a></p>
<p>Given a <strong>6×6</strong> 2D Array, <strong>arr</strong>:</p>
<pre><code>1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
</code></pre>
<p>We define an hourglass in <strong>A</strong> to be a subset of values with indices
falling in this pattern in <strong>arr</strong>'s graphical representation:</p>
<pre><code>a b c
d
e f g
</code></pre>
<p>There are <strong>16</strong> hourglasses in <strong>arr</strong>, and an hourglass sum is the
sum of an hourglass' values. Calculate the hourglass sum for every
hourglass in <strong>arr</strong>, then print the maximum hourglass sum.</p>
<p>For example, given the 2D array:</p>
<pre><code>-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3
0 0 8 6 6 0
0 0 0 -2 0 0
0 0 1 2 4 0
</code></pre>
<p>We calculate the following <strong>16</strong> hourglass values:</p>
<pre><code>-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18
</code></pre>
<p>Our highest hourglass value is <strong>28</strong> from the hourglass:</p>
<pre><code>0 4 3
1
8 6 6
</code></pre>
<p>Note: If you have already solved the Java domain's Java 2D Array
challenge, you may wish to skip this challenge.</p>
<p><strong>Function Description</strong></p>
<p>Complete the function hourglassSum in the editor below. It should
return an integer, the maximum hourglass sum in the array.</p>
<p>hourglassSum has the following parameter(s):</p>
<ul>
<li>arr: an array of integers</li>
</ul>
<p><strong>Sample Input</strong></p>
<pre><code>1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>19
</code></pre>
<p><strong>Explanation</strong></p>
<p><strong>arr</strong> contains the following hourglasses:</p>
<p><img src="https://i.stack.imgur.com/pZBUR.png" alt="Preview" /></p>
<p>The hourglass with the maximum sum (19) is:</p>
<pre><code>2 4 4
2
1 2 4
</code></pre>
</blockquote>
<p><strong>Following is my imperative style Solution:</strong></p>
<pre><code>def hourglassSum(arr: Array[Array[Int]]): Int = {
def sum(rowNumber: Int, columnNumber: Int): Int = {
var oneHourglassSum = 0
for {
i <- 0 to 2
j <- 0 to 2
} yield {
val cumulativeSum = if (i == 1 && (j == 0 || j == 2)) 0
else arr(i + rowNumber)(j + columnNumber)
oneHourglassSum += cumulativeSum
}
oneHourglassSum
}
def max(x: Int, y: Int): Int = if (x > y) x else y
var hourglassMaxSum = 0
for {
rowOffset <- 0 to 3
columnOffset <- 0 to 3
} yield {
hourglassMaxSum = max(sum(rowOffset, columnOffset), hourglassMaxSum)
}
hourglassMaxSum
}
</code></pre>
|
[] |
[
{
"body": "<p>There's no need to write a <code>max()</code> method. The Standard Library provides for that.</p>\n\n<p>A <code>for</code> comprehension, with a <code>yield</code> clause, produces a result. So instead of using a mutable <code>var</code> to capture and collect the results of the <code>yield</code> you should capture them directly.</p>\n\n<pre><code>val res = for {...} yield {...}\n</code></pre>\n\n<p>Or, if you want to process the results more directly, i.e. without the intermediate variable, you can use the somewhat awkward parentheses construct.</p>\n\n<pre><code>def hourglassSum(arr: Array[Array[Int]]): Int = {\n (for {\n x <- 0 to 3\n y <- 0 to 3\n } yield {\n arr(y)(x) + arr(y)(x+1) + arr(y)(x+2) +\n arr(y+1)(x+1) +\n arr(y+2)(x) + arr(y+2)(x+1) + arr(y+2)(x+2)\n }).max\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T06:05:09.997",
"Id": "224652",
"ParentId": "224616",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224652",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T15:34:30.473",
"Id": "224616",
"Score": "0",
"Tags": [
"programming-challenge",
"functional-programming",
"scala"
],
"Title": "Provide functional-programming style solution for 2D Array - DS challenge"
}
|
224616
|
<p>I have a system that stores resources. A resource contains a string that represents a user role, for example "3".
With this user role "3", you can retrieve a list of permissions for the user role, for example ["1", "2", "3"]. This list represents actions a user can perform (1 = read, 2 = write, etc). </p>
<p>So given user role "3", you know you can perform action "1", "2" and "3". </p>
<p>The problem: Users in my system do not directly store a security level number. They only store the actions they are allowed to perform. Given a set of allowed actions, I need to find the correct user role. This part of the code gets used a LOT, so I have to create a solution that works quick and efficiently. </p>
<p>My solution: create an unbalanced search tree and navigate through it to get the correct security level for a set of permissions. </p>
<p>Overview: for three sets of permissions: </p>
<ul>
<li>[ "1", "2", "3", "4" ] level 1</li>
<li>[ "1", "2", "3", "5" ] level 2</li>
<li>["6", "8", "10", "11" ] level 3 </li>
<li>[ "2", "1" ] level 4</li>
</ul>
<p>Create a tree that looks like this:
<a href="https://i.stack.imgur.com/Zj9tm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zj9tm.png" alt="enter image description here"></a></p>
<p>Then given an array [ "6", "8", "10", "11" ], create a function that returns "3", or "-1" if no corresponding level was found. The search tree is cached, so creating it does not have to be very efficient. Searching it however should be quick. My code:</p>
<pre><code> Public class TreeSearcher
{
private static Dictionary<string, SearchTree> documentSearchTrees = new Dictionary<string, SearchTree>();
/// <summary>
/// Create a search tree for a document type's different rights levels.
/// </summary>
/// <param name="documentType">The documenttype</param>
/// <param name="documentRights">A tuple holding an int (rights level), and a string[] (the rights)</param>
public static void CreateSearchTree(string documentType, params Tuple<int, string[]>[] documentRights)
{
if (string.IsNullOrEmpty(documentType))
throw new ArgumentNullException(nameof(documentType), $"{nameof(documentType)} can not be null.");
if (documentRights?.Length == 0)
throw new ArgumentNullException(nameof(documentRights), $"{nameof(documentRights)} can not be null or empty.");
// Only insert rights if they haven't been inserted before.
// Use the DeleteSearchTree(documentType) method to explicitly remove document rights.
if (documentSearchTrees.ContainsKey(documentType) == false)
{
SearchTree searchTree = new SearchTree();
foreach (var rights in documentRights)
{
searchTree.AddNode(rights.Item1, rights.Item2);
}
documentSearchTrees.Add(documentType, searchTree);
}
}
/// <summary>
/// Returns the level of a passed in array of user rights.
/// </summary>
/// <param name="documentType">The type of document to compare the user rights for.</param>
/// <param name="userRights">The rights of the user.</param>
/// <returns>The authorization level for the user, or -1 if none was found.</returns>
public static int GetAuthorizationLevel(string documentType, string[] userRights)
{
Array.Sort(userRights);
if (documentSearchTrees.TryGetValue(documentType, out var searchTree) == true)
{
return searchTree.GetAuthorizationLevel(userRights);
}
else
{
return -1;
}
}
/// <summary>
/// Delete a document type's searchTree.
/// </summary>
/// <param name="documentType"></param>
public static void DeleteSearchTree(string documentType)
{
if (string.IsNullOrEmpty(documentType))
throw new ArgumentNullException(nameof(documentType), $"{nameof(documentType)} can not be null.");
documentSearchTrees.Remove(documentType);
}
/// <summary>
/// The entire search tree.
/// </summary>
private class SearchTree
{
private Dictionary<string, TreeNode> Nodes = new Dictionary<string, TreeNode>();
internal void AddNode(int authorizationLevel, string[] rights)
{
// We need the rights to be sorted, otherwise the tree will not work.
Array.Sort(rights);
// Add the nodes recursively.
if (Nodes.TryGetValue(rights[0].ToString(), out TreeNode nodeToAdd) == false)
{
nodeToAdd = new TreeNode(authorizationLevel, rights.Skip(1).ToArray());
Nodes.Add(rights[0].ToString(), nodeToAdd);
}
else
{
nodeToAdd.AddNode(authorizationLevel, rights.Skip(1).ToArray(), new TreeNode(authorizationLevel, rights.Skip(1).ToArray()));
}
}
internal int GetAuthorizationLevel(string[] userRights)
{
int arrayStartPosition = 0;
if (Nodes.TryGetValue(userRights[arrayStartPosition], out var treeNode) == true)
{
return treeNode.GetAuthorizationLevel(userRights, arrayStartPosition + 1);
}
else
{
return -1;
}
}
}
/// <summary>
/// A single node with all sub-nodes of the tree.
/// </summary>
private class TreeNode
{
private Dictionary<string, TreeNode> Nodes = new Dictionary<string, TreeNode>();
internal int AuthorizationLevel { get; set; }
internal TreeNode(int authorizationLevel, string[] rights)
{
if (rights.Length <= 0)
{
AuthorizationLevel = authorizationLevel;
return;
}
if (Nodes.TryGetValue(rights[0].ToString(), out TreeNode existingNode) == false)
{
if (rights.Length == 1)
AuthorizationLevel = authorizationLevel;
existingNode = new TreeNode(authorizationLevel, rights.Skip(1).ToArray());
Nodes.Add(rights[0].ToString(), existingNode);
}
else
{
existingNode.AddNode(authorizationLevel, rights, new TreeNode(authorizationLevel, rights.ToArray()));
}
}
internal void AddNode(int authorizationLevel, string[] rights, TreeNode treeNode)
{
if (rights.Length <= 0)
{
return;
}
if (rights.Length == 1)
{
treeNode.AuthorizationLevel = authorizationLevel;
}
if (Nodes.TryGetValue(rights[0].ToString(), out TreeNode existingNode) == false)
{
Nodes.Add(rights[0].ToString(), treeNode);
}
else
{
existingNode.AddNode(authorizationLevel, rights.Skip(1).ToArray(), treeNode);
}
}
internal int GetAuthorizationLevel(string[] userRights, int offset)
{
if (userRights.Length == offset)
return AuthorizationLevel;
if (Nodes.TryGetValue(userRights[offset], out var treeNode) == true)
{
return treeNode.GetAuthorizationLevel(userRights, offset + 1);
}
else
{
return -1;
}
}
}
}
</code></pre>
<p>Adding permissions per resource type works like this:</p>
<pre><code> var list = new List<Tuple<int, string[]>>
{
new Tuple<int, string[]>(1, new string[] { "1", "2", "3", "4" }),
new Tuple<int, string[]>(2, new string[] { "1", "2", "3", "5" }),
new Tuple<int, string[]>(3, new string[] { "6", "8", "10", "11" }),
new Tuple<int, string[]>(4, new string[] { "1", "8", "11", "12" }),
new Tuple<int, string[]>(5, new string[] { "1", }),
new Tuple<int, string[]>(6, new string[] { "1", "2" }),
new Tuple<int, string[]>(7, new string[] { "30", "28", "123" }),
};
CreateSearchTree("aCoolResource", list.ToArray());
</code></pre>
<p>Finding a user permission goes like this: </p>
<pre><code> var userRights1 = new string[] { "1", "2", "3", "5" };
var userRights2 = new string[] { "123", "30", "28" };
int userLevel1= AuthorizationHelper.GetAuthorizationLevel("aCoolResource", userRights1);
int userLevel2 = AuthorizationHelper.GetAuthorizationLevel("aCoolResource", userRights2);
</code></pre>
<p>This works as intended. What I'm mostly looking for is tips on how to improve performance. However, all other tips are welcome as well. You can also download the source here: </p>
<p><a href="https://gofile.io/?c=wwwNwv" rel="nofollow noreferrer">https://gofile.io/?c=wwwNwv</a></p>
<p>NOTE: Because the trees store strings, they’re ordered as such. So 1, 2 and 10 is ordered as 1, 10 and 2. It works fine this way for me, but there may be edge cases I missed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T16:20:28.727",
"Id": "435712",
"Score": "0",
"body": "We could provide a better review if the entire class(s) was included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T18:04:07.700",
"Id": "435720",
"Score": "0",
"body": "@pacmaninbw I did one better and added some source code. Link is at the bottom of the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:16:41.640",
"Id": "435810",
"Score": "0",
"body": "Roughly how many roles and actions per role do you need to handle? Also, can you use integers instead of strings for action IDs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:35:38.530",
"Id": "435816",
"Score": "0",
"body": "There are about 10 roles per search tree, with about 40 possible actions per role. All combinations of roles and actions are possible as far as I know, so role 1 can have just 1 action, while role 2 has 40 actions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:58:57.623",
"Id": "435825",
"Score": "0",
"body": "And are those action IDs always numeric, or do they have to be strings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T12:02:38.407",
"Id": "435826",
"Score": "0",
"body": "Everything is received as strings, but they're always integers in string format. I opted out of parsing everything to integers as I didn't want the extra overhead, and the code works with strings equally well."
}
] |
[
{
"body": "<p>First of all, it's good to see the public interface being documented.</p>\n\n<p>There are however some problems:</p>\n\n<ul>\n<li><code>CreateSearchTree</code> is broken. When registering level 1 with <code>[\"1\", \"2\", \"3\"]</code>, it marks both the <code>\"2\"</code> and <code>\"3\"</code> node as level 1. And when registering level 2 with <code>[\"1\", \"2\"]</code>, the <code>\"2\"</code> node is not updated to level 2.\nThis causes various lookup failures, depending on the order in which rights were registered.</li>\n<li>In some cases you're returning 0 instead of -1. That's because <code>TreeNode.AuthorizationLevel</code>'s default value is 0, and you're not explicitly initializing it to -1.</li>\n</ul>\n\n<p>Other things that could be improved:</p>\n\n<ul>\n<li>In <code>CreateSearchTree</code>, you could use value tuples instead of the old <code>Tuple</code> class.</li>\n<li><code>== false</code> and <code>== true</code> are only necessary when you're working with nullable booleans, which is not the case here.</li>\n<li>You don't need to call <code>ToString()</code> on a string.</li>\n<li><code>Array.Sort</code> modifies its input, which means that <code>GetAuthorizationLevel</code> is modifying the <code>userRights</code> array. That's an unexpected side-effect that could cause trouble elsewhere.</li>\n<li>There's a fair bit of code duplication between <code>SearchTree</code> and <code>TreeNode</code>. You can simplify <code>SearchTree</code> by giving it a single root node to which it can delegate its calls.</li>\n</ul>\n\n<hr>\n\n<p>Regarding performance, using integer action IDs instead of strings would make this quite a bit faster - even with integer parsing overhead.</p>\n\n<p>But with the number of actions being limited to about 40, a dictionary with a <code>ulong</code> as key (with each bit indicating the presence of a specific action ID) would be even faster. If the IDs are all within the 0-63 range, then the key can be generated with one binary-or and bit-shift operation per action ID. Otherwise, you'll need a lookup table that maps action IDs to bit-masks (which would work for integer as well as string IDs). Even with this lookup table, it's still several times faster than the tree-based approach, mostly because you can skip the expensive input-sorting operation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:03:37.177",
"Id": "435829",
"Score": "0",
"body": "Thanks, I can really use this advice. I'm trying to understand your comment on a lookup table though. For that, do you mean something like mapping all user actions to an enum with the [Flag] attribute, converting any set of user actions to an enum, and using the result ulong as a key for a <ulong, int> dictionary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:31:55.500",
"Id": "435832",
"Score": "1",
"body": "You don't need an enum for that: registering an action (during initialization) can be done like `actionMasks[actionID] = 1ul << actionMasks.Count;`. A `[Flags]` enum allows you to give descriptive names to these bit-masks, but that's not very useful in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:35:10.890",
"Id": "435833",
"Score": "0",
"body": "Ahhhhhh, excellent! Thanks. Sadly, I doubt my team will understand bitwise operators, so I have to do some explaining first, as I don't want to check in code that only I understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:29:50.610",
"Id": "435851",
"Score": "0",
"body": "I also had to withdraw some bitwise operations once, because the team rather used an array of booleans. It's not a good feeling if you know you have a good solution that nobody understands :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T12:32:31.403",
"Id": "224668",
"ParentId": "224618",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224668",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T16:02:52.193",
"Id": "224618",
"Score": "5",
"Tags": [
"c#",
"tree"
],
"Title": "Unbalanced search tree for comparing multiple string arrays"
}
|
224618
|
<p>The problem in simple words: I have three arrays of double values (x-, y- and z-coordinates) and need to find the index of the point which has minimum distance to a reference points. I do not need the actual value of this distance. If the minimum distance is not unique, any index where its value occurs may be returned.</p>
<p>I will be using this function for determining the squared distance between points:</p>
<pre><code>double distSqr(double xa, double ya, double za,
double xb, double yb, double zb)
{
double X = xa - xb;
double Y = xa - xb;
double Z = xa - xb;
return X * X + Y * Y + Z * Z;
}
</code></pre>
<p>Taking the square root in the final step will not be necessary.</p>
<p>First of all, consider a "naive" implementation where you simply compare the "current" value to all other values, exchanging the "current" value if a smaller value is found:</p>
<pre><code>// Take the three arrays of x-, y-, and z-coordinates filled with arbitrary values.
#define SIZE 20
double cx[SIZE];
double cy[SIZE];
double cz[SIZE];
int min_naive(double x, double y, double z)
{
double minDist = distSqr(x, y, z, cx[0], cy[0], cz[0]);
int minIndex = 0;
for (int i = 1; i < SIZE; i++)
{
double d = distSqr(x, y, z, cx[i], cy[i], cz[i]);
if (d < minDist)
{
minDist = d;
minIndex = i;
}
}
return minIndex;
}
// Finally, determin the index, e.g.
int minInd = min_naive(0, 0, 0);
</code></pre>
<p>This does not seem like an optimal solution to me, especially since it might not be fast enough if the loop has to run over all distances where only one comparison happens at each step. Obviously, sooner or later all distances have to be calculated.
Next, I came up with a better solution that first calculates all distances and then compares them in a loop in such a way, that each loop halves the number of possible distances left.
I hoped that the compiler might auto-vectorize this function, instead of using a simple loop over all points, but I have not checked that yet.</p>
<p>This is the code I came up with:</p>
<pre><code>void cmpmv(int lower, int upper, int *inds, double *dists)
{
double a = dists[lower];
double b = dists[upper];
if (a > b)
{
inds[lower] = inds[upper];
dists[lower] = b;
}
}
int min_better(double kax, double kay, double kaz)
{
double dists[SIZE];
int inds[SIZE];
for (int i = 0; i < SIZE; i++)
{
dists[i] = distSqr(kax, kay, kaz, nncx[i], nncy[i], nncz[i]);
inds[i] = i;
}
int div, mod;
int s = SIZE;
while (s > 1)
{
div = s / 2;
mod = s % 2;
for (int i = 0; i < div; i++)
cmpmv(i, i + div, inds, dists);
if (mod == 1)
cmpmv(0, s - 1, inds, dists);
s = div;
}
return inds[0];
}
</code></pre>
<p>(Note that this must differentiate the cases where <code>SIZE</code> and later <code>s</code> are not a multiple of 2.)</p>
<p>Are there maybe even better and especially faster ways to implement this?</p>
<p>There are two restrictions:</p>
<ol>
<li>I only have one thread available.</li>
<li>I have to use arrays/pointers.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T19:09:51.293",
"Id": "435725",
"Score": "0",
"body": "You've tagged this SIMD, but which versions of SIMD would you accept?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T21:09:54.783",
"Id": "435730",
"Score": "0",
"body": "@harold I'm new to SIMD so my question would be \"which versions are there\" :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T21:16:47.200",
"Id": "435731",
"Score": "1",
"body": "A whole bunch even just for x86 processors, and different architectures have their own kinds. Maybe you're OK with AVX2? (requires Haswell or newer from Intel, or from AMD Excavator or Ryzen) If some older hardware is a concern, maybe SSE4.1?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:53:34.370",
"Id": "435738",
"Score": "0",
"body": "@harold I think AVX2 would be incompatible with the machines I am using. It should be compatible with Ivy Bridge and KBL microarchitecture."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:59:42.760",
"Id": "435740",
"Score": "1",
"body": "AVX (aka AVX1) then? That does require some workarounds but nothing too bad"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T04:47:31.130",
"Id": "435923",
"Score": "1",
"body": "Just for what it's worth, this is exactly the sort of problem for which octrees were invented."
}
] |
[
{
"body": "<p>The major compilers did not really auto-vectorize this, but it can be done manually. For example with AVX, we could do something like (not tested)</p>\n\n<pre><code>int indexOfMin(double pt_x, double pt_y, double pt_z, int n)\n{\n __m256d ptx = _mm256_set1_pd(pt_x);\n __m256d pty = _mm256_set1_pd(pt_y);\n __m256d ptz = _mm256_set1_pd(pt_z);\n __m256d xdif = _mm256_sub_pd(ptx, _mm256_loadu_pd(cx));\n __m256d ydif = _mm256_sub_pd(pty, _mm256_loadu_pd(cy));\n __m256d zdif = _mm256_sub_pd(ptz, _mm256_loadu_pd(cz));\n __m256d min_dist = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(xdif, xdif), \n _mm256_mul_pd(ydif, ydif)), \n _mm256_mul_pd(zdif, zdif));\n __m128i min_index = _mm_set_epi32(3, 2, 1, 0);\n __m128i index = min_index;\n __m256d dist;\n for (int i = 4; i < n; i += 4) {\n xdif = _mm256_sub_pd(ptx, _mm256_load_pd(cx + i));\n ydif = _mm256_sub_pd(pty, _mm256_load_pd(cy + i));\n zdif = _mm256_sub_pd(ptz, _mm256_load_pd(cz + i));\n dist = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(xdif, xdif), \n _mm256_mul_pd(ydif, ydif)), \n _mm256_mul_pd(zdif, zdif));\n index = _mm_add_epi32(index, _mm_set1_epi32(4));\n __m256 mask256 = _mm256_castpd_ps(_mm256_cmp_pd(dist, min_dist, _CMP_LT_OS));\n // mask256 has the masks as 4 x int64, but we need 4 x int32\n // there's no nice 'pack' to do it, but shufps can extract\n // the relevant floats, and then we can reinterpret as integers\n // mask256 = * D * C * B * A (* is an ignored float)\n __m128 maskL = _mm256_castps256_ps128(mask256); // * B * A\n __m128 maskH = _mm256_extractf128_ps(mask256, 1); // * D * C\n __m128 maskps = _mm_shuffle_ps(maskL, maskH, _MM_SHUFFLE(2, 0, 2, 0)); // D C B A\n __m128i mask = _mm_castps_si128(maskps);\n min_dist = _mm256_min_pd(min_dist, dist);\n // if the mask is set (this distance is LT the old minimum) then take the current index\n // otherwise keep the old index\n min_index = _mm_blendv_epi8(min_index, index, mask);\n }\n\n double mdist[4];\n _mm256_storeu_pd(mdist, min_dist);\n uint32_t mindex[4];\n _mm_storeu_si128((__m128i*)mindex, min_index);\n double closest = mdist[0];\n int closest_i = mindex[0];\n for (int i = 1; i < 4; i++) {\n if (mdist[i] < closest) {\n closest = mdist[i];\n closest_i = mindex[i];\n }\n }\n return closest_i;\n}\n</code></pre>\n\n<p>The relevant header to include is <code><immintrin.h></code> and to compile you would need to enable AVX with <code>-mavx</code> (GCC, Clang) or <code>/arch:AVX</code> (MSVC).</p>\n\n<p>Most of the code is just subtracting the values from the given coordinate, squaring the difference, and summing the squares. That's not very interesting to discuss, though it plays a significant part in making the code fast. Finding the minimum is more interesting, and is what prevented auto-vectorization. The approach I used is comparing the distance (obviously that was going to be part of it) which results in a bit-mask that is all set where the comparison is true, and then I use that to blend between the \"index of best-so-far\" and the current index, to conditionally replace values without branching.</p>\n\n<p>Because AVX was targeted instead of AVX2, the simpler approach of using an <code>__m256i</code> for the indexes could not be used. That would have removed the need to extract/shuffle the mask, as it would have already been the right size. With AVX2 there are no 256 bit wide integer operations (well, mostly) so it would not be possible to add 4 to the indexes. It <em>would</em> be possible to do a 256 bit blend by using a floating point type blend, then the blend mask is easy but it just pushes the problem to incrementing the indexes.</p>\n\n<p>Finally at the end there is a small loop to select the best index among the 4 candidates.</p>\n\n<p>The array size must be a multiple of 4, it would not be hard to remove that requirement. 32-byte alignment of the arrays is not required but would be better.</p>\n\n<p>By the way this is related to an SSE2 version that I did <a href=\"https://stackoverflow.com/a/30031003/555045\">a couple of years ago</a>, which used single precision floats.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T14:29:42.403",
"Id": "436349",
"Score": "0",
"body": "What is the parameter `n` for the method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T14:51:15.910",
"Id": "436356",
"Score": "0",
"body": "@HerpDerpington the length of the arrays"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T23:31:53.057",
"Id": "224636",
"ParentId": "224622",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T17:55:26.593",
"Id": "224622",
"Score": "2",
"Tags": [
"c++",
"performance",
"array",
"simd"
],
"Title": "Fast \"index of minimum\" for distances to points on single thread"
}
|
224622
|
<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>Here's my implementation in Python, it's very slow(takes like 10 secs to show results. How to make it faster, more efficient?</p>
<pre><code>def is_prime(number):
"""returns True for a prime number, False otherwise."""
if number == 1:
return False
factor = 2
while factor * factor <= number:
if number % factor == 0:
return False
factor += 1
return True
def get_truncatable(n):
"""returns truncatable numbers within range n."""
for number in range(9, n, 2):
if is_prime(number):
check = 0
for index in range(-1, -len(str(number)), -1):
less_right = str(number)[:index]
if not is_prime(int(less_right)):
check += 1
if check == 0:
for index in range(1, len(str(number))):
less_left = str(number)[index:]
if not is_prime(int(less_left)):
check += 1
if check == 0:
yield number
if __name__ == '__main__':
print(sum(list(get_truncatable(1000000))))
</code></pre>
|
[] |
[
{
"body": "<p>You know that a prime other than 2 and 5 ends in 1, 3, 7 or 9. What does that tell you about the digits of x if it is right truncatable? It tells you that all the digits after the first must be 1, 3, 7 or 9. </p>\n\n<p>On the other hand, if you have a four digit left-truncatable number, then the last three digits are also left truncatable. So the find the n+1 digit both left and right truncatable numbers, you take an n digit one which starts with 1, 3, 7 or 9, and prepend any of the digits 1 to 9, and check that the result is both a prime and right-truncatable. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:05:14.943",
"Id": "224631",
"ParentId": "224628",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T21:16:16.290",
"Id": "224628",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 37 Truncatable primes in Python"
}
|
224628
|
<p>This is my first Python program and all it does is print out a description of the specific "Alien Class" that the user inputs. </p>
<p>Looking for tips and pointers and what I can do better and what I am doing well.</p>
<pre><code># Initializing the alien army with different alien classes
alien_army = {
'rogue': {
'name': 'rogue',
'color': 'green',
'size': 'small',
'speed': 'fast',
'damage': 'small'
},
'warrior': {
'name': 'warrior',
'color': 'blue',
'size': 'medium',
'speed': 'average',
'damage': 'heavy'
},
'hunter': {
'name': 'hunter',
'color': 'dark green',
'size': 'average',
'speed': 'average',
'damage': 'average'
}
}
# Adding an Alien class 'Monk' to the alien_army
alien_army['monk'] = {
'name': 'monk',
'color': 'light gray',
'size': 'small',
'speed': 'quick',
'damage': 'average'
}
class_names = []
for k, v in alien_army.items():
class_names.append(k)
# Function that shows the alien that the user typed
def showPickedAlien(a):
print(f"{a['name'].upper()}'S are {a['color'].title()} in color, {a['size'].lower()} in size, {a['speed'].lower()} in speed and they do a {a['damage'].lower()} amount in damage.")
# While loop flag to run or stop loop
input_enabled = True
# While loop to keep displaying the alien class that the user inputs
while input_enabled:
user_input = input("Which class do you want to see? ").lower()
input_alien = alien_army.get(user_input)
# Checking if user entered a valid alien class name
if user_input in class_names:
showPickedAlien(input_alien)
else:
print(f"{user_input.upper()} is not a valid alien class name.")
# Asking user if they want to see another alien class or not
input_for_quit = input("Do you want to see another class? ").lower()
# Determining if the user wants the loop to stop or not
if input_for_quit == 'no' or input_for_quit == 'n':
print("Goodbye.")
input_enabled = False
elif input_for_quit == 'yes' or input_for_quit == 'y':
input_enabled = True
</code></pre>
|
[] |
[
{
"body": "<p>Good job on your first Python program!</p>\n\n<p>You used a <strong>Dictionary</strong> to store all the alien classes. There are many other alternatives to do the same task. The most common one for this kind of problem is <strong>Python Classes</strong> (<a href=\"https://www.w3schools.com/python/python_classes.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/python/python_classes.asp</a>).</p>\n\n<p>You could simply create a <strong>class</strong> called <code>myArmy</code> and then create your soldiers as <strong>objects</strong>. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#Create a class called myArmy\nclass myArmy:\n\n #Use the __init__() function to assign values for name, color...\n def __init__(self, name, color, size, speed, damage):\n\n self.name = name\n self.color = color\n self.size = size\n self.speed = speed\n self.damage = damage\n\n#Create your soldiers (Referred to as \"Objects\" here. The __init__() function is called automatically every time the class is being used to create a new object.\nrogue = myArmy('rogue', 'green', 'small', 'fast', 'small')\nwarrior = myArmy('warrior', 'green', 'medium', 'average', 'heavy')\nhunter = myArmy('hunter', 'dark green', 'average', 'average', 'average')\n\n#Access Rogue information for example\nprint(rogue.name, rogue.color, rogue.size, rogue.speed, rogue.damage)\n</code></pre>\n\n<p>Next step should be to give them attack/defense values and attack speed, and let the user make them battle each other!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T03:12:52.483",
"Id": "224645",
"ParentId": "224629",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>According to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> widely-accepted style, your function should be named <code>show_picked_alien</code>.</p></li>\n<li><p>You don't need a <code>class_names</code> list, as you can just do <code>if key in dictionary</code></p></li>\n<li><p>If it always coincides with the key, you don't need the <code>name</code> attribute</p></li>\n<li><p>You don't need a <code>input_enabled</code> variable: you can just break out of the loop, or better, put that in a function and return</p></li>\n<li><p>You should avoid executable code at the top level of your module, for future extensibility (it also always helps having smaller functions). Use a classic: <code>if __name__ == \"__main__\": main()</code></p></li>\n<li><p>It's better if you pick one quote type (single or doubles) and stick with it, within a program (also from PEP8). But don't pick one style \"for life\" and apply it on projects using other styles.</p></li>\n<li><p>Maybe that's pushing it too far, but if your goal is to make a real application, you can transform your attributes, at least speed/size/damage into enums rather than strings (or use string constants). Because later on you will have checks like <code>if speed == 'average'</code> and don't want to repeat string literals and have to make them coincide in several places</p></li>\n<li><p>I second MarkH's suggestion of making a class (but with a PEP8-compliant name). If you do this, implement <code>__str__</code> on it (maybe the same as your current <code>showPickedAlien</code> if not too verbose). That will help with your debugging later on.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T06:56:34.380",
"Id": "224715",
"ParentId": "224629",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T21:36:53.623",
"Id": "224629",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "First Python program: pick and display alien characteristics"
}
|
224629
|
<p>I am trying to display images from a folder in my project using the "fs" module with NodeJS. I need to read all images in a directory and run them in a loop for them to be displayed. I was able to do it but I'm not sure if this is the proper or good way to do it.</p>
<p>I inserted my readdir (Reading Files Asynchronously) inside my Homepage route.
The images were displayed but I have no one to ask if I did it the proper way.</p>
<pre><code>const express = require('express');
const router = express.Router();
const fs = require('fs');
router.get('/', function(){
fs.readdir('./assets/images/', (err, files) => {
if(err) {
throw err;
}
res.render('home', {
files: files
});
});
});
module.exports = router;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:57:42.553",
"Id": "435824",
"Score": "0",
"body": "Perhaps you should also provide us the `res.render` function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T22:44:30.200",
"Id": "435913",
"Score": "0",
"body": "Hi @konijn, res.render function is from express module required on top, you can check here for reference --> https://expressjs.com/en/api.html#res.render . Thank you!"
}
] |
[
{
"body": "<p>That's not a lot to review, but it looks textbook good.</p>\n\n<p>If anything, the value of <code>'./assets/images/'</code> could have been an upfront declared constant, or could have been retrieved from a configuration file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T22:46:08.177",
"Id": "435914",
"Score": "0",
"body": "@konjin Thanks for making time reviewing my code, Your advice is highly appreciated! Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:16:17.097",
"Id": "224683",
"ParentId": "224632",
"Score": "1"
}
},
{
"body": "<ul>\n<li>Don't use callbacks, it's hard to read and maintain, the <code>fs.readdir</code> function will return a promise if you didn't provide a callback function.</li>\n<li>Use arrow functions when you could.</li>\n<li>Respond with an error instead of throwing (unless you have a catch wrapper middleware).</li>\n<li>Use property shorthands.</li>\n<li>You forgot <code>req</code> and <code>res</code>.</li>\n</ul>\n\n<p>Try this:</p>\n\n<pre><code>const express = require('express');\nconst router = express.Router();\nconst fs = require('fs');\n\nrouter.get('/', async (req, res) => { \n try {\n const files = await fs.readdir('./assets/images/')\n res.render({ files }) // notice the property shorthand\n } catch (error) {\n res.status(404).json({ error })\n }\n});\n\nmodule.exports = router;\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:40:30.340",
"Id": "441839",
"Score": "1",
"body": "This is cool! Thanks Man very much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:30:25.600",
"Id": "227140",
"ParentId": "224632",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227140",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:23:30.340",
"Id": "224632",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"node.js",
"file-system",
"express.js"
],
"Title": "Reading image files asynchronously and displaying them on the page"
}
|
224632
|
<p>This is a USB related question, but the problem is not USB specific. When reading data from a USB endpoint, there are two patterns I am concerned with. Request/Response like HTTP (done over the Bulk endpoint), and Interrupt transfer where one would continuously poll the interrupt endpoint without writing data to the device. </p>
<p>In one particular case, there is a device that uses a request/response pattern but over the interrupt endpoint. This usually isn't a problem, but the UWP USB API does the polling for you on the interrupt endpoint and treats the incoming data as an event. So, if I want to implement a <code>ReadAsync</code> method, I need to await some kind of <code>TaskCompletionSource</code> to get the data. This is certainly not elegant but I'm looking for the least nasty way of synchronizing the context. I've used a combination of <code>SemaphoreSlim</code> and <code>TaskCompletionSource</code> here. Is there a more elegant way?</p>
<p><a href="https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Usb.Net.UWP/UWPUsbInterfaceInterruptReadEndpoint.cs" rel="nofollow noreferrer">Code</a></p>
<pre><code>private async void UsbInterruptInPipe_DataReceived(UsbInterruptInPipe sender, UsbInterruptInEventArgs args)
{
try
{
await _DataReceivedLock.WaitAsync();
var bytes = args.InterruptData.ToArray();
_Chunks.Add(bytes);
if (bytes != null)
{
Logger?.Log($"{bytes.Length} read on interrupt pipe {UsbInterruptInPipe.EndpointDescriptor.EndpointNumber}", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
}
if (_ReadChunkTaskCompletionSource != null && _ReadChunkTaskCompletionSource.Task.Status!= TaskStatus.RanToCompletion)
{
//In this case there should be no chunks. TODO: Put some unit tests around this.
//The read method wil be waiting on this
var result = _Chunks[0];
_Chunks.RemoveAt(0);
_ReadChunkTaskCompletionSource.SetResult(result);
Logger?.Log($"Completion source result set", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
return;
}
}
finally
{
_DataReceivedLock.Release();
}
}
</code></pre>
<p>And</p>
<pre><code>public async Task<byte[]> ReadAsync()
{
try
{
Logger?.Log($"Read called on {nameof(UWPUsbInterfaceInterruptReadEndpoint)}", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
await _ReadLock.WaitAsync();
byte[] retVal = null;
try
{
//Don't let any datas be added to the chunks here
await _DataReceivedLock.WaitAsync();
if (_Chunks.Count > 0)
{
retVal = _Chunks[0];
Tracer?.Trace(false, retVal);
_Chunks.RemoveAt(0);
Logger?.Log($"Read the first chunk {nameof(UWPUsbInterfaceInterruptReadEndpoint)}", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
return retVal;
}
}
catch(Exception ex)
{
Logger?.Log($"Error {nameof(ReadAsync)}", nameof(UWPUsbInterfaceInterruptReadEndpoint), ex, LogLevel.Error);
throw;
}
finally
{
_DataReceivedLock.Release();
}
_ReadChunkTaskCompletionSource = new TaskCompletionSource<byte[]>();
Logger?.Log($"Data received lock released. Completion source created. Waiting for data.", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
//Wait for the event here. Once the event occurs, this should return and the semaphore should be released
retVal = await _ReadChunkTaskCompletionSource.Task;
_ReadChunkTaskCompletionSource = null;
Logger?.Log($"Completion source nulled", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
Tracer?.Trace(false, retVal);
return retVal;
}
finally
{
_ReadLock.Release();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T08:32:16.333",
"Id": "435776",
"Score": "2",
"body": "You could post the code of the class that provides these 2 methods? We can only assume how you have declared and instantiated some of these threading classes like _ReadLock_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T08:56:35.383",
"Id": "435779",
"Score": "0",
"body": "I did. It's the link that says \"Code\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T09:01:30.783",
"Id": "435781",
"Score": "4",
"body": "Links can rot or become broken, I would just add a bit more context in the question. [Please include a description of the challenge here in your question.](https://codereview.meta.stackexchange.com/a/1994)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:09:14.173",
"Id": "435845",
"Score": "4",
"body": "I realize that a link to the entire source code is provided, but it is much easier to provide a good review when the entire class is posted."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T22:27:19.240",
"Id": "224633",
"Score": "2",
"Tags": [
"c#",
"thread-safety",
"event-handling",
"async-await",
"serial-port"
],
"Title": "Await data coming from an event"
}
|
224633
|
<blockquote>
<p>Take the number 192 and multiply it by each of 1, 2, and 3:</p>
<ul>
<li>192 × 1 = 192</li>
<li>192 × 2 = 384</li>
<li>192 × 3 = 576</li>
</ul>
<p>By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)</p>
<p>The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).</p>
<p>What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?</p>
</blockquote>
<p>Awaiting feedback.</p>
<pre><code>def check_pandigital(n):
"""Assumes n is a string of numbers.
returns True if 1-9 in number, False otherwise."""
for i in range(1, 9):
if str(i) not in n:
return False
return True
def multiply_concatenate(n):
"""Assumes n is a positive integer.
returns concatenations of number multiplied by a range if (1-9) in number."""
s = str(n)
for i in range(2, 10):
s += str(i * n)
if check_pandigital(s):
return s
def check_range(n):
"""Assumes n is a range(integer).
generates pandigitals within the range."""
for i in range(2, n):
mult_conc = multiply_concatenate(i)
if mult_conc and len(mult_conc) <= 9:
yield mult_conc
if __name__ == '__main__':
print(max(int(number) for number in check_range(10000)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T04:41:24.553",
"Id": "435751",
"Score": "2",
"body": "Why'd you add the rant to seven of your recent questions? It is counterproductive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T04:46:30.263",
"Id": "435752",
"Score": "0",
"body": "I'm sorry if you're offended or anything but I'm making some effort to learn and become better at programming all I'm getting since the beginning of the day are downvotes without feedback so I'm a bit confused why i'm getting the downvotes though all the codes I posted are working maybe not the most efficient but get you the right answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T05:00:45.753",
"Id": "435753",
"Score": "1",
"body": "I'm not offended. But I'd be less inclined to review the code with that paragraph in it (I don't know Python so I'm not going to review it). You've asked several questions within a short time span, and questions on CR can take several days to get answered. You can improve the questions by including a link to the challenge question, a summary of the question, and an explanation of your code. See [ask]. Perhaps check out a [related question](https://codereview.stackexchange.com/questions/49321/project-euler-38-pandigital-multiples)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T21:09:27.267",
"Id": "435907",
"Score": "0",
"body": "Also see this [answer](https://codereview.meta.stackexchange.com/a/591/85680) to a recent question on Meta."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T23:27:16.790",
"Id": "224635",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 38 Pandigital multiples in Python"
}
|
224635
|
<p>I'm new to MySQL database design.
My question is this database is correctly built or not.
We used the users table to login and get account type <a href="https://i.stack.imgur.com/06hOL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/06hOL.png" alt="enter image description here"></a></p>
<p>and here the code to login </p>
<pre><code> $result = mysqli_query($db->_connect()," SELECT * FROM users WHERE nam = $_n AND pas = $_p ");
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
$response["userInfo"] = array();
while ($row = mysqli_fetch_array($result)) {
$userInfo = array();
$userInfo["id"] = $row["id"];
$userInfo["id_school"] = $row["id_school"];
$userInfo["states"] = $row["states"];
$userInfo["a_type"] = $row["a_type"];
array_push($response["userInfo"], $userInfo);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T03:52:19.517",
"Id": "435747",
"Score": "1",
"body": "Welcome to CodeReview! I find it slightly unsettling to be presented code with unmatched braces or parentheses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T06:27:55.660",
"Id": "435763",
"Score": "0",
"body": "I have several questions: 1. What is an user? In other words: Why does an user need `id_school`, `states` and `a_type`. The last two don't mean anything to me. 2. Why do you abbreviate names? `$_n` and `nam`, really? Why not `$username` and `username`? Code should not be a puzzle. 3. You insert PHP variables directly into your query string. That's like opening the door to your palace and invite the riff-raff. Please read up on [SQL-injection](https://www.php.net/manual/en/security.database.sql-injection.php). 4. Why do you, seemingly, allow multiple users to log in at the same time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T08:27:59.207",
"Id": "435775",
"Score": "0",
"body": "@KIKOSoftware the 1-user need id_school to add the user to that school case we have multiple school and same login screen to student and school so we make the users table states if the account is disable on not a_type account type school or student 2- this php script for android app not web app and i'am new to php"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:21:34.280",
"Id": "435798",
"Score": "0",
"body": "@KIKOSoftware for php insert i will use this \n $stmt = $db->_connect()->prepare(\" SELECT * FROM users WHERE nam = ? AND pas = ?\");\n $stmt->bind_param(\"ss\", $_n,$_p);\n $result = $stmt->execute();"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:37:47.757",
"Id": "435804",
"Score": "0",
"body": "That is indeed better. However, the problem with the names remains. How will anyone know what `$_n` or `$_p` stand for? Also, if I had to guess I would say that `id_std` is a student id, but why not call it `student_id` or `student_number`? similarly `sc_nam` should probably be called `school_name`. This will make your code a lot easier to read. 30 years ago we used abbreviations to save memory, but nowadays most computers have enough memory to store a normal sensible name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:44:29.143",
"Id": "435835",
"Score": "0",
"body": "I believe this code is not working yes and therefore the question would likely be closed. Please test your code before posting it here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T01:19:13.803",
"Id": "435920",
"Score": "0",
"body": "@YourCommonSense This code worked"
}
] |
[
{
"body": "<p>This code work for me </p>\n\n<pre><code>$query = 'SELECT * FROM users WHERE username = ? AND _password= ?';\n\nif ($stmt = $con->prepare($query)) {\n $stmt->bind_param('ss', $_username, $_password); // 's' specifies the variable type => 'string'\n $stmt->execute();\n $result = $stmt->get_result();\n\n if (mysqli_num_rows($result) > 0) {\n $response[\"userInfo\"] = array();\n\n while ($row = $result->fetch_assoc()) {\n\n // Do something with $row\n $userInfo = array();\n $userInfo[\"id\"] = $row[\"id\"];\n $userInfo[\"id_school\"] = $row[\"id_school\"];\n $userInfo[\"states\"] = $row[\"states\"];\n $userInfo[\"account_type\"] = $row[\"account_type\"];\n array_push($response[\"userInfo\"], $userInfo);\n }\n\n $response[\"success\"] = 1;\n $response[\"message\"] = \"Login Done\";\n // echoing JSON response\n echo json_encode($response, JSON_UNESCAPED_UNICODE);\n } else {\n $response[\"success\"] = 0;\n $response[\"message\"] = \"Fail to Login\";\n // echoing JSON response\n echo json_encode($response, JSON_UNESCAPED_UNICODE);\n }\n $stmt->close();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:37:59.347",
"Id": "435944",
"Score": "0",
"body": "You are not supposed to post an edited code as an answer. I would suggest to delete the current question and to ask a new one, adding the code you posted here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T01:17:26.897",
"Id": "224708",
"ParentId": "224637",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T23:49:36.713",
"Id": "224637",
"Score": "-1",
"Tags": [
"php",
"database",
"authentication",
"mysqli"
],
"Title": "Login to a school system and get account type"
}
|
224637
|
<p>I am looking to optimize the nested for-loops shown in the code below. </p>
<p>I have a list, <code>mixtures</code>, that contains points that represent 1 Gaussian Mixture (GM) on each line. My goal is to run a function <code>kl_divergence</code> between all combinations of GM's (with i≠j) and store the results in an array <code>PxP</code>.</p>
<p><em>Note: The following</em> <code>mixtures</code> <em>list is a simplified version of the actual list. In my original code, I am working with a lot more data.</em></p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from sklearn.mixture import GaussianMixture
def kl_divergence(gmm_i, gmm_j, n_samples=10**5):
X = gmm_i.sample(n_samples)
log_p_i = gmm_i.score_samples(X[0])
log_p_j = gmm_j.score_samples(X[0])
return log_p_i.mean() - log_p_j.mean()
mixtures = [[[1, 3, 4, 7], [3, 5, 9, 2], [4, 3, 6, 1], [4, 3, 6, 3]],
[[3, 4, 8, 2], [3, 6, 3, 7], [2, 6, 8, 4]],
[[4, 8, 9, 3], [2, 6, 5, 8], [2, 5, 3, 5]],
[[4, 9, 0, 2], [2, 4, 8, 3], [9, 8, 2, 3], [2, 6, 8, 3]]]
#Note: Each line has a different number of points
P_comp = len(mixtures)
PxP = np.zeros((P_comp, P_comp), dtype=int)
for row_i, GM_i in enumerate(mixtures): #Loop through mixtures using i
gmm_i = GaussianMixture(n_components=1).fit(GM_i)
for row_j, GM_j in enumerate(mixtures): #Loop through mixtures using j
if GM_i is not GM_j: #Skip if same mixture
gmm_j = GaussianMixture(n_components=1).fit(GM_j)
PxP[row_i, row_j] = kl_divergence(gmm_i, gmm_j) #Store result at index (row_i, row_j)
print("PxP\n", PxP)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T03:43:19.733",
"Id": "435745",
"Score": "1",
"body": "Welcome to CodeReview! Looks like you instantiate a `GaussianMixture` over and again for any given element of `mixtures` - is that a cheap operation? Did you try and find out which part of the consumes most time with `a lot more data`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T07:35:40.260",
"Id": "435771",
"Score": "1",
"body": "Are you working with so much data that space might start to become a problem, or \"just\" so much data that performance might be significant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T01:02:39.040",
"Id": "435918",
"Score": "0",
"body": "@greybeard Here are some performance figures: `kl_divergence(gmm_i, gmm_j)` runs in **45ms** on average. Preparing a GM `gmm_i` or `gmm_j` takes anywhere between **10ms** and **1000ms**, and depends on how many points are in `row_i` or `row_j`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T01:09:48.207",
"Id": "435919",
"Score": "0",
"body": "@Ninetails Memory hasn't been an issue yet, so it's purely a performance issue."
}
] |
[
{
"body": "<p>The code to establish <code>PxP</code> should be in a function of its own, featuring a <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">doc string</a> and comments where necessary (why not use <code>GaussianMixture(covariance_type ='spherical')</code>?)<br>\nSame goes for <code>kl_divergence()</code>: when(/why?) is <code>n_samples=10**5</code> appropriate?</p>\n\n<p>From eyeballing your code, it would seem that you instantiate a <code>GaussianMixture()</code> not just once for each mixture, but <code>(len(mixtures))²</code>? times.<br>\nTry to turn <code>mixtures</code> into <code>GaussianMixture</code> upfront: <code>mixtures = [GaussianMixture().fit(mix) for mix in mixtures]</code> (<code>n_components=1</code> is default - do you need <code>covariance_type='full'</code>?). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T04:12:23.860",
"Id": "436276",
"Score": "0",
"body": "The improvement I got in computation time after I turned `mixtures` into `GaussianMixture` upfront is unbelievable. I was expecting a 1.5-2x boost in performance but it turned out to be much more: **30x**. Regarding the doc string and comments, I believe you are right. It will help explain/clarify the parameters I'm using."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T03:27:54.003",
"Id": "224712",
"ParentId": "224638",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224712",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T00:45:00.930",
"Id": "224638",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Filling up a numpy array using data from a list"
}
|
224638
|
<blockquote>
<p>The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.</p>
<p>Let <span class="math-container">\$d_1\$</span> be the 1st digit, <span class="math-container">\$d_2\$</span> be the 2nd digit, and so on. In this way, we note the following:</p>
<p><span class="math-container">\$d_2d_3d_4=406\$</span> is divisible by 2</p>
<p><span class="math-container">\$d_3d_4d_5=063\$</span> is divisible by 3</p>
<p><span class="math-container">\$d_4d_5d_6=635\$</span> is divisible by 5</p>
<p><span class="math-container">\$d_5d_6d_7=357\$</span> is divisible by 7</p>
<p><span class="math-container">\$d_6d_7d_8=572\$</span> is divisible by 11</p>
<p><span class="math-container">\$d_7d_8d_9=728\$</span> is divisible by 13</p>
<p><span class="math-container">\$d_8d_9d_{10}=289\$</span> is divisible by 17</p>
<p>Find the sum of all 0 to 9 pandigital numbers with this property.</p>
</blockquote>
<p>Awaiting feedback.</p>
<pre><code>from itertools import permutations
from time import time
def check_divisibility(number):
"""returns True if pandigital number obeys to the divisibility rules."""
primes = [2, 3, 5, 7, 11, 13, 17]
to_str = str(number)
for index in range(1, 8):
partition = to_str[index: index + 3]
if int(partition) % primes[index - 1]:
return False
return True
def check_zero_nine_pandigits():
"""generates all 10 pandigital numbers that obey the divisibility rules."""
return (int(''.join(perm)) for perm in permutations('1406357289') if perm[0] != '0' and
check_divisibility(int(''.join(perm))))
if __name__ == '__main__':
start_time = time()
print(sum(check_zero_nine_pandigits()))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[] |
[
{
"body": "<p>There are probably more subtle ways to solve this problem like using a constructive solution starting from the end. Anyway, let's try to improve your bruteforce implementation.</p>\n\n<p><strong>Already defined values</strong></p>\n\n<p><code>permutations('1406357289')</code> could be written <code>permutations(string.digits)</code></p>\n\n<p><strong>Conversions in all directions</strong></p>\n\n<p>From a permutation (iterable), you build a string (with <code>join</code>) then an int which is then converted to a string (in <code>check_divisibility</code>) to get the chunks of 3 digits which are converted to int.</p>\n\n<p>Also, some of these operations are performed twice...</p>\n\n<p>From a permutation <code>perm</code>, you can directly compute the value of the chunk at index <code>i</code> with <code>int(''.join(p[i:i + 3]))</code> (which involves many conversions but it is hard to do less).</p>\n\n<p><strong>Avoid <code>range(1, 8)</code></strong></p>\n\n<p>The hardcoded range can be hard to understand and easy to get wrong when other parts of the code get updated because of the magic numbers.</p>\n\n<p>In general, it is best to avoid using <code>range</code> when what you want is to iterate over an iterable - see also <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Ned Batchelder's excellent talk: \"Loop like a native\"</a>.</p>\n\n<p>Here, you could write something like (not tested):</p>\n\n<pre><code>def check_divisibility(number):\n \"\"\"returns True if pandigital number obeys to the divisibility rules.\"\"\"\n divisors = [2, 3, 5, 7, 11, 13, 17]\n to_str = str(number)\n for idx, div in enumerate(divisors):\n if int(to_str[idx + 1: idx + 3 + 1]) % div:\n return False\n return True\n</code></pre>\n\n<p><strong>Builtins</strong></p>\n\n<p>This looks like the typical situation where you can use the builtins <code>all</code>/<code>any</code>.</p>\n\n<pre><code>def check_divisibility(number):\n \"\"\"returns True if pandigital number obeys to the divisibility rules.\"\"\"\n divisors = [2, 3, 5, 7, 11, 13, 17]\n to_str = str(number)\n return all(int(to_str[idx + 1: idx + 3 + 1]) % div == 0\n for idx, div in enumerate(divisors))\n</code></pre>\n\n<p>Now that we remember that we could provide number as a string directly to the function, we'd have something like:</p>\n\n<pre><code>def check_divisibility(number):\n \"\"\"returns True if pandigital number obeys to the divisibility rules.\"\"\"\n divisors = [2, 3, 5, 7, 11, 13, 17]\n return all(int(number[idx + 1: idx + 3 + 1]) % div == 0\n for idx, div in enumerate(divisors))\n\n\ndef check_zero_nine_pandigits():\n \"\"\"generates all 10 pandigital numbers that obey the divisibility rules.\"\"\"\n return (int(''.join(perm)) for perm in permutations(string.digits) if perm[0] != '0' and check_divisibility(''.join(perm)))\n</code></pre>\n\n<p>And then, we could ask ourselves if we really need that extra function:</p>\n\n<pre><code>def check_zero_nine_pandigits():\n \"\"\"generates all 10 pandigital numbers that obey the divisibility rules.\"\"\"\n divisors = [2, 3, 5, 7, 11, 13, 17]\n return (int(''.join(perm)) for perm in permutations(string.digits)\n if perm[0] != '0' and\n all(int(''.join(perm)[idx + 1: idx + 3 + 1]) % div == 0 for idx, div in enumerate(divisors)))\n</code></pre>\n\n<p><strong>Small optimisation</strong></p>\n\n<p>The divisibility criteria with 17 is more restrictive than the one with 2. We could start with that one.\nFor instance:</p>\n\n<pre><code>def check_zero_nine_pandigits():\n \"\"\"generates all 10 pandigital numbers that obey the divisibility rules.\"\"\"\n divisors = [(17, 7), (13, 6), (11, 5), (7, 4), (5, 3), (3, 2), (2, 1)]\n return (int(''.join(perm)) for perm in permutations(string.digits)\n if perm[0] != '0' and\n all(int(''.join(perm)[idx: idx + 3]) % div == 0 for div, idx in divisors))\n</code></pre>\n\n<p><strong>Joining less elements</strong></p>\n\n<p><code>''.join(perm)[idx: idx + 3]</code> can be written <code>''.join(perm[idx: idx + 3])</code></p>\n\n<p><strong>Final code:</strong></p>\n\n<pre><code>def check_zero_nine_pandigits():\n \"\"\"generates all 10 pandigital numbers that obey the divisibility rules.\"\"\"\n divisors = [(17, 7), (13, 6), (11, 5), (7, 4), (5, 3), (3, 2), (2, 1)]\n return (int(''.join(perm)) for perm in permutations(string.digits)\n if perm[0] != '0' and\n all(int(''.join(perm[idx: idx + 3])) % div == 0 for div, idx in divisors))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T21:42:48.593",
"Id": "224928",
"ParentId": "224646",
"Score": "1"
}
},
{
"body": "<p>Obviously, there are a billion possible permutations to check. To be able to find the number in a reasonable time, you need to prune off parts of the search space that can't possibly include the answer.</p>\n\n<p>For example, given the property <em>d<sub>4</sub>d<sub>5</sub>d<sub>6</sub> is divisible by 5</em>, we know that <em>d<sub>6</sub></em> can only be 0 or 5. Similarly, we know that d<sub>4</sub> must be an even digit, and d<sub>1</sub> can't be 0. Using that information, you can reduce the search space to \"only\" 90 million permutations (still a lot).</p>\n\n<p>Alternatively, you could try to construct a number by starting with a 3-digit number that satisfies one of the criteria. And then try adding digits in such a way that with each new digit, the number satisfies another criteria.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T03:48:09.070",
"Id": "224941",
"ParentId": "224646",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T03:13:35.067",
"Id": "224646",
"Score": "-1",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 43 Sub-string divisibility in Python"
}
|
224646
|
<p>I am making a small console app to get XML from an API and then save the data to a database. While this project was not created via test-driven-development, I have tried to make it such that tests can be written easily and properly. Additionally, the core portions of the application are in a separate library project, as I am also making other interfaces (web app, etc.) for working with the API and data.</p>
<h3>Application</h3>
<pre><code>Imports JetBrains.Annotations
Public Class Application
<UsedImplicitly>
Public Shared Function Main(arguments As String()) As Integer
Dim calendarImporter As ICalendarImporter
If arguments.Length <> 2
calendarImporter = New CalendarImporter(
GetInput("Url: "),
GetInput("Token: "))
Else
calendarImporter = New CalendarImporter(arguments(0), arguments(1))
End If
Try
calendarImporter.RunAsync().GetAwaiter()
Return 0
Catch exception As Exception
HandleException(exception)
Return 1
End Try
End Function
Private Shared Function GetInput(prompt As String) As String
Dim input As String = Nothing
While String.IsNullOrWhiteSpace(input)
System.Console.Write(prompt)
input = System.Console.ReadLine()
End While
Return input
End Function
Private Shared Sub HandleException(exception As Exception)
System.Console.WriteLine(exception.Message)
Dim innerException = exception.InnerException
While innerException IsNot Nothing
System.Console.WriteLine()
System.Console.WriteLine(innerException.Message)
innerException = innerException.InnerException
End While
End Sub
End Class
</code></pre>
<h3>ICalendarImporter</h3>
<pre><code>Public Interface ICalendarImporter
Function RunAsync() As Task
End Interface
</code></pre>
<h3>CalendarImporter</h3>
<pre><code>Imports Library.CalendarImporter.Db
Imports Library.CalendarImporter.Services
Imports Library.CalendarImporter.Services.Interfaces
Public Class CalendarImporter
Implements ICalendarImporter
Implements IDisposable
Public Sub New(url As String, token As String)
Me.Url = url
Me.Token = token
End Sub
Private Property CalendarImporterService As ICalendarImporterService
Private Property Db As CalendarImporterDbContext
Private Property Url As String
Private Property Token As String
Public Async Function RunAsync() As Task Implements ICalendarImporter.RunAsync
CalendarImporterService = New CalendarImporterService(url, token)
Dim calendarImportResult = Await CalendarImporterService.ImportCalendarAsync()
If calendarImportResult.CalendarImport Is Nothing
Throw New Exception(
Convert.ToInt32(calendarImportResult.StatusCode) &
" " &
calendarImportResult.StatusCode.ToString())
End If
Db.CalendarImports.Add(calendarImportResult.CalendarImport)
Await Db.SaveChangesAsync()
End Function
Public Sub Dispose() Implements IDisposable.Dispose
Db?.Dispose()
End Sub
End Class
</code></pre>
<p>That concludes the console app. The following items are from the library, and used by the console app and others.</p>
<h3>ICalendarImporterService</h3>
<pre><code>Imports Library.CalendarImporter.Services.Models
Namespace Services.Interfaces
Public Interface ICalendarImporterService
Function ImportCalendarAsync() As Task(Of ImportCalendarResult)
End Interface
End NameSpace
</code></pre>
<h3>CalendarImporterService</h3>
<pre><code>Imports System.IO
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Xml
Imports System.Xml.Serialization
Imports Library.CalendarImporter.Entities
Imports Library.CalendarImporter.Services.Interfaces
Imports Library.CalendarImporter.Services.Models
Namespace Services
Public Class CalendarImporterService
Implements ICalendarImporterService
Public Sub New(url As String, token As String)
Me.Url = url
Me.Token = token
End Sub
Private ReadOnly Property Url As String
Private ReadOnly Property Token As String
Private Property CalendarImportXmlSerializer As XmlSerializer =
New XmlSerializer(GetType(CalendarImport))
Public Async Function ImportCalendarAsync() As Task(Of ImportCalendarResult) _
Implements ICalendarImporterService.ImportCalendarAsync
Dim getXmlResult = Await GetXmlAsync()
Dim result = New ImportCalendarResult With {
.StatusCode = getXmlResult.StatusCode
}
If Not String.IsNullOrWhiteSpace(getXmlResult.Xml)
result.CalendarImport = DeserializeXml(getXmlResult.Xml)
result.CalendarImport.Xml = getXmlResult.Xml.Replace("UTF-8", "UTF-16")
result.CalendarImport.Date = Date.Now
End If
Return result
End Function
Private Function DeserializeXml(xml As String) As CalendarImport
Using stringReader = New StringReader(xml)
Using xmlReader As XmlReader = XmlReader.Create(stringReader)
Return CalendarImportXmlSerializer.Deserialize(xmlReader)
End Using
End Using
End Function
Private Async Function GetXmlAsync() As Task(Of GetXmlResult)
Using httpClient = New HttpClient
httpClient.DefaultRequestHeaders.Authorization =
New AuthenticationHeaderValue("Basic", Token)
Dim response = Await httpClient.GetAsync(Url)
Dim result = New GetXmlResult With {
.StatusCode = response.StatusCode
}
If response.IsSuccessStatusCode
result.Xml = Await response.Content.ReadAsStringAsync()
End If
Return result
End Using
End Function
End Class
End NameSpace
</code></pre>
<h3>GetXmlResult</h3>
<pre><code>Imports System.Net
Namespace Services.Models
Public Class GetXmlResult
Public Property StatusCode As HttpStatusCode
Public Property Xml As String
End Class
End NameSpace
</code></pre>
<h3>ImportCalendarResult</h3>
<pre><code>Imports System.Net
Imports Library.CalendarImporter.Entities
Namespace Services.Models
Public Class ImportCalendarResult
Public Property CalendarImport As CalendarImport
Public Property StatusCode As HttpStatusCode
End Class
End NameSpace
</code></pre>
<p>The <code>Entities</code> namespace that includes <code>CalendarImport</code> contains the POCO the XML and database map to. <code>CalendarImport</code> is the name of the root XML object. The namespaces have been edited to remove potentially identifying information about the client(s) involved with the project.</p>
<p>How would I improve this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T03:48:11.130",
"Id": "224647",
"Score": "1",
"Tags": [
"console",
"xml",
"entity-framework",
"vb.net"
],
"Title": "Console app to get XML from API and save to database"
}
|
224647
|
<blockquote>
<p>Pentagonal numbers are generated by the formula, <span class="math-container">\$P_n=\frac{n(3n−1)}{2}\$</span>. The first ten pentagonal numbers are:</p>
<p><code>1, 5, 12, 22, 35, 51, 70, 92, 117, 145</code></p>
<p>It can be seen that <span class="math-container">\$P_4 + P_7 = 22 + 70 = 92 = P_8\$</span>. However, their difference, <span class="math-container">\$70 − 22 = 48\$</span>, is not pentagonal.</p>
<p>Find the pair of pentagonal numbers, <span class="math-container">\$P_j\$</span> and <span class="math-container">\$P_k\$</span>, for which their sum and difference are pentagonal and <span class="math-container">\$D = |P_k − P_j|\$</span> is minimised; what is the value of D?</p>
</blockquote>
<p>Awaiting feedback.</p>
<pre><code>from time import time
def generate_pentagons(n):
"""generates next n pentagons"""
pentagons = (num * (3 * num - 1) // 2 for num in range(1, n))
for i in range(n - 1):
yield next(pentagons)
def get_pentagons(n):
"""Assumes n is a range > 0.
generates pentagons that obey to the + - rules."""
pentagons = set(generate_pentagons(n))
for pentagon1 in pentagons:
for pentagon2 in pentagons:
if pentagon1 + pentagon2 in pentagons and abs(pentagon1 - pentagon2) in pentagons:
return pentagon1, pentagon2
if __name__ == '__main__':
start_time = time()
pent1, pent2 = get_pentagons(10000)
print(abs(pent1 - pent2))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T05:17:57.683",
"Id": "435755",
"Score": "1",
"body": "Why do you ignore the repeated advice ([1](https://codereview.stackexchange.com/questions/224598/project-euler-34-digit-factorials-in-python#comment435654_224598), [2](https://codereview.stackexchange.com/questions/224607/project-euler-36-double-base-palindromes-in-python#comment435675_224607)) to tag Python questions correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T05:24:39.267",
"Id": "435756",
"Score": "0",
"body": "I'm sorry if I seem to be ignoring your advice but in fact, 'python-3.x' as well as 'programming-challenge' are already tagged. I don't know what's wrong here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T05:25:34.573",
"Id": "435757",
"Score": "0",
"body": "check under the code block, you must see them I guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T05:28:29.870",
"Id": "435758",
"Score": "1",
"body": "From the first referenced comment: “Please tag all Python questions with [python], ...”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T07:18:39.977",
"Id": "435766",
"Score": "7",
"body": "You're averaging 5 questions a day. Some of the downvotes might be from people who think you should take things a lot slower, waiting for answers to one question so that you can apply the same principles to your next program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T07:25:40.140",
"Id": "435768",
"Score": "0",
"body": "@Peter Taylor it's not a big deal man. any feedback given will be helpful that's the whole point."
}
] |
[
{
"body": "<p><strong>This is an answer focused primarily about styling</strong></p>\n\n<ul>\n<li>Your parameter names can be renamed to be more specific, like <code>generate_pentagons(n)</code> can be rewritten to <code>generate_pentagons(number_of_pentagons)</code>. This change can also be implemented in the <code>get_pentagons</code> method. While this may seem useless in this program, since <code>n</code> can be easily interpreted as the number of pentagons to generate, it's a good practice to follow when you start writing large programs that require more specific parameter names.</li>\n<li>Parameter constants should be UPPERCASE.</li>\n<li>You don't use <code>i</code> in your loop in <code>generate_pentagons</code> method. To avoid generating an unused variable, you can use an underscore. The <code>_</code> immediately signals the reader that the value is not important.</li>\n</ul>\n\n<p><strong><em>Final Code</em></strong></p>\n\n<pre><code>from time import time\n\n\ndef generate_pentagons(number_of_pentagons):\n \"\"\"generates next n pentagons\"\"\"\n pentagons = (num * (3 * num - 1) // 2 for num in range(1, number_of_pentagons))\n for _ in range(number_of_pentagons - 1):\n yield next(pentagons)\n\n\ndef get_pentagons(number_of_pentagons):\n \"\"\"Assumes n is a range > 0. Generates pentagons that obey to the + - rules.\"\"\"\n pentagons = set(generate_pentagons(number_of_pentagons))\n for pentagon1 in pentagons:\n for pentagon2 in pentagons:\n if pentagon1 + pentagon2 in pentagons and abs(pentagon1 - pentagon2) in pentagons:\n return pentagon1, pentagon2\n\nif __name__ == '__main__':\n START_TIME = time()\n PENTAGON_1, PENTAGON_2 = get_pentagons(10000)\n print(abs(PENTAGON_1 - PENTAGON_2))\n print(f\"Time: {time() - START_TIME} seconds.\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T05:14:44.237",
"Id": "224856",
"ParentId": "224649",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224856",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T04:48:10.583",
"Id": "224649",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 44 Pentagon numbers in Python"
}
|
224649
|
<p>I am currently working on building a calculator using Java and JavaFX to practice my coding skills. I wrote the following methods to evaluate a given expression. </p>
<p>What can I improve? Is there anything you would recommend me to change to optimize my program?</p>
<hr>
<pre><code>public static String evaluate(String expression) {
char[] tokens = expression.toCharArray();
List<String> list = new ArrayList<>();
String s = "";
String operator = "";
String firstNum = "";
String secondNum = "";
boolean operationOnQueue = false;
for (int i = 0; i < tokens.length; i++) {
if (Character.isDigit(tokens[i])) {
s += Character.toString(tokens[i]);
} else {
list.add(s);
list.add(Character.toString(tokens[i]));
if (operationOnQueue) {
operationOnQueue = false;
secondNum = s;
list.set(list.lastIndexOf(firstNum), eval(firstNum, operator, secondNum));
list.remove(list.lastIndexOf(operator));
list.remove(list.lastIndexOf(secondNum));
}
if (tokens[i] == '*' || tokens[i] == '/') {
operationOnQueue = true;
operator = Character.toString(tokens[i]);
firstNum = list.get(list.lastIndexOf(operator) - 1);
}
s = "";
}
if (i == tokens.length - 1 && s.length() > 0) {
list.add(s);
if (list.get(list.size() - 2).equals("*") || list.get(list.size() - 2).equals("/")) {
firstNum = list.get(list.size() - 3);
operator = list.get(list.size() - 2);
secondNum = list.get(list.size() - 1);
list.set(list.size() - 3, eval(firstNum, operator, secondNum));
list.remove(list.size() - 2);
list.remove(list.size() - 1);
}
}
}
while (list.size() > 1) {
firstNum = list.get(0);
operator = list.get(1);
secondNum = list.get(2);
list.set(0, eval(firstNum, operator, secondNum));
list.remove(2);
list.remove(1);
}
return list.get(0);
}
</code></pre>
<pre><code>
public static String eval(String a, String operator, String b) {
double r = 0;
switch (operator) {
case "/":
r += Double.parseDouble(a) / Double.parseDouble(b);
break;
case "*":
r += Double.parseDouble(a) * Double.parseDouble(b);
break;
case "-":
r += Double.parseDouble(a) - Double.parseDouble(b);
break;
case "+":
r += Double.parseDouble(a) + Double.parseDouble(b);
break;
}
return Double.toString(r);
}
</code></pre>
<hr>
<p>These are the results of my tests. The first line is the string inputted, along with the answer to the expression. The second line is the output of the program.</p>
<pre><code>8+4/2+10*3+5*10 = 90
90.0
60*60+8+384/7/4-44*26 = 2477.71
2477.714285714286
64/16*18-51*7+5 = -280
-280.0
64/16*18-5100*7+5 = -35623
-35623.0
7325+92+44/4+57-84 = 7401
7401.0
14+54/9+1 = 21
21.0
7*4/7+9+12*3 = 49
49.0
</code></pre>
|
[] |
[
{
"body": "<h2>How does it work?</h2>\n\n<p>Seems to be working now. What I can't understand is how :)</p>\n\n<p>Code should be readable and easily understandable by humans as well. You might even be one of the humans that have to work with code that you wrote a year or more ago..</p>\n\n<p>There is a lot going on in the code that I cannot tell why it's there and what its use is.</p>\n\n<p>For example:</p>\n\n<pre><code> if (operationOnQueue) {\n operationOnQueue = false;\n secondNum = s;\n\n list.set(list.lastIndexOf(firstNum), eval(firstNum, operator, secondNum));\n list.remove(list.lastIndexOf(operator));\n list.remove(list.lastIndexOf(secondNum));\n }\n</code></pre>\n\n<p>I can read the code and see what it will do, but why? I have no clue. </p>\n\n<p>So either try to explain the why in comments, or re-write the code to be more self-explanatory.</p>\n\n<p>(Btw your code looks a bit like <a href=\"https://en.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Shunting-yard_algorithm</a>.) </p>\n\n<h2>Try to break big methods into smaller ones</h2>\n\n<p>You <code>evaluate</code> does a few things. The <code>while</code> loop in the end seems like a good candidate for a separate method. The second <code>if</code> in the <code>for</code> loop as well.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>There are a few <code>Character.toString(tokens[i])</code> in the code. It's easier to read if you extract that to a variable, for example <code>String currentToken = Character.toString(tokens[i])</code></p>\n\n<h2>Handling error cases</h2>\n\n<p>What if the input is not a correct expression?</p>\n\n<p>For example: <code>14+54/9+</code></p>\n\n<pre><code>Exception in thread \"main\" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2\n at java.util.ArrayList.rangeCheck(ArrayList.java:657)\n at java.util.ArrayList.get(ArrayList.java:433)\n at Math.evaluate(Math.java:64)\n at Math.main(Math.java:96)\n</code></pre>\n\n<p>BTW: for more interesting links / implementations see here:\n<a href=\"https://stackoverflow.com/a/114601/461499\">https://stackoverflow.com/a/114601/461499</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:39:13.320",
"Id": "224722",
"ParentId": "224650",
"Score": "3"
}
},
{
"body": "<p>To make your code short, understandable, elegant, maintainable, and fast, I recommend to:</p>\n\n<ul>\n<li>implement separately syntax and semantics</li>\n<li>for syntax part, construct recursive descent parser. </li>\n<li>read something on theory, starting from <a href=\"https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form\" rel=\"nofollow noreferrer\">Bacus-Naur form</a></li>\n<li>learn examples on <a href=\"https://github.com/search?l=Java&q=recursive%20descent%20parser&type=Repositories\" rel=\"nofollow noreferrer\">Github recursive descent parser</a></li>\n<li>ask questions at Stackoverflow. Tag them with [recursive-descent].</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:09:09.260",
"Id": "224733",
"ParentId": "224650",
"Score": "0"
}
},
{
"body": "<p>There is one big issue in your setup, which reduces the usability, readability and quality of your code.</p>\n\n<h2>Single Responsibility Principle</h2>\n\n<p>Your function does both (1) parsing and evaluation, and (2) printing results.</p>\n\n<blockquote>\n<pre><code>public static String evaluate(String expression) \n{\n // .. parse expression\n // .. evaluate the expression tree\n // .. print the result as string\n}\n</code></pre>\n</blockquote>\n\n<p>You have even managed to combine the evaluation and printing.</p>\n\n<blockquote>\n<pre><code>public static String eval(String a, String operator, String b) \n{\n // evaluate operation\n // format the result to string\n}\n</code></pre>\n</blockquote>\n\n<p>You should refactor your code.</p>\n\n<p>Parsing and evaluation:</p>\n\n<pre><code>public static Double evaluate(String expression) \n{\n // .. parse expression\n // .. evaluate the expression tree\n}\n\npublic static Double eval(Double a, Operators operator, Double b) \n{\n // .. evaluate operation\n}\n\npublic enum Operators { Add, Subtract, Multiply, Divide }\n</code></pre>\n\n<p>Printing</p>\n\n<pre><code>public static String print(Double value) \n{\n // .. print value\n}\n</code></pre>\n\n<hr>\n\n<p>And there's that infamous <a href=\"https://stackoverflow.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-why\">division by zero</a> amongst other possible edge cases you should think about:</p>\n\n<blockquote>\n <p><code>r += Double.parseDouble(a) / Double.parseDouble(b);</code></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:17:20.643",
"Id": "224735",
"ParentId": "224650",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T04:53:07.340",
"Id": "224650",
"Score": "6",
"Tags": [
"java",
"beginner",
"math-expression-eval"
],
"Title": "Evaluating a math expression given in string format"
}
|
224650
|
<p>My path to learning C++ has been a rough one. Currently, I'm writing a project and my knowledge is very outdated. While I can write code that accomplishes the tasks required, I'd like to improve and learn new aspects of the language. </p>
<p>So, I've written a class called <code>Sequencer</code>. It works. It's not great. It's not terrible. But it's based on old code. How would I improve the class with modern code?</p>
<hr>
<pre><code>#pragma once
#include <regex>
#include <string>
#include <experimental/filesystem>
class Sequencer
{
public:
//////////////////////
// CTors / DTor
Sequencer(std::string const first_frame_in): first_frame_name(first_frame_in)
{
bool result = std::regex_search(first_frame_name, first_frame_regex_results, match_pattern);
prefix = first_frame_regex_results[1];
std::string frame = first_frame_regex_results[2];
ext = first_frame_regex_results[3];
first_frame = std::stoi(frame);
digit_padding = frame.length();
current_frame = first_frame;
out_prefix = "_signature";
file_delim = ".";
get_last_frame();
}
~Sequencer() {}
Sequencer(Sequencer const&) = delete;
void operator=(Sequencer const&) = delete;
bool get_next_frame(std::string &next_frame, std::string &name_out)
{
if (current_frame <= last_frame)
{
tmp_num = add_padding(current_frame);
next_frame = prefix + file_delim + tmp_num + file_delim + ext;
name_out = prefix + out_prefix + file_delim + tmp_num + file_delim + "ppm";
current_frame++;
return true;
}
else
{
name_out = "";
next_frame = "";
return false;
}
}
private:
void get_last_frame()
{
bool test = true;
std::string tmpname;
unsigned int i = current_frame + 1;
do
{
tmpname = "C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v9.0\\3_Imaging\\MovieHasher\\data\\" + prefix + file_delim + add_padding(i) + file_delim + ext;
test = std::experimental::filesystem::exists(tmpname);
if (test)
i++;
else
i--;
} while (test);
last_frame = i;
}
std::string add_padding(int frame_num_in)
{
std::string outval = std::to_string(frame_num_in);
int length = outval.length();
while (length < digit_padding)
{
outval = "0" + outval;
length = outval.length();
}
return outval;
}
std::string first_frame_name;
std::regex match_pattern = std::regex("([a-zA-Z]*).([0-9]*).(\\w{3})");
std::smatch first_frame_regex_results;
std::string prefix, ext, out_prefix, tmp_num, file_delim;
int first_frame;
int last_frame;
int digit_padding;
int current_frame;
};
</code></pre>
<hr>
<p>A sample main file to run the <code>Sequencer</code> class</p>
<pre><code>////////////////////////
// INCLUDES
//// System
#include <iostream>
#include <string>
//// User Defined
#include "../../Sequencer.h"
int main(int argc, char **argv)
{
std::string image_filename = "prefix.00000.ext";
std::string out_filename = "prefix_signature.00000.ppm";
Sequencer sequencer(image_filename);
bool tmp = true;
do
{
tmp = sequencer.get_next_frame(image_filename, out_filename);
if (tmp)
std::cout << image_filename << ", " << out_filename << std::endl;
} while (tmp);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T04:40:38.433",
"Id": "436776",
"Score": "0",
"body": "Just want to thank both reviewers for their earnest and thorough reviews of my code. Wish I could accept both answers."
}
] |
[
{
"body": "<p>Code:</p>\n\n<ul>\n<li><p><code>// CTors / DTor</code>: This comment doesn't add anything that we can't see from the code.</p>\n\n<p>Sometimes comments like this denote sections or regions of code in a file, but without consistently doing this for all the code, we don't know where the \"constructor / destructor\" section ends. I'd suggest just removing the comment.</p></li>\n<li><p><code>Sequencer(std::string const first_frame_in)</code>: There's little benefit to making function arguments that are passed by value <code>const</code>. It doesn't affect the caller, and makes the function signature harder to read.</p>\n\n<p>Perhaps this should be a <code>const&</code> though?</p></li>\n<li><p>When we have lots of member variables in a class, adding an <code>m_</code> prefix on the names (e.g. <code>m_current_frame</code>) helps to distinguish them from local variables or function arguments.</p></li>\n<li><p><code>first_frame_name</code>, <code>match_pattern</code>, and <code>first_frame_regex_results</code> are all unused after the constructor, so they could just be local variables rather than members.</p></li>\n<li><p><code>tmp_num</code> and <code>tmpname</code> are not informative names. They should also be local variables since they are each used in only one function.</p></li>\n<li><p>Presumably negative frame numbers can't exist. If this is the case we should be using an unsigned integer type, not a signed one.</p></li>\n<li><p>We should check the result of the regex search and handle an error (since presumably this is going to be a user specified string).</p></li>\n<li><p>The regex captures \"zero or more\" digits, but we don't check that we got a match before trying to convert the frame number. Perhaps we should require \"one or more\" digits / letters when matching.</p></li>\n<li><p>Perhaps the regex pattern should use the specified <code>file_delim</code> too.</p></li>\n<li><p>Using a chain of <code>+</code> operators for <code>std::string</code>s tends to create a lot of temporary strings. Using <code>std::string::append</code> is likely to be faster, especially if we <code>reserve()</code> the memory we need first.</p></li>\n<li><p>We can add the padding digits in one operation by using <code>std::string::insert</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>Design:</p>\n\n<ul>\n<li><p>I'd suggest grouping the information extracted from the first frame filename into a struct. We can then put the regex search and data extraction into a separate function, and more easily use the constructor initializer list.</p></li>\n<li><p>Unless there's a particular reason for it, I wouldn't try finding the last frame inside the <code>Sequencer</code> class. It's probably simpler to restrict the \"sequencer\" to only generating filenames, and leave checking if the file exists for code that does actual processing.</p></li>\n<li><p>Perhaps something like <code>FrameFilenameGenerator</code> might be a more accurate name than <code>Sequencer</code>?</p></li>\n<li><p>We can effectively use the same code to generate the input and output filenames.</p></li>\n<li><p>If we let the user keep track of the current frame, our generator can generate the filename for any requested frame, and doesn't have to keep track of the frame itself.</p></li>\n</ul>\n\n<hr>\n\n<p>So applying the above points, we might get something like:</p>\n\n<pre><code>#include <regex>\n#include <string>\n#include <experimental/filesystem>\n\nclass FrameFilenameGenerator\n{\npublic:\n\n // note: \n // `first_frame_filename` isn't copied, so we only need a const&\n // `file_delim` is a \"sink argument\" (i.e. we store a copy in the class), so we take the argument by value and move it into place.\n FrameFilenameGenerator(std::string const& first_frame_filename, std::string file_delim = \".\"):\n m_file_delim(std::move(file_delim)),\n m_info(get_first_filename_info(first_frame_filename))\n {\n\n }\n\n // note: we should probably be more careful with the frame offset!\n // first_frame_number + frame_offset could overflow!\n std::string make_filename(std::uint32_t frame_offset, std::string const& output_suffix = \"\") const\n {\n auto result_size = \n m_info.prefix.size() + \n output_suffix.size() + \n m_file_delim.size() + \n m_info.digit_padding + \n m_file_delim.size() + \n m_info.extension.size();\n\n auto result = std::string();\n result.reserve(result_size);\n\n result.append(m_info.prefix);\n result.append(output_suffix);\n result.append(m_file_delim);\n result.append(frame_number_to_string(m_info.first_frame_number + frame_offset, m_info.digit_padding));\n result.append(m_file_delim);\n result.append(m_info.extension);\n\n return result;\n }\n\nprivate:\n\n struct FirstFilenameInfo\n {\n std::string prefix;\n std::uint32_t first_frame_number;\n std::size_t digit_padding;\n std::string extension;\n };\n\n static FirstFilenameInfo get_first_filename_info(std::string const& first_frame_filename)\n {\n auto result = FirstFilenameInfo();\n\n const auto match_pattern = std::regex(\"([a-zA-Z]*).([0-9]*).(\\\\w{3})\");\n std::smatch regex_results;\n\n if (!std::regex_search(first_frame_filename, regex_results, match_pattern))\n throw std::runtime_error(\"First frame filename does not meet the required format!\");\n\n result.prefix = regex_results[1];\n\n if (regex_results[2].length())\n {\n result.first_frame_number = std::uint32_t{ std::stoul(regex_results[2]) };\n result.digit_padding = regex_results[2].length();\n }\n\n result.extension = regex_results[3];\n\n return result;\n }\n\n static std::string frame_number_to_string(std::uint32_t frame_number, std::size_t digit_padding)\n {\n auto result = std::to_string(frame_number);\n\n if (result.size() >= digit_padding)\n return result;\n\n auto const zeros_needed = (digit_padding - result.size());\n result.insert(result.begin(), zeros_needed, '0');\n\n return result;\n }\n\n std::string m_file_delim;\n FirstFilenameInfo m_info;\n};\n\n#include <iostream>\n\nint main()\n{\n std::string image_filename = \"prefix.00030.ext\";\n auto generator = FrameFilenameGenerator(image_filename);\n\n for (auto i = 0u; i != 20u; ++i)\n {\n auto in = generator.make_filename(i);\n auto out = generator.make_filename(i, \"_signature\");\n\n //if (!std::experimental::filesystem::exists(in))\n // break;\n\n std::cout << in << \" -> \" << out << \"\\n\";\n }\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:28:48.660",
"Id": "224663",
"ParentId": "224654",
"Score": "4"
}
},
{
"body": "<h3>Better use of standard library</h3>\n\n<p>Right now, you have:</p>\n\n<pre><code>std::string add_padding(int frame_num_in)\n{\n std::string outval = std::to_string(frame_num_in);\n\n int length = outval.length();\n while (length < digit_padding)\n {\n outval = \"0\" + outval;\n length = outval.length();\n }\n\n return outval;\n}\n</code></pre>\n\n<p>This strikes me as a fairly inefficient way to do the job. Lacking a specific reason to do otherwise, I'd probably use a <code>stringstream</code>:</p>\n\n<pre><code>std::string add_padding(int frame_num_in) { \n std::ostringstream buffer;\n\n buffer << std::setfill('0') << std::setw(digit_padding) << frame_num_in;\n return buffer.str();\n}\n</code></pre>\n\n<p>If you really want to do it as string manipulation rather than using a stream, you could eliminate a fair amount of work with a simple subtraction:</p>\n\n<pre><code>std::string add_padding(int frame_num_in)\n{\n std::string outval = std::to_string(frame_num_in);\n\n int pad_len = std::max(0, digit_padding - outval.length());\n\n return std::string(pad_len, '0') + outval;\n}\n</code></pre>\n\n<h3>Use applicable member functions</h3>\n\n<p>In <code>get_next_frame</code>, I'd change this:</p>\n\n<pre><code> else\n {\n name_out = \"\";\n next_frame = \"\";\n return false;\n }\n</code></pre>\n\n<p>..to use <code>.clear()</code> instead:</p>\n\n<pre><code>else \n{\n name_out.clear();\n next_frame.clear();\n return false;\n}\n</code></pre>\n\n<h3>Minimize Scopes</h3>\n\n<p>As a general rule, I'd prefer to give each variable as narrow a scope as possible. Right now, you have a number of class member variables that are really only used in a single function. In such a case, it's better to define them inside that function. If you can define them inside the body of a loop or <code>if</code> statement, that's even better.</p>\n\n<p>This not only keeps outside code from \"messing\" with something it shouldn't, but also makes the code considerably easier to read, since you don't need to look through the whole file to find things.</p>\n\n<h3>Construct regexes carefully</h3>\n\n<p>Right now you have:</p>\n\n<pre><code>std::regex match_pattern = std::regex(\"([a-zA-Z]*).([0-9]*).(\\\\w{3})\");\n</code></pre>\n\n<p>This has a bit of a problem: in a regex, a <code>.</code> means \"match any one character\". From the looks of the data you're using with the code, it seems nearly certain that you wanted to match only an actual <code>.</code>. You also allow each of the other sub-patterns to be empty, so (for example) this will match against a string like <code>\"[] \"</code>, which I'd guess really isn't intended.</p>\n\n<p>Unfortunately, you haven't documented what you really intended to require, so I can't suggest one that I'm sure is better. It looks like in the end, you mostly just want a pointer to the first digit in the string though. If so, it might be easier to just use <code>your_string.find_first_of(\"0123456789\")</code> and be done with it (unless you really need to verify the format of the input string, in which case I doubt the regex you're using suffices).</p>\n\n<h3>Avoid hard-coding where parameters make more sense</h3>\n\n<p>Most of this path:</p>\n\n<pre><code>tmpname = \"C:\\\\ProgramData\\\\NVIDIA Corporation\\\\CUDA Samples\\\\v9.0\\\\3_Imaging\\\\MovieHasher\\\\data\\\\\" + prefix + file_delim + add_padding(i) + file_delim + ext;\n</code></pre>\n\n<p>...should probably be supplied as a parameter to the program rather than hard-coded into the class--for most practical purposes, it restricts the code to running on your machine, for no particularly good reason.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T04:15:45.110",
"Id": "436771",
"Score": "0",
"body": "Here's an example of the files I was meaning to match with regex: filename.00000.ext"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T04:39:19.687",
"Id": "436775",
"Score": "0",
"body": "I updated the '*' searches to '+' searches in the regex where applicable.\nReally amazing feedback. I wish I could accept both answers, and hope I have the benefit of your reviews again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:04:50.657",
"Id": "224682",
"ParentId": "224654",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "224663",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T06:34:53.303",
"Id": "224654",
"Score": "5",
"Tags": [
"c++",
"iterator"
],
"Title": "Filename sequencer with outdated C++"
}
|
224654
|
<blockquote>
<p>Triangle, pentagonal, and hexagonal numbers are generated by the
following formulae:</p>
<ul>
<li>Triangle: <span class="math-container">\$T_n=\frac{n(n+1)}{2}\$</span> <code>1, 3, 6, 10, 15, …</code></li>
<li>Pentagonal: <span class="math-container">\$P_n=\frac{n(3n−1)}{2}\$</span> <code>1, 5, 12, 22, 35, …</code></li>
<li>Hexagonal: <span class="math-container">\$H_n=n(2n−1)\$</span> <code>1, 6, 15, 28, 45, …</code></li>
</ul>
<p>It can be verified that <span class="math-container">\$T_{285} = P_{165} = H_{143} = 40755\$</span>.</p>
<p>Find the next triangle number that is also pentagonal and hexagonal.</p>
</blockquote>
<pre><code>from time import time
def tri_pent_hex(n):
"""yields triangles that are also pentagons and hexagons in range n."""
triangles = set((num * (num + 1)) // 2 for num in range(1, n))
pentagons = set((num * (3 * num - 1)) // 2 for num in range(1, n))
hexagons = set(num * (2 * num - 1) for num in range(1, n))
for triangle in triangles:
if triangle in pentagons and triangle in hexagons:
yield triangle
if __name__ == '__main__':
start_time = time()
print(max(tri_pent_hex(1000000)))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[] |
[
{
"body": "<p>The way this was written, it was meant to steer you in the direction you did.</p>\n\n<blockquote>\n <p>Find the next triangle number that is also pentagonal and hexagonal.</p>\n</blockquote>\n\n<p>You loop the triangles to find matches in the others:</p>\n\n<blockquote>\n<pre><code>for triangle in triangles:\n if triangle in pentagons and triangle in hexagons:\n yield triangle\n</code></pre>\n</blockquote>\n\n<p>But if you think about it, there are more triangles than pentagons and more pentagons than hexagons. And since you need to find occurences where all 3 types match, wouldn't it be better to loop the hexagons, and find a match on the others from there?</p>\n\n<p>My point is: </p>\n\n<p><strong>Don't let the way a question is asked influence the way you implement an algorithm.</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:45:37.963",
"Id": "224664",
"ParentId": "224656",
"Score": "3"
}
},
{
"body": "<p>Instead of generating 3 million numbers and store them in memory, you only need to generate 3 of them at a time (one triangular, one pentagonal and one hexagonal) and compare them. The lowest should be advanced to the next of its kind and the processus repeated. That way you only generate the amount of numbers you need to achieve your goal and you don't put that much pressure on your memory.</p>\n\n<p>You can use 3 simples functions to generate each kind of number:</p>\n\n<pre><code>def triangular_numbers():\n n = 0\n while True:\n n += 1\n yield (n * (n + 1)) // 2\n\n\ndef pentagonal_numbers():\n n = 0\n while True:\n n += 1\n yield (n * (3 * n - 1)) // 2\n\n\ndef hexagonal_numbers():\n n = 0\n while True:\n n += 1\n yield (n * (2 * n - 1))\n</code></pre>\n\n<p>And combine them to generate each number that are the 3 at the same time:</p>\n\n<pre><code>def triangular_pentagonal_and_hexagonal_numbers():\n \"\"\"yields triangles that are also pentagons and hexagons.\"\"\"\n triangles = triangular_numbers()\n pentagons = pentagonal_numbers()\n hexagons = hexagonal_numbers()\n\n t = next(triangles)\n p = next(pentagons)\n h = next(hexagons)\n\n while True:\n if t == p == h:\n yield t\n m = min(t, p, h)\n if m == t:\n t = next(triangles)\n elif m == p:\n p = next(pentagons)\n else:\n h = next(hexagons)\n</code></pre>\n\n<p>You now only need to ask this function for the number you’re after:</p>\n\n<pre><code>def main():\n numbers = triangular_pentagonal_and_hexagonal_numbers()\n one = next(numbers)\n assert one == 1\n given = next(numbers)\n assert given == 40755\n return next(numbers)\n\n\nif __name__ == '__main__':\n print(main())\n</code></pre>\n\n<hr>\n\n<p>Now that it works, you can simplify the first 3 functions using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow noreferrer\"><code>itertools.count</code></a>:</p>\n\n<pre><code>def triangular_numbers():\n yield from ((n * (n + 1)) // 2 for n in count(start=1))\n\n\ndef pentagonal_numbers():\n yield from ((n * (3 * n - 1)) // 2 for n in count(start=1))\n\n\ndef hexagonal_numbers():\n yield from (n * (2 * n - 1) for n in count(start=1))\n</code></pre>\n\n<hr>\n\n<p>Comparing to your approach:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ python emadboctor.py \n1533776805\nTime: 1.0859220027923584 seconds.\n</code></pre>\n\n<p>Mine is around 20 times faster:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ python -m timeit 'import tri_pen_hexa; tri_pen_hexa.main()'\n5 loops, best of 5: 50.4 msec per loop\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:13:13.983",
"Id": "435808",
"Score": "0",
"body": "@ Mathias that approach you suggested, I did it before this one but i failed to go any further with it because I did not think about next-ing the trio, i made 3 functions with 3 generators and then i thought I need all numbers at once in a container for comparison because i don't know for what value of triangle will == both other numbers. Anyway i'll try your approach, thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:16:11.790",
"Id": "435809",
"Score": "0",
"body": "@ Mathias There is another problem I applied this mechanism it's called 'pentagon numbers' or something similar. You might check it if you want and tell me what you think."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:46:22.540",
"Id": "224665",
"ParentId": "224656",
"Score": "3"
}
},
{
"body": "<p><strong>Disclaimer</strong>: This is not a proper review. I just want to give a taste of how the Project Euler problems shall be addressed.</p>\n\n<p>Given a number <span class=\"math-container\">\\$x\\$</span>, it is triangular if there exist <span class=\"math-container\">\\$n\\$</span> such that</p>\n\n<p><span class=\"math-container\">\\$\\dfrac{n(3n-1)}{2} = x\\$</span></p>\n\n<p>Solving for <span class=\"math-container\">\\$n\\$</span>, gives <span class=\"math-container\">\\$n = \\dfrac{1 + \\sqrt{1 + 24x}}{6}\\$</span></p>\n\n<p>Similarly, for it to be pentagonal, there must be <span class=\"math-container\">\\$k\\$</span> such that</p>\n\n<p><span class=\"math-container\">\\$\\dfrac{k(k+1)}{2} = k\\$</span></p>\n\n<p>Solving for <span class=\"math-container\">\\$k\\$</span> gives <span class=\"math-container\">\\$k = \\dfrac{-1 + \\sqrt{1 + 8k}}{2}\\$</span></p>\n\n<p>It means that <span class=\"math-container\">\\$1 + 8x\\$</span> and <span class=\"math-container\">\\$1 + 24x\\$</span> must simultaneously be perfect squares. We may stop here. Generate hexagonal numbers and test them against a condition above. It is already better than <a href=\"https://codereview.stackexchange.com/a/224665/40480\">the solution above</a> (we only need to generate one sequence vs three), but just by a linear factor; besides, testing for something being a perfect square does not feel comfy. Let's continue.</p>\n\n<p>We are after integer <span class=\"math-container\">\\$u\\$</span> and <span class=\"math-container\">\\$v\\$</span> such that <span class=\"math-container\">\\$1 + 8x = u^2\\$</span> and <span class=\"math-container\">\\$1 + 24x = v^2\\$</span>. Excluding <span class=\"math-container\">\\$x\\$</span> results in <span class=\"math-container\">\\$v^2 - 3u^2 = -2\\$</span>. This is a variation of a famous <a href=\"https://en.wikipedia.org/wiki/Pell's_equation#Transformations\" rel=\"nofollow noreferrer\">Pell's equation</a>, and it is where a real efficiency comes from: the solutions of Pell's equation <em>grow exponentially fast</em>.</p>\n\n<p>Now, solve the Pell equation (it is trivial) for <span class=\"math-container\">\\$u_i, v_i\\$</span>. Recreate <span class=\"math-container\">\\$x_i\\$</span>. Test it to be a hexagonal number (yet another quadratic).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:00:19.360",
"Id": "435935",
"Score": "0",
"body": "Unless I am mistaken, you mixed up the formulas for triangular and pentagonal numbers. Note also that \\$ 1 + 24x \\$ being a perfect square is a necessary, but not a *sufficient* condition for a pentagonal number (example: \\$ x = 15 \\$)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T17:17:20.950",
"Id": "224690",
"ParentId": "224656",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224665",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T07:27:56.353",
"Id": "224656",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # Triangular, pentagonal and hexagonal in Python"
}
|
224656
|
<p>The following Python class is what I am trying to refactor in the case where I have to add validation of the existence of an AWS cloudformation stack before creating it in the method <strong>create_cfn_stack</strong> :</p>
<pre><code>import boto3
import botocore
from botocore.exceptions import ClientError
class AWSPlugin(object):
""" AWS Plugin class """
def __init__(**kwargs):
""" setting kwargs to class object variables"""
pass
def get_stack_info(self, stack_name):
""" returns the cloudformation stack details """
client_response = None
try:
cfn_client = self.get_client(AWS_SERVICES.CLOUDFORMATION)
response = cfn_client.describe_stacks(StackName=stack_name)
client_response = response['Stacks'].pop()
except ClientError as ce:
self.log.error("Failed to retrieve cloudformation stack object : %s", ce)
except Exception as e:
self.log.exception("Exception occurred while retrieving cloudformation stack object : %s", e)
return client_response
def create_cfn_stack(self, stack_name, cfn_template_file, parameters):
""" creates a cloudformation stack """
client_response = None
try:
with open(cfn_template_file, 'r') as jfp:
template_body = jfp.read()
cfn_client = self.get_client(AWS_SERVICES.CLOUDFORMATION)
cfn_response = cfn_client.create_stack(
StackName=stack_name,
TemplateBody=template_body,
Parameters=parameters,
DisableRollback=False,
Tags=[
{
'Key': 'Name',
'Value': stack_name
},
]
)
client_response = cfn_response['StackId']
except ClientError as ce:
self.log.error("Failed to create cloudformation stack : %s", ce)
except Exception as e:
self.log.exception("Exception occurred while creating cloudformation stack : %s", e)
return client_response
</code></pre>
<p>There are 3 ways the code can could be refactored as shown here :</p>
<p><strong>Way 1:</strong></p>
<pre><code>def create_cfn_stack(self, stack_name, cfn_template_file, parameters):
""" creates a cloudformation stack """
client_response = None
try:
existing_stack = self.get_stack_info(stack_name)
if existing_stack is not None:
raise Exception("Stack %s is already exists and in %s state" %(stack_name, existing_stack['Status']))
except ClientError as ce:
print "Stack is not present and its good to create with name %s" % (stack_name)
with open(cfn_template_file, 'r') as jfp:
template_body = jfp.read()
cfn_client = self.get_client(AWS_SERVICES.CLOUDFORMATION)
cfn_response = cfn_client.create_stack(
StackName=stack_name,
TemplateBody=template_body,
Parameters=parameters,
DisableRollback=False,
Tags=[
{
'Key': 'Name',
'Value': stack_name
},
]
)
client_response = response['StackId']
except Exception as e:
self.log.exception("Exception occurred while creating cloudformation stack : %s", e)
return client_response
</code></pre>
<p><strong>Way 2</strong></p>
<pre><code>def create_cfn_stack(self, stack_name, cfn_template_file, parameters):
""" creates a cloudformation stack """
client_response = None
try:
try:
existing_stack = self.get_stack_info(stack_name)
if existing_stack is not None:
raise Exception("Stack %s is already exists and in %s state" %(stack_name, existing_stack['Status']))
except ClientError as ce:
print "Stack is not present and its good to create with name %s" % (stack_name)
with open(cfn_template_file, 'r') as jfp:
template_body = jfp.read()
cfn_client = self.get_client(AWS_SERVICES.CLOUDFORMATION)
cfn_response = cfn_client.create_stack(
StackName=stack_name,
TemplateBody=template_body,
Parameters=parameters,
DisableRollback=False,
Tags=[
{
'Key': 'Name',
'Value': stack_name
},
]
)
client_response = cfn_response['StackId']
except ClientError as ce:
self.log.error("Failed to create cloudformation stack : %s", ce)
except Exception as e:
self.log.exception("Exception occurred while creating cloudformation stack : %s", e)
return client_response
</code></pre>
<p><strong>Way 3</strong></p>
<pre><code>def create_cfn_stack(self, stack_name, cfn_template_file, parameters):
""" creates a cloudformation stack """
client_response = None
try:
existing_stack = self.get_stack_info(stack_name)
if existing_stack is not None:
raise Exception("Stack %s is already exists and in %s state" %(stack_name, existing_stack['Status']))
except ClientError as ce:
print "Stack is not present and its good to create with name %s" % (stack_name)
try:
with open(cfn_template_file, 'r') as jfp:
template_body = jfp.read()
cfn_client = self.get_client(AWS_SERVICES.CLOUDFORMATION)
cfn_response = cfn_client.create_stack(
StackName=stack_name,
TemplateBody=template_body,
Parameters=parameters,
DisableRollback=False,
Tags=[
{
'Key': 'Name',
'Value': stack_name
},
]
)
client_response = cfn_response['StackId']
except ClientError as ce:
self.log.error("Failed to create cloudformation stack : %s", ce)
except Exception as e:
self.log.exception("Exception occurred while creating cloudformation stack : %s", e)
return client_response
</code></pre>
<p>Among 3 or apart from what I have shared here, I am not sure what is the standardized way to handle such a scenario. Helping hands are very much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T12:12:52.483",
"Id": "435827",
"Score": "0",
"body": "I don't get it. Why do you expect to get a `ClientError` when calling `self.get_stack_info(stack_name)`? It's already handled in there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:25:31.533",
"Id": "435838",
"Score": "0",
"body": "I am using AWS python SDK called `boto3`. If any AWS related exceptions/errors caught, then it ll falls under `ClientError`. \nIn this scenario, I wanted to create an AWS resource in the specified name which should not exist when I call this method. To validate that, I called another method called `get_stack_info()` which returns detailed info about stack if exists else it'll throw ClientError. I have to react to both the situation and act accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:47:45.080",
"Id": "435842",
"Score": "0",
"body": "Except the `ClientError` is caught in `get_stack_info` and never get a chance to bubble up to `create_cfn_stack` (which makes the first solution broken, ihmo)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:10:20.160",
"Id": "435853",
"Score": "0",
"body": "Please include the relevant `import` statements for clarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T17:10:26.127",
"Id": "435864",
"Score": "0",
"body": "@MathiasEttinger, I agree with you. But the challenge here is, I have to avert the blast would be created by the **get_stack_info** method and proceed to create a new resource in the case of no resource with a given name is present."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T10:57:38.290",
"Id": "224666",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"error-handling",
"amazon-web-services"
],
"Title": "AWS plugin to create a CloudFormation stack if it doesn't exist"
}
|
224666
|
<p>I would like to share a matplotlib real-time monitor plot that I needed for another application. Basic trick is to reverse the time, so that t=0 is now and t=20 is twenty seconds in the past and to plot the signal from 0 at the right towards the left. The core method is <code>update</code> that reverses time using the <code>deque</code> <code>appendleft</code> and applying a reverse axis by <code>self.ax_monitor.set_xlim(self.monitor_time_window_s, 0)</code>, i.e. from high to low, rather than the typical low to high.</p>
<p>The following code is a running example:
(requirements <code>matplotlib</code> and <code>numpy</code>)</p>
<pre><code>from collections import deque
import time
import numpy as np
import matplotlib.pyplot as plt
fps = 24
seconds_per_frame = 1 / fps
class Monitor():
''' class to monitor value versus time
'''
def __init__(self, figsize=(5, 2), monitor_window=10, update_interval=0.1,
ymin=-1, ymax=1, ticks=None):
self.monitor_time_window_s = monitor_window
self.update_monitor_interval_s = update_interval
self.fig_monitor, self.ax_monitor = plt.subplots(
1, 1, figsize=figsize)
self.ax_monitor.set_ylim(ymin, ymax)
if ticks is None:
ticks = [ymin, 0, ymax]
self.ax_monitor.set_yticks(ticks)
self.ax_monitor.tick_params(axis='y', which='major', labelsize=6)
self.ax_monitor.tick_params(axis='x', which='major', labelsize=6)
self.ax_monitor.grid(True)
self.fig_monitor.tight_layout()
self.monitor_plot, = self.ax_monitor.plot(
[0], [0], color='black', linewidth=0.5)
self.ax_monitor.set_xlim(self.monitor_time_window_s, 0)
@property
def update_time_s(self):
return self.update_monitor_interval_s
@property
def monitor_fig(self):
return self.fig_monitor
@property
def monitor_ax(self):
return self.ax_monitor
def set_fig_title(self, title='Monitor Figure'):
self.fig_monitor.canvas.set_window_title(title)
def set_ax_title(self, title='Monitor'):
self.ax_monitor.set_title(title)
self.fig_monitor.tight_layout()
def blit(self):
self.fig_monitor.canvas.draw()
self.fig_monitor.canvas.flush_events()
def update(self, _time, value):
''' method to plot value in time_window_graphs, time is
past time, so t=0 is now and t=20 is 20 seconds ago
'''
# reset when time is zero
if _time < self.update_monitor_interval_s:
self.monitor_values = []
self.time_values_reversed = deque([])
self.time_reversed = []
# build the time_reversed list (in reversed order to represent
# time passed) and trim the monitor_values so they keep the
# a finite length
self.monitor_values.append(value)
if _time < self.monitor_time_window_s + self.update_monitor_interval_s:
self.time_values_reversed.appendleft(_time)
self.time_reversed = list(self.time_values_reversed)
else:
self.monitor_values.pop(0)
self.monitor_plot.set_data(self.time_reversed, self.monitor_values)
def run_monitor(event, monitor):
def current_time():
return time.time()
_time = 0
actual_start_time = current_time()
while True:
value = np.sin(_time) - 0.5 + np.random.random_sample()
if _time % monitor.update_time_s < seconds_per_frame:
monitor.update(_time, value)
monitor.blit()
_time += seconds_per_frame
# wait for actual time to catch up with model time _time
running_time = current_time() - actual_start_time
while running_time < _time:
running_time = current_time() - actual_start_time
def main():
monitor = Monitor(monitor_window=20, ymin=-1.6, ymax=1.6,
ticks=[-1.5, -1.0, -0.5, 0.0, +0.5, 1.0, 1.5])
monitor.set_fig_title('Press any key to start ...')
monitor.set_ax_title()
monitor.monitor_fig.canvas.mpl_connect(
'key_press_event', lambda event: run_monitor(event, monitor))
plt.show()
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T11:58:07.187",
"Id": "224667",
"Score": "2",
"Tags": [
"python",
"animation",
"matplotlib"
],
"Title": "Matplotlib realtime monitor"
}
|
224667
|
<p>I'm doing an experiment trying to freshen up my unit-testing and learn dynamic programming. Every test passes but I'm curious of the result of some of them and worried if I'm doing the testing correctly. Currently I just got the one scenario for each method, with the input of 40, the goal of this test is to test which method is the most efficient for large numbers. </p>
<blockquote>
<pre><code>Test result are as follow:
BottomUp: 7 ms
DynamicFibonacci: 5 sec
DynamicFibonacci2: 8 ms
MatrixFibonacci: 7 ms
EfficientMatrix: 8 ms
PiVersion: 7 ms
RecursiveFibonacci: 4 sec
</code></pre>
</blockquote>
<p>I understand the slowness of the recursive, that one makes sense since it does not store the value. The efficientmatrix is however only 1 ms faster and in some test the time even seem to be the same. DynamicFibonacci1 I don't get at all why it's so slow, it should be very similiar to version 2 but the time difference is huge. It's even slower than the recursive one where it does not memoize. </p>
<p>I ran all test individually since I noticed the result differed wildly otherwise, I believe the array value was stored when running them all at once, but that did not seem to be the case when debugging the test individually. </p>
<p>My question is, how can I improve my tests, both method wise and the testing process. It feels like I get slightly different test result just running them once, is there a better way to run several time in a for loop maybe? It just seems like I can't really compare the results this way.</p>
<p>Which method is generally the best to use when using large numbers/heavy calculations like this? I'm originally a mobile Xamarin developer and just trying to learn a bit more on how to speed up some of my other work. </p>
<p>TEST Class // sample method, all of them look the same except calling the different methods. </p>
<pre><code>[TestClass]
public class FibonacciSequenceTest
{
private const long Number = 40;
private const long Result = 102334155;
private readonly FibonacciSequence fibonacciSequence;
public FibonacciSequenceTest()
{
fibonacciSequence = new FibonacciSequence();
}
[TestMethod]
public void MatrixFibonacciCalculatorTest()
{
// Act
var returnValue = fibonacciSequence.MatrixFibonacciCalculator(Number);
// Assert
long actual = returnValue;
Assert.AreEqual(actual, Result);
}
}
</code></pre>
<p>Class and methods</p>
<pre><code>public class FibonacciSequence
{
private readonly long max = 1000;
private readonly long[] memoizedFibonacciNumbers;
public FibonacciSequence()
{
memoizedFibonacciNumbers = new[] { max };
}
#region MatrixFibonnaciCalculator
public long MatrixFibonacciCalculator(long n)
{
long[,] f = { { 1, 1 }, { 1, 0 } };
if (n == 0)
return 0;
PowerMatrix1(f, n - 1);
return f[0, 0];
}
/* Helper function that multiplies 2
matrices F and M of size 2*2, and puts
the multiplication result back to F[][] */
public void MultiplyMatrix1(long[,] F, long[,] M)
{
long x = F[0, 0] * M[0, 0] + F[0, 1] * M[1, 0];
long y = F[0, 0] * M[0, 1] + F[0, 1] * M[1, 1];
long z = F[1, 0] * M[0, 0] + F[1, 1] * M[1, 0];
long w = F[1, 0] * M[0, 1] + F[1, 1] * M[1, 1];
F[0, 0] = x;
F[0, 1] = y;
F[1, 0] = z;
F[1, 1] = w;
}
/* Helper function that calculates F[][]
raise to the power n and puts the result
in F[][] Note that this function is designed
only for fib() and won't work as general
power function */
public void PowerMatrix1(long[,] F, long n)
{
long i;
var M = new long[,] { { 1, 1 }, { 1, 0 } };
// n - 1 times multiply the matrix to
// {{1,0},{0,1}}
for (i = 2; i <= n; i++)
MultiplyMatrix1(F, M);
}
#endregion
#region EfficentMatrixFibonacciCalculator
public long EfficientMatrixFibonacciCalculator(long n)
{
var f = new long[,] { { 1, 1 }, { 1, 0 } };
if (n == 0)
return 0;
EfficientPowerMatrix(f, n - 1);
return f[0, 0];
}
public void EfficientPowerMatrix(long[,] F, long n)
{
if (n == 0 || n == 1)
return;
var M = new long[,] { { 1, 1 }, { 1, 0 } };
EfficientPowerMatrix(F, n / 2);
EfficientMultiplyMatrix(F, F);
if (n % 2 != 0)
EfficientMultiplyMatrix(F, M);
}
public void EfficientMultiplyMatrix(long[,] f, long[,] m)
{
long x = f[0, 0] * m[0, 0] + f[0, 1] * m[1, 0];
long y = f[0, 0] * m[0, 1] + f[0, 1] * m[1, 1];
long z = f[1, 0] * m[0, 0] + f[1, 1] * m[1, 0];
long w = f[1, 0] * m[0, 1] + f[1, 1] * m[1, 1];
f[0, 0] = x;
f[0, 1] = y;
f[1, 0] = z;
f[1, 1] = w;
}
#endregion
public int IterativeFibonacciCalculator(long number)
{
int firstNumber = 0, secondNumber = 1, result = 0;
if (number == 0) return 0; // To return the first Fibonacci number
if (number == 1) return 1; // To return the second Fibonacci number
for (var i = 2; i <= number; i++)
{
result = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = result;
}
return result;
}
public long RecursiveFibonacciCalculator(long number)
{
if (number <= 1)
{
return number;
}
return RecursiveFibonacciCalculator(number - 1) + RecursiveFibonacciCalculator(number - 2);
}
public long DynamicFibonacciCalculator(long number)
{
long result;
var memoArrays = new long[number + 1];
if (memoArrays[number] != 0) return memoArrays[number];
if (number == 1 || number == 2)
{
result = 1;
}
else
{
result = DynamicFibonacciCalculator(number - 1) + DynamicFibonacciCalculator(number - 2);
memoArrays[number] = result;
}
return result;
}
public long DynamicFibonacciCalculator2(long n)
{
// Declare an array to
// store Fibonacci numbers.
// 1 extra to handle
// case, n = 0
var f = new long[n + 2];
long i;
/* 0th and 1st number of the
series are 0 and 1 */
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++)
/* Add the previous 2 numbers
in the series and store it */
f[i] = f[i - 1] + f[i - 2];
return f[n];
}
// Helper method for PiCalculator
public long PiFibonacciCalculator(long n)
{
double phi = (1 + Math.Sqrt(5)) / 2;
return (long)Math.Round(Math.Pow(phi, n) / Math.Sqrt(5));
}
public long BottomUpFibonacciCalculator(long n)
{
long a = 0, b = 1;
// To return the first Fibonacci number
if (n == 0) return a;
for (long i = 2; i <= n; i++)
{
long c = a + b;
a = b;
b = c;
}
return b;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T10:15:49.453",
"Id": "435956",
"Score": "0",
"body": "F(40) isn't exactly a large number. Here's an [efficient algorithm in Java](https://codereview.stackexchange.com/a/184955/139491) which calculates F(10000000) in less than 2 seconds on my laptop. And [here's](https://codereview.stackexchange.com/a/183262/139491) more info about the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T11:12:49.533",
"Id": "436124",
"Score": "0",
"body": "I guess, the goal however was just to test out dynamic programming a bit and see how it compares to a iterative function. What I learned is, dynamic programming is definently useful but MAN for loops are pretty darn fast"
}
] |
[
{
"body": "<p><code>DynamicFibonacciCalculator</code> is slow because you create a new <code>memoArrays</code> for each recursion, so it will never contain any precalculated values, and it behave just as the normal recursive version (and even worse because of the overhead of allocating the arrays.</p>\n\n<blockquote>\n<pre><code>public long DynamicFibonacciCalculator(long number)\n{\n long result;\n var memoArrays = new long[number + 1];\n ...\n</code></pre>\n</blockquote>\n\n<p>You should maintain the <code>memoArrays</code> outside of the recursion method. You could maybe do the recursion in an local function: </p>\n\n<pre><code>public static long DynamicFibonacciCalculator(long number)\n{\n if (num <= 1)\n {\n return num;\n }\n\n long[] memoArrays = new long[number + 1];\n\n long Recursion(long num)\n {\n if (num <= 1)\n {\n return num;\n }\n\n long result;\n\n if (memoArrays[num] != 0)\n {\n return memoArrays[num];\n ....\n\n }\n\n return Recursion(number);\n}\n</code></pre>\n\n<hr>\n\n<p>All your methods don't depend on instance members, so it would be more correct to make them <code>static</code> (and the helpers could be <code>static</code> as well):</p>\n\n<pre><code> public static class FibonacciSequence\n {\n #region MatrixFibonnaciCalculator\n\n public static long MatrixFibonacciCalculator(long n)\n {\n long[,] f = { { 1, 1 }, { 1, 0 } };\n if (n == 0)\n return 0;\n ...\n</code></pre>\n\n<hr>\n\n<p>You could optimize the test class by making a common test method that takes a delegate as argument:</p>\n\n<pre><code>public class FibonacciSequenceTest\n{\n private const long Number = 40;\n private const long Result = 102334155;\n\n public FibonacciSequenceTest()\n {\n }\n\n public void FibonacciTester(Func<long, long> method, string methodName)\n {\n // Act\n var returnValue = method(Number);\n\n // Assert\n long actual = returnValue;\n Assert.AreEqual(actual, Result, $\"{methodName} produced wrong result.\");\n }\n\n [TestMethod]\n public void TestBottomUpFibonacciCalculator()\n {\n FibonacciTester(FibonacciSequence.BottomUpFibonacciCalculator, nameof(FibonacciSequence.BottomUpFibonacciCalculator));\n }\n\n // TODO: Test methods for each Fib method...\n\n\n}\n</code></pre>\n\n<p>In this way it is easier to maintain, and you avoid repeating yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:10:53.277",
"Id": "435846",
"Score": "0",
"body": "This is the whole _functional_ vs _interface_ approach dilemma. You would opt for _static_ classes and executing them with _Func_. I would favor an _interface_ and instances rather than static classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:18:00.237",
"Id": "435847",
"Score": "0",
"body": "@dfhwze: Normally I agree in that, but I regard the `Fibonacci` method just as another `Math` function for which it would be tedious if you would have to instantiate a `Math` object each time you need one of its methods (`Sqrt()`, `Pow()`, etc.) - You could of course have a global `Math` instance hanging around, but that is \"ugly\" IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:21:05.540",
"Id": "435848",
"Score": "0",
"body": "I would also agree the chosen algorithm should end up as _Math.Fibonacci_ or something like that. For the sake of comparing several methods, I would use an interface (for this trivial domain). So yes, in production code, I agree with the static function in a Math library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:53:59.623",
"Id": "435860",
"Score": "0",
"body": "Hey @HenrikHansen, great answer! Especially with the delegate, combining that one with the benchmark should really improve my tests! The one thing i'm unsure about is the static one, I honestly don't understand when it's best to use static and when it's best to use instances. Could you explain further why static or maybe you got a good link to read regarding this? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:12:30.087",
"Id": "435869",
"Score": "2",
"body": "@JsonDork: If a method or function has no [side effects](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) and its result is only dependent on its argument (produce the same result for the same arguments when called more than once), it may be candidate as a static method - in functional programming it's called a [pure function](https://en.wikipedia.org/wiki/Pure_function)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:04:08.207",
"Id": "224679",
"ParentId": "224669",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p><em>Currently I just got the one scenario for each method, with the input\n of 40, the goal of this test is to test which method is the most\n efficient for large numbers.</em></p>\n</blockquote>\n\n<p>Running one iteration of a test case is not resilient to external interference. What if your CPU is doing other stuff at the same time. To get better comparison results, you should <em>benchmark</em> tests.</p>\n\n<p><a href=\"https://jonskeet.uk/csharp/benchmark.html\" rel=\"noreferrer\">Jon Skeet's Micro-benchmark Framework</a> might be an option, or you could roll out your own benchmark tests.</p>\n\n<p>A trivial example of a benchmark test to get an idea:</p>\n\n<pre><code> [TestMethod]\n public void TestBottomUpFibonacciCalculator()\n {\n for (int i = 0; i < 10000; i++)\n {\n FibonacciTester(FibonacciSequence.BottomUpFibonacciCalculator,\n nameof(FibonacciSequence.BottomUpFibonacciCalculator));\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:50:37.117",
"Id": "435859",
"Score": "1",
"body": "Woah! Thanks! This one is really good, didn't know about benchmark but will try to change it to one instead/read up on it a bit more. But this really helps me, because manually running tests always seemed like a unreliable way of doing them. Great answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:19:37.647",
"Id": "224680",
"ParentId": "224669",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "224679",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T12:39:12.870",
"Id": "224669",
"Score": "12",
"Tags": [
"c#",
"performance",
"unit-testing",
"comparative-review",
"fibonacci-sequence"
],
"Title": "Calculating Fibonacci sequence in several different ways"
}
|
224669
|
<p>I was looking for comments (on performance and general implementation) on the following Linked HashMap implementation in C:</p>
<pre><code>typedef int (*cmp)(void *a, void *b);
typedef size_t (*hash_fn)(void *val, int bound);
typedef struct {
int index;
size_t hash;
void *key;
void *val;
struct Entry *next;
struct Entry *neighbor;
} Entry;
typedef struct {
Entry *head;
Entry *tail;
int size;
int capacity;
Entry **table;
int threshold;
float loadFactor;
cmp key_cmp;
hash_fn hash;
} HashMap;
void resize(HashMap **map);
void internal_init(HashMap **map, cmp key_cmp, hash_fn hash, int capacity) {
(*map) = (HashMap *) calloc(1, sizeof(HashMap));
(*map)->head = (*map)->tail = NULL;
(*map)->size = 0;
(*map)->capacity = capacity;
(*map)->key_cmp = key_cmp;
(*map)->hash = hash;
(*map)->loadFactor = 0.75f;
(*map)->threshold = (int) ((*map)->capacity * (*map)->loadFactor);
(*map)->table = calloc(capacity, sizeof(Entry *));
for (int i = 0; i < capacity; i++) {
(*map)->table[i] = NULL;
}
}
void init(HashMap **map, cmp key_cmp, hash_fn hash) {
internal_init(map, key_cmp, hash, 16);
}
int indexOf(HashMap *map, void *key) {
int ret = 0;
for (Entry *e = map->head; e != NULL; e = (Entry *) e->next) {
if (map->key_cmp(e->key, key)) {
return ret;
}
ret++;
}
return -1;
}
int internal_put(HashMap **map, void *key, void *val) {
// 1. Create entry
Entry *entry = calloc(1, sizeof(Entry));
entry->key = key;
entry->val = val;
entry->next = NULL;
// Calculate hash and get entry
size_t key_hash = (*map)->hash(key, (*map)->capacity);
Entry *tableEntry = (*map)->table[key_hash];
// If bucket has at least one element
if (tableEntry != NULL) {
while (tableEntry->neighbor != NULL) {
if ((*map)->key_cmp(tableEntry->key, key)) {
// Key already exists
tableEntry->val = val;
return tableEntry->index;
}
tableEntry = (Entry *) tableEntry->neighbor;
}
if ((*map)->key_cmp(tableEntry->key, key)) {
// Key already exists
tableEntry->val = val;
return tableEntry->index;
}
// Key was not found in the bucket
entry->neighbor = (struct Entry *) (*map)->table[key_hash];
}
entry->hash = key_hash;
(*map)->table[key_hash] = entry;
// Append to list
if ((*map)->head == NULL && (*map)->tail == NULL) {
(*map)->head = (*map)->tail = entry;
entry->index = 1;
} else {
entry->index = (*map)->tail->index + 1;
(*map)->tail->next = (struct Entry *) entry;
(*map)->tail = (Entry *) (*map)->tail->next;
}
(*map)->size++;
return entry->index;
}
int put(HashMap **map, void *key, void *val) {
int ret = internal_put(map, key, val);
if ((*map)->size >= (*map)->threshold) {
resize(map);
}
return ret;
}
void *get(HashMap *map, void *key) {
size_t key_hash = map->hash(key, map->capacity);
if (map->table[key_hash] != NULL) {
Entry *el = map->table[key_hash];
while (el != NULL) {
if (map->key_cmp(el->key, key)) {
return el->val;
}
el = (Entry *) el->neighbor;
}
}
return NULL;
}
void resize(HashMap **map) {
HashMap *newMap;
internal_init(&newMap, (*map)->key_cmp, (*map)->hash, (*map)->capacity * 2);
Entry *e = (*map)->head;
while (e != NULL) {
internal_put(&newMap, e->key, e->val);
e = (Entry *) e->next;
}
(*map) = newMap;
}
int containsKey(HashMap *map, void *key) {
return get(map, key) != NULL;
}
</code></pre>
<p>I maintain a linked list in each bucket as well as a central linked list (starting at “head”). On insertion, I add into the correct bucket as well as the tail in order to maintain the insertion order.
Please let me know if you need any more information.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:23:00.987",
"Id": "435849",
"Score": "0",
"body": "This would be a better question if all included header files were shown and if the code that creates the the hashmap and uses the hasmap were shown. It is not currently clear that the code works."
}
] |
[
{
"body": "<p>We need to include <code><stdlib.h></code>, to have a prototype for <code>calloc()</code>.</p>\n\n<hr>\n\n<p>There's no definition of <code>struct Entry</code> here; this isn't valid C:</p>\n\n<pre><code>typedef struct {\n struct Entry *next;\n struct Entry *neighbor;\n} Entry;\n</code></pre>\n\n<hr>\n\n<p>Let's have a look at how we create a <code>HashMap</code> object:</p>\n\n<blockquote>\n<pre><code> (*map) = (HashMap *) calloc(1, sizeof(HashMap));\n</code></pre>\n</blockquote>\n\n<p>It's not necessary to cast the result of the <code>malloc()</code> family of functions, and can be considered harmful to do so.</p>\n\n<p>Something that <em>is</em> necessary, but is absent, is a test that the return value is non-null before it's used.</p>\n\n<p>It's better to return the <code>map</code> pointer than to assign it via pointer to pointer.</p>\n\n<p>It also helps to use the size of <code>*map</code> rather than of <code>(HashMap)</code>, as it's then easier to visually match that the code is correct.</p>\n\n<p>There's no benefit to using <code>calloc()</code> rather than <code>malloc()</code>, as we're initializing all members programmatically. Using <code>calloc()</code> just wastes the processor's time.</p>\n\n<p>Those changes lead to</p>\n\n<pre><code> map = malloc(sizeof *map);\n if (!map) { return map; }\n</code></pre>\n\n<hr>\n\n<p>The function to free a hash map seems to be completely missing.</p>\n\n<p>It seems strange to use <code>int</code> rather than <code>size_t</code> for <code>size</code> and <code>capacity</code> members.</p>\n\n<p>There's more unnecessary casts in many places:</p>\n\n<blockquote>\n<pre><code>for (Entry *e = map->head; e != NULL; e = (Entry *) e->next) {\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> entry->neighbor = (struct Entry *) (*map)->table[key_hash];\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> (*map)->tail = (Entry *) (*map)->tail->next;\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:24:12.870",
"Id": "224675",
"ParentId": "224670",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:14:12.073",
"Id": "224670",
"Score": "0",
"Tags": [
"performance",
"c",
"hash-map"
],
"Title": "Linked HashMap in C"
}
|
224670
|
<p>The following code evaluates probability mass function for all possible states of a model. </p>
<pre><code>def PDF(size):
b = np.random.randn(size)
J = np.random.randn(size, size)
density_func = np.zeros(2**size)
states = dec2bin(size)
for i in range(2**size):
density_func[i] = np.exp((np.dot(b, states[i,:]) + np.dot(np.dot(states[i],J),states[i])))
Z = np.sum(density_func)
density_func = density_func / Z
return density_func
</code></pre>
<p>utility functions </p>
<pre><code>def bitfield(n,size):
x = [int(x) for x in bin(n) [ 2 :]]
x = [0] * (size - len(x)) + x
return x
def dec2bin(size):
states = []
for i in range(2**size):
binary = bitfield(i, size)
states.append(binary)
return np.array(states)
</code></pre>
<p>The model is grid graph Markov random field. Each node of the graph can have two states {0, 1}, so the total number of possible states of the model is 2<sup>total number of nodes</sup>. Each instance of the <code>for</code> loop is calculating the probability of that state. At end I want to calculate the joint probability distribution of all the nodes. The joint probability distribution of this model is as follows </p>
<p><span class="math-container">$$
p(\mathbf{x}) = \tfrac{1}{z} exp(\mathbf{b}\cdot\mathbf{x} + \mathbf{x}\cdot\mathbf{J}\cdot\mathbf{x})
$$</span></p>
<p><span class="math-container">\$b\$</span> and <span class="math-container">\$J\$</span> are model parameters and <span class="math-container">\$x\$</span> is a vector of present states of the system. </p>
<p><span class="math-container">\$Z\$</span> is the normalizing constant which is calculated by summing up 'values' of each possible state of the system to convert them into probabilities. </p>
<p>When the variable <code>size</code> is greater than 25 the code takes long time to execute. Is there a way to vectorize this code and speed it up? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:43:19.033",
"Id": "435834",
"Score": "2",
"body": "Welcome to Code Review! I will help reviewers if you describe the problem you are trying to solve in more detail. At the moment its not immediately obvious why the system is modeled as it is in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:04:10.037",
"Id": "435836",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:17:23.943",
"Id": "435837",
"Score": "3",
"body": "I have added more context to my question and changed the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:36:54.317",
"Id": "435839",
"Score": "1",
"body": "You can use [MathJax](https://codereview.meta.stackexchange.com/a/1708/92478) here on Code Review to typeset your math expressions directly in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T22:15:07.357",
"Id": "435911",
"Score": "0",
"body": "I have edited the code. Apologies for the mixup."
}
] |
[
{
"body": "<p>A first go at the problem:</p>\n\n<h2>Generating the states</h2>\n\n<p>Since you are generating all possible bit patterns with a given number of bits, it's wasteful to first create a binary representation as a string, and then convert it back to integers digit by digit. As often <code>itertools</code> can help you here. Especially <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a>. Your use case is basically one of the examples given in its documentation.</p>\n\n<pre><code>from itertools import product\n\ndef generate_all_possible_states(size):\n states = np.empty((2**size, size))\n for i, value in enumerate(product((0, 1), repeat=size)):\n states[i, :] = value\n return states\n</code></pre>\n\n<p>The reimplementation also avoids the dynamically growing list and allocates a numpy array of appropriate size beforehand.</p>\n\n<h2>Moving repeated computations</h2>\n\n<p>You are calculating <code>exp</code> for every single scalar that you put in <code>density_func</code>. That is wasteful since it does not allow numpy to play its strengths, namely applying the same operation to a lot of values aka vectorization. Fortunately, there is an easy way out (ot the loop ;-)) and you can just compute <code>np.exp</code> on the whole <code>density_func</code> vector.</p>\n\n<p>The first part of the sum can also be easily moved out of the loop.</p>\n\n<pre><code>density_func = np.empty(2**size)\nfor i in range(2**size):\n density_func[i] = np.dot(np.dot(states[i], J), states[i])\n\ndensity_func += np.dot(states, b)\ndensity_func = np.exp(density_func)\n# maybe a teeny-tiny bit faster:\n# density_func = np.exp(density_func + np.dot(states, b))\n</code></pre>\n\n<p>The order of operation matters here. Intializing <code>density_func</code> to <code>np.dot(states, b)</code> and then adding the results in the loop like <code>density_func[i] += np.dot(np.dot(states[i], J), states[i])</code> is consistently slower.</p>\n\n<hr>\n\n<h2>Preliminary timing</h2>\n\n<p>As an example, for <code>size = 18</code>, your original implementation takes about <span class=\"math-container\">\\$5.5s\\$</span> here on my machine. With just the two modifications above, you can get down to <span class=\"math-container\">\\$1.9s\\$</span> (both with the same fixed seed for the random numbers). </p>\n\n<ul>\n<li><code>size = 20</code>: <span class=\"math-container\">\\$23.4s\\$</span> vs. <span class=\"math-container\">\\$8.0s\\$</span></li>\n<li><code>size = 21</code>: <span class=\"math-container\">\\$47.9s\\$</span> vs. <span class=\"math-container\">\\$16.4s\\$</span></li>\n</ul>\n\n<p>Maybe I will have time to revisit this later on this week to update the answer with a proper analysis on how both of them scale for larger sizes. My strong intuition at this point would be that they both have a complexity of <span class=\"math-container\">\\$\\mathcal{O}(2^n)\\$</span> and the difference between them will actually remain a constant factor (<span class=\"math-container\">\\$\\approx 3\\times\\$</span> faster).</p>\n\n<hr>\n\n<h3>Things that didn't work (so far)</h3>\n\n<p>Things that I tried, that didn't work for me:</p>\n\n<ol>\n<li><p>Eliminating the magic of <code>np.dot</code> and explicitely using <code>np.inner</code> or <code>np.matmul</code> / <code>@</code> (in Python 3). <code>np.dot</code> seems to have some tricks up its sleeves and is still faster. Maybe I will have to read the doc more carefully.</p></li>\n<li><p>Trying to compute the second part of the sum in a vectorized manner. I'm a little bit too tired at the moment to come up with a clever solution to this.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T09:13:25.210",
"Id": "436316",
"Score": "0",
"body": "I have run your code and timed both of the ways using `timeit`. I'm also seeing a ~3x speedup. For n = 21, my code clocked 6.21s per loop and your code clocked 2.49s with numba.jit it clocked 0.548s per loop. That's a great a speedup. I'm eagerly for your further analysis. How do I train myself to write optimized code like this, any suggestions ? Thank you for the help :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T14:25:57.810",
"Id": "436346",
"Score": "0",
"body": "I just found out another way to do this with no `for` loop and all matrices which is in total 6x faster than my first attempt but I could only verify this for n = 10, anything more than that I'm running out of memory and for some `n` its slower than your method. This is the code to my method \n\nhttps://pastebin.com/2D64jQQr"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T14:28:41.993",
"Id": "436348",
"Score": "0",
"body": "Basically I do the operations as shown in the original equation in the question and do trace(result) to get the PDF. Maybe if I use `np.einsum` it would be faster because I'm doing a lot of wasteful calculations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T17:33:40.100",
"Id": "436401",
"Score": "0",
"body": "I have also come up with the solution you posted on pastebin, but hit the same out of memory error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T20:33:33.633",
"Id": "436428",
"Score": "1",
"body": "Regarding your other question: [Python Data Science Handbook](https://jakevdp.github.io/PythonDataScienceHandbook/) by Jake VanderPlas as well as his PyCon talks ([2017](https://www.youtube.com/watch?v=ZyjCqQEUa8o), [2018](https://www.youtube.com/watch?v=zQeYx87mfyw)) are a good start to get going with optimization potential."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T20:44:17.393",
"Id": "436430",
"Score": "0",
"body": "Thanks for the recommendation, I'll look into them. Is there any way to prevent wasteful calculations done in the full matrix method ? Because we just only need the diagonal of the resulting matrix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T09:47:45.153",
"Id": "436492",
"Score": "1",
"body": "try this `np.einsum('ij,jk,ik->i',states, J, states)`. It is giving me more speedup as the value of n is increases. Ref: https://stackoverflow.com/questions/57216521/matrix-multiplication-but-only-between-specific-rows-and-columns/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T17:46:17.763",
"Id": "436565",
"Score": "0",
"body": "@papabiceps: Maybe you should write up a self answer to show your final code."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T22:05:07.260",
"Id": "224765",
"ParentId": "224671",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224765",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T13:18:12.393",
"Id": "224671",
"Score": "4",
"Tags": [
"python",
"performance",
"numpy",
"statistics",
"bitset"
],
"Title": "Evaluate joint probability density function of a Markov random field"
}
|
224671
|
<p>I have been implementing a library of PLC logic blocks (i.e. AND gates, OR gates,
RS flip-flops and TON, TOF and TP timers) in C++. I have decided to model all of
these logic blocks with C++ classes which implement common interface</p>
<pre><code>namespace LogicBlocks
{
class LogicBlk {
public:
enum LogicType_e{
POS, // positive logic
NEG // negative logic
};
virtual void Update(void) = 0;
private:
};
}
</code></pre>
<p>I have already implemented the <a href="https://codereview.stackexchange.com/questions/223309/implementing-plc-timer-pulse-function-block-in-c">timers</a> and RS flip-flop logic blocks. What I would
like to do now is to implement the AND and OR gates. My idea is to use AND gates
and OR gates with 1 input up to 8 inputs. I have implemented this in following
manner. I have special class for each type of gate. For example:</p>
<p><strong>OR gate with two inputs</strong></p>
<p>Interface:</p>
<pre><code>namespace LogicBlocks
{
// OR logic gate with two inputs
class Or_02 : public LogicBlk{
public:
Or_02(uint32_t *bitsArray,
uint32_t input_01, LogicType_e inputType_01,
uint32_t input_02, LogicType_e inputType_02,
uint32_t output);
virtual ~Or_02();
void Update(void);
private:
uint32_t m_In01;
LogicType_e m_In01Type;
uint32_t m_In02;
LogicType_e m_In02Type;
uint32_t m_Out;
uint32_t *m_BitsArray;
};
}
</code></pre>
<p>Implementation:</p>
<pre><code>LogicBlocks::Or_02::Or_02(uint32_t *bitsArray,
uint32_t input_01, LogicType_e inputType_01,
uint32_t input_02, LogicType_e inputType_02,
uint32_t output):
m_BitsArray{bitsArray},
m_In01{input_01}, m_In01Type{inputType_01},
m_In02{input_02}, m_In02Type{inputType_02},
m_Out{output}{
}
LogicBlocks::Or_02::~Or_02() {
}
void LogicBlocks::Or_02::Update(void){
if(((Utils::TestBitSet(m_BitsArray, m_In01) && m_In01Type == POS) || (Utils::TestBitClr(m_BitsArray, m_In01) && m_In01Type == NEG)) ||
((Utils::TestBitSet(m_BitsArray, m_In02) && m_In02Type == POS) || (Utils::TestBitClr(m_BitsArray, m_In02) && m_In02Type == NEG))){
Utils::SetBit(m_BitsArray, m_Out);
}else{
Utils::ClrBit(m_BitsArray, m_Out);
}
}
</code></pre>
<p><strong>OR gate with three inputs</strong></p>
<p>Interface:</p>
<pre><code>namespace LogicBlocks
{
// OR logic gate with three inputs
class Or_03 : public LogicBlk{
public:
Or_03(uint32_t* const bitsArray,
const uint32_t input_01, const LogicType_e inputType_01,
const uint32_t input_02, const LogicType_e inputType_02,
const uint32_t input_03, const LogicType_e inputType_03,
const uint32_t output);
virtual ~Or_03();
void Update(void);
private:
uint32_t m_In01;
LogicType_e m_In01Type;
uint32_t m_In02;
LogicType_e m_In02Type;
uint32_t m_In03;
LogicType_e m_In03Type;
uint32_t m_Out;
uint32_t *m_BitsArray;
};
}
</code></pre>
<p>Implementation:</p>
<pre><code>LogicBlocks::Or_03::Or_03(uint32_t* const bitsArray,
const uint32_t input_01, const LogicType_e inputType_01,
const uint32_t input_02, const LogicType_e inputType_02,
const uint32_t input_03, const LogicType_e inputType_03,
const uint32_t out):
m_BitsArray{bitsArray},
m_In01{input_01}, m_In01Type{inputType_01},
m_In02{input_02}, m_In02Type{inputType_02},
m_In03{input_03}, m_In03Type{inputType_03},
m_Out{output}{
}
LogicBlocks::Or_03::~Or_03() {
}
void LogicBlocks::Or_03::Update(void){
if(((Utils::TestBitSet(m_BitsArray, m_In01) && m_In01Type == POS) || (Utils::TestBitClr(m_BitsArray, m_In01) && m_In01Type == NEG)) ||
((Utils::TestBitSet(m_BitsArray, m_In02) && m_In02Type == POS) || (Utils::TestBitClr(m_BitsArray, m_In02) && m_In02Type == NEG)) ||
((Utils::TestBitSet(m_BitsArray, m_In03) && m_In03Type == POS) || (Utils::TestBitClr(m_BitsArray, m_In03) && m_In03Type == NEG))){
Utils::SetBit(m_BitsArray, m_Out);
}else{
Utils::ClrBit(m_BitsArray, m_Out);
}
}
</code></pre>
<p>Here is the usage. Lets say I have an object called Logic:</p>
<p>Interface:</p>
<pre><code>#include <stdint.h>
#include "LogicBlk.h"
namespace Logic
{
class Logic{
public:
Logic();
virtual ~Logic();
// method shall be called from a task
void Loop(void);
private:
uint32_t m_BitsArray[1] = {0};
static const uint8_t NO_LOGIC_BLKS = 2;
LogicBlocks::LogicBlk* m_LogicBlks[NO_LOGIC_BLKS];
};
}
</code></pre>
<p>Implementation:</p>
<pre><code>#include "Logic.h"
#include "Bits.h"
#include "Or_02.h"
#include "And_02.h"
#define LW_01 (0)
// Byte 01
#define LSig01 (LW_01*32 + 0x00)
#define LSig02 (LW_01*32 + 0x01)
#define LSig03 (LW_01*32 + 0x02)
//efine L (LW_01*32 + 0x03)
//efine L (LW_01*32 + 0x04)
//efine L (LW_01*32 + 0x05)
//efine L (LW_01*32 + 0x06)
//efine L (LW_01*32 + 0x07)
// Byte 02
#define LAx01 (LW_01*32 + 0x08)
#define LAx02 (LW_01*32 + 0x09)
//efine L (LW_01*32 + 0x0A)
//efine L (LW_01*32 + 0x0B)
//efine L (LW_01*32 + 0x0C)
//efine L (LW_01*32 + 0x0D)
//efine L (LW_01*32 + 0x0E)
//efine L (LW_01*32 + 0x0F)
// Byte 03
//efine L (LW_01*32 + 0x10)
//efine L (LW_01*32 + 0x11)
//efine L (LW_01*32 + 0x12)
//efine L (LW_01*32 + 0x13)
//efine L (LW_01*32 + 0x14)
//efine L (LW_01*32 + 0x15)
//efine L (LW_01*32 + 0x16)
//efine L (LW_01*32 + 0x17)
// Byte 04
//efine L (LW_01*32 + 0x18)
//efine L (LW_01*32 + 0x19)
//efine L (LW_01*32 + 0x1A)
//efine L (LW_01*32 + 0x1B)
//efine L (LW_01*32 + 0x1C)
//efine L (LW_01*32 + 0x1D)
//efine L (LW_01*32 + 0x1E)
//efine L (LW_01*32 + 0x1F)
Logic::Logic::Logic(){
m_LogicBlks[0] = new LogicBlocks::Or_02(m_BitsArray,
LSig01, LogicBlocks::LogicBlk::POS,
LSig02, LogicBlocks::LogicBlk::POS,
LAx01);
m_LogicBlks[1] = new LogicBlocks::And_02(m_BitsArray,
LAx01, LogicBlocks::LogicBlk::POS,
LSig03, LogicBlocks::LogicBlk::NEG,
LAx02);
}
Logic::Logic::~Logic(){
}
void Logic::Logic::Loop(void){
for(uint8_t curBlk = 0; curBlk < NO_LOGIC_BLKS; curBlk++){
m_LogicBlks[curBlk]->Update();
}
}
</code></pre>
<p>For completeness the utility functions for work with individual bits</p>
<pre><code>bool Utils::TestBitSet(uint32_t *bitsArray, uint32_t bit){
uint32_t wordValue = *(bitsArray + (bit >> 5));
uint32_t bitPosInWord = (bit - ((bit >> 5) << 5));
return ((wordValue & ((uint32_t)1 << bitPosInWord)) >> bitPosInWord) ? true : false;
}
bool Utils::TestBitClr(uint32_t *bitsArray, uint32_t bit){
uint32_t wordValue = *(bitsArray + (bit >> 5));
uint32_t bitPosInWord = (bit - ((bit >> 5) << 5));
return ((wordValue & ((uint32_t)1 << bitPosInWord)) >> bitPosInWord) ? false : true;
}
void Utils::SetBit(uint32_t *bitsArray, uint32_t bit){
uint32_t word = (bit >> 5);
uint32_t bitPosInWord = (bit - ((bit >> 5) << 5));
*(bitsArray + word) |= ((uint32_t)1 << bitPosInWord);
}
void Utils::ClrBit(uint32_t *bitsArray, uint32_t bit){
uint32_t word = (bit >> 5);
uint32_t bitPosInWord = (bit - ((bit >> 5) << 5));
*(bitsArray + word) &= ~((uint32_t)1 << bitPosInWord);
}
void Utils::NegBit(uint32_t *bitsArray, uint32_t bit){
if(TestBitSet(bitsArray, bit)){
ClrBit(bitsArray, bit);
}else{
SetBit(bitsArray, bit);
}
}
</code></pre>
<p>Now I have been thinking about weaknesses of this implementation. First of all I
thing that implementation of OR gate with three inputs is sort of code repetition
of OR gate with two inputs. Exactly the same is true for OR gates with more inputs. The second problem which I have is the way how the gates "communicate" and form the whole logic. Here I have been using bits array. I have also took into account a possibility that each logic block would receive pointers to cooperating logic blocks. The reason why I didn't use this approach was that in my opinion this implementation would lead to tree data structure and in case evaluation of the whole logic the stack can grow rapidly especially in complex logic structures. </p>
<p>Does anybody have any idea how to resolve my issues i.e. code repetition and
communication between logic blocks? Thank you for any suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T05:39:09.497",
"Id": "435926",
"Score": "0",
"body": "What family of PLC do you intend to run this on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T06:13:33.673",
"Id": "435932",
"Score": "0",
"body": "My intention is to use this library for programming a control board based on ARM MCU."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:45:12.440",
"Id": "435948",
"Score": "0",
"body": "So, boards like [this](http://www.ti.com/lit/ug/tidu191/tidu191.pdf)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:26:11.930",
"Id": "435951",
"Score": "1",
"body": "Did you test (either on board or in simulation) whether it indeed does what you think it does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T10:17:37.390",
"Id": "435957",
"Score": "1",
"body": "@Mast As far as the board. Yes, it is basically similar. As far as testing. I have already tested this library and it works. My problem is that I have doubts regarding to my implementation. As I have already mentioned namely code repetition and interconnection of individual logic blocks."
}
] |
[
{
"body": "<pre><code>LogicBlocks::Or_02::Or_02(uint32_t *bitsArray, \n uint32_t input_01, LogicType_e inputType_01,\n uint32_t input_02, LogicType_e inputType_02, \n uint32_t output):\n m_BitsArray{bitsArray}, \n m_In01{input_01}, m_In01Type{inputType_01}, \n m_In02{input_02}, m_In02Type{inputType_02}, \n m_Out{output}{\n}\n</code></pre>\n\n<p>Member variables are initialized in the order specified in the class, not the order in the initializer list (so <code>m_BitsArray</code> will be initialized last). While nothing will break here, it's best to always use the correct order in the initializer list.</p>\n\n<hr>\n\n<pre><code>(Utils::TestBitSet(m_BitsArray, m_In01) && m_In01Type == POS)\n</code></pre>\n\n<p>There's a lot of code like this. Why not factor it into a function taking all three variables:</p>\n\n<pre><code>Utils::TestBitSet(m_BitsArray, m_In01, m_In01Type);\n</code></pre>\n\n<hr>\n\n<p>[Opinion] I'm not too fond of the separate <code>TestBitSet()</code> and <code>TestBitClr()</code>. It's neater to just have one <code>IsBitSet()</code> and use <code>!IsBitSet()</code> where appropriate.</p>\n\n<hr>\n\n<pre><code>new LogicBlocks::Or_02\n</code></pre>\n\n<p>Don't just leak memory. Use a <code>std::unique_ptr</code>, or delete it manually.</p>\n\n<hr>\n\n<p><code>LogicBlk</code> must have a virtual destructor (and then you also don't need to specify empty destructors in the derived classes).</p>\n\n<hr>\n\n<p><code>virtual Update(void);</code></p>\n\n<p>The <code>void</code> parameter isn't necessary in C++.</p>\n\n<hr>\n\n<pre><code>#define LSig01 (LW_01*32 + 0x00)\n...\n</code></pre>\n\n<p>Prefer constant static variables to <code>#defines</code>, because they have proper scoping.</p>\n\n<hr>\n\n<pre><code>Or_03(uint32_t* const bitsArray, \n const uint32_t input_01, const LogicType_e inputType_01, ...\n</code></pre>\n\n<p>Don't make function arguments that are passed by value <code>const</code>. These <code>const</code>s don't actually matter to the caller, and they hide the <code>const</code>s that do matter (e.g. <code>&</code> vs <code>const&</code> or <code>*</code> vs <code>const*</code>), which makes the declaration harder to read. C++ also allows the use of <code>const</code> in a declaration to be different from the use of <code>const</code> in the function definition, so it can even be misleading.</p>\n\n<hr>\n\n<p>We can use templates for the different numbers of inputs:</p>\n\n<pre><code>struct LogicInput {\n LogicType_e type;\n std::uint32_t value;\n};\n\ntemplate<std::size_t NumInputs>\nclass Or {\npublic:\n\n Or(uint32_t* bitsArray, std::array<LogicInput>, NumInputs> in, uint32_t out);\n\n ...\n\n std::array<LogicInput> m_In;\n std::uint32_t m_Out;\n uint32_t* m_BitsArray;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:57:05.267",
"Id": "224687",
"ParentId": "224676",
"Score": "3"
}
},
{
"body": "<h3>Parameterize Logic Type</h3>\n\n<p>I'd start by trying to consolidate the mapping from voltage level to logic level in one place. For example:</p>\n\n<pre><code>class positive_signal { \n unsigned value : 1;\npublic:\n bool isSet() const { return value == 1; }\n void set() { value = 1; }\n void clear() { value = 0; }\n};\n\nclass negative_signal {\n unsigned value : 1;\npublic:\n bool isSet() const { return value == 0; }\n void set() { value = 0; }\n void clear() { value = 1; }\n};\n</code></pre>\n\n<p>Note that I'm leaving out a lot of detail here, just giving a sketch of a general direction. Just for example, in practice there's a decent chance that you'd want the <code>set</code> and <code>clear</code> member functions to <code>return *this;</code> to support chaining.</p>\n\n<h3>Generalize Gates</h3>\n\n<p>I'd consider implementing each gate type to take an arbitrary number of inputs:</p>\n\n<pre><code>namespace logic {\n\n bool OR(std::vector<signal> const &inputs) { \n return std::any_of(inputs().begin(), inputs.end(),\n [](signal in) { return in.isSet; });\n }\n\n bool AND(std::vector<signal> const &inputs) { \n return std::all_of(inputs.begin(), inputs.end(), \n [](signal in) { return in.isSet; });\n }\n // and so on\n}\n</code></pre>\n\n<p>This avoids duplicating logic for gates with different numbers of inputs, because you use exactly the same code for both.</p>\n\n<h3>Integration</h3>\n\n<p>Putting those two together can be a little tricky though. As I've shown the code above, they don't really fit well. You can go a couple of different routes. One is to use inheritance, so you'd start with <code>signal</code> as an abstract base class, and then positive and negative signals derived from that. If you do that, you'd have to pass vectors of pointers to signals, rather than vectors of signals.</p>\n\n<p>Alternatively, you could pass the signal type as a template parameter to the gate, so the compiler would instantiate one <code>OR</code> for negative logic and a separate <code>OR</code> for positive logic (and so on).</p>\n\n<p>In this case, I think the latter is a better fit. Inheritance would make sense if you expected to create something like a 5-input OR gate, with 2 arbitrary inputs being negative logic, and the other three positive logic (or more generally, inputs could be any arbitrary combination of positive/negative logic). In reality, however, you typically define the logic type at the gate level, so a 5-input <code>OR</code> gate is going to take either all 5 inputs as positive logic, or else all 5 inputs as negative logic, but never some combination of the two.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T17:47:30.217",
"Id": "224692",
"ParentId": "224676",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T14:29:47.943",
"Id": "224676",
"Score": "0",
"Tags": [
"c++",
"embedded"
],
"Title": "PLC logic library"
}
|
224676
|
<p>I am trying to emulate a C++ enum class in C and the code works as I expect. I used this code as indicated on
<a href="https://stackoverflo_3.com/questions/2124339/c-preprocessor-va-args-number-of-arguments" rel="nofollow noreferrer">Stack Overflow</a>.</p>
<pre><code>// .................................................... JOIN
#define JOIN(id,_1) id ## _1
// .................................................... CONCAT
#define CONCAT(id,_1) JOIN(id,_1)
#ifdef _MSC_VER // Microsoft compilers
# define GET_ARG_COUNT(...) INTERNAL_EidPAND_ARGS_PRIVATE(INTERNAL_ARGS_AUGMENTER(__VA_ARGS__))
# define INTERNAL_ARGS_AUGMENTER(...) unused, __VA_ARGS__
# define INTERNAL_EidPAND(id) id
# define INTERNAL_EidPAND_ARGS_PRIVATE(...) INTERNAL_EidPAND(INTERNAL_GET_ARG_COUNT_PRIVATE(__VA_ARGS__, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
# define INTERNAL_GET_ARG_COUNT_PRIVATE(_1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, _33_, _34_, _35_, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count
#else // Non-Microsoft compilers
# define GET_ARG_COUNT(...) INTERNAL_GET_ARG_COUNT_PRIVATE(0, ## __VA_ARGS__, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
# define INTERNAL_GET_ARG_COUNT_PRIVATE(_0, _1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, _33_, _34_, _35_, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count
#endif
#define OVERLOAD CONCAT
#define ARG GET_ARG_COUNT
</code></pre>
<p>so I reproduced the sequence in this way:</p>
<pre><code>// EnumClass1 enum { }
// EnumClass2 enum id { } ;
#define EnumClass2(id,_1)\
enum id##_e { id##_##_1 }
#define EnumClass3(id,_1,_2)\
enum id##_e { id##_##_1 , id##_##_2 }
#define EnumClass4(id,_1,_2,_3)\
enum id##_e { id##_##_1 , id##_##_2 , id##_##_3 }
#define EnumClass5(id,_1,_2,_3,_4)\
enum id##_e { id##_##_1 , id##_##_2 , id##_##_3 , id##_##_4 }
#define EnumClass6(id,_1,_2,_3,_4,_5)\
enum id##_e { id##_##_1 , id##_##_2 , id##_##_3 , id##_##_4 , id##_##_5 }
#define EnumClass7(id,_1,_2,_3,_4,_5,_6)\
enum id##_e { id##_##_1 , id##_##_2 , id##_##_3 , id##_##_4 , id##_##_5 , id##_##_6 }
#define EnumClass8(id,_1,_2,_3,_4,_5,_6,_7)\
enum id##_e { id##_##_1 , id##_##_2 , id##_##_3 , id##_##_4 , id##_##_5 , id##_##_6 , id##_##_7 }
</code></pre>
<p>and so on, with significant enum the repetition of code becomes abnormal:</p>
<pre><code>#define EnumClass(...) OVERLOAD ( EnumClass , ARG(__VA_ARGS__) ) ( __VA_ARGS__ )
</code></pre>
<p>This is the last part of the code and works with Visual Studio and gcc:</p>
<pre><code>int main(void)
{
EnumClass(sender
,lexer=100
,parser
) a ;
a=sender_parser ;
printf ( "\n%d\n",a ) ;
return 0 ;
}
</code></pre>
<p>Is there a more elegant way to avoid continuous repetitions of macros?</p>
<p>Other related questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11903625/how-to-emulate-strongly-typed-enum-in-c">How to emulate strongly typed enum in C?
</a></li>
<li><a href="https://stackoverflow.com/questions/52657232/does-enum-class-exist-in-c">Does “enum class” exist in C?</a></li>
</ul>
<p>After many attempts I have found this solution:</p>
<pre><code>#define EnumClass1(ID,X1 ) ID##_##X1
#define EnumClass2(ID,X1,... ) ID##_##X1 , OVERLOAD ( EnumClass , ARG(__VA_ARGS__) ) ( ID,__VA_ARGS__ )
...
#define EnumClass64(ID,X1,... ) ID##_##X1 , OVERLOAD ( EnumClass , ARG(__VA_ARGS__) ) ( ID,__VA_ARGS__ )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T16:30:39.680",
"Id": "435857",
"Score": "0",
"body": "Where is EnumClass(sender, lexer, parser) declared or defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T17:00:01.753",
"Id": "435862",
"Score": "0",
"body": "first arg is ID, other is member of enum : enum Class sender { lexer,parser } ; in C++, here the main macro code #define EnumClass(...) , so i obtain sender_lexer and son on."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T15:23:26.130",
"Id": "224681",
"Score": "3",
"Tags": [
"c",
"enum"
],
"Title": "Emulating a C++ enum class C++ in C"
}
|
224681
|
<p>I've created a <code>Node</code> class which contains two important properties:<br></p>
<ul>
<li><code>public Node Parent { get; private set; }</code></li>
<li><code>private List<Node> Children { get; set;}</code></li>
</ul>
<p>As the name suggests, the <code>Parent</code> object holds information about the <strong>ancestor</strong> of a certain node, if the parent is the <strong>root</strong> of the tree, then the parent is set to <code>null</code>. And the <code>Children</code> collection stores all the <strong>descendant</strong> nodes.<br></p>
<p>The methods responsible for the searching are:</p>
<ul>
<li><code>GetChildren()</code></li>
<li><code>GetChildrenRecursive()</code></li>
</ul>
<p>All of them are described on the code documentation. <strong>But I am specially concerned about the performance and reliability of the searching algorithm and the overall implementation of the tree structure</strong>. I'd like to hear some opinions on how I could possibly improve the code quality or any reading material about searching algorithms on trees.<br></p>
<ul>
<li>Node.cs</li>
</ul>
<pre>/// <summary>
/// Represents a tree-like structure
/// </summary>
public class Node
{
/// <summary>
/// The ancestor (parent) of this node. Null if the current node is the root of the tree.
/// </summary>
public Node Parent { get; private set; }
/// <summary>
/// The descendats (children) of this node.
/// </summary>
private List<Node> Children { get; set; }
/// <summary>
/// Checks wheter the current node is the root of the tree.
/// </summary>
public bool IsRoot { get { return Parent != null; } }
/// <summary>
/// Checks wheter the current node has any children.
/// </summary>
public bool HasChildren { get { return Count > 0; } }
/// <summary>
/// The current node's children count.
/// </summary>
public int Count { get { return Children?.Count ?? 0; } }
/// <summary>
/// The object stored in the current node.
/// </summary>
public object Value { get; set; }
/// <summary>
/// Creates a new instance of the <see cref="Node"/> class with an empty object.
/// </summary>
/// <param name="value">The value that will be held by this node</param>
public Node()
{
Value = new object();
Children = new List<Node>();
}
/// <summary>
/// Creates a new instance of the <see cref="Node"/> class with a set value.
/// </summary>
/// <param name="value">The value that will be held by this node</param>
public Node(object value)
{
Value = value;
Children = new List<Node>();
}
/// <summary>
/// Returns a copy of all values contained in this <see cref="Node"/>.
/// <para>
/// Useful for avoiding interferences between instances of the <see cref="Node"/> class.
/// </para>
/// </summary>
/// <returns>A <see cref="Node"/> with the property values of this node</returns>
public Node DeepCopy()
{
var other = (Node)MemberwiseClone();
other.Children = new List<Node>(collection: Children);
other.Parent = Parent?.DeepCopy();
other.Value = new Node(value: Value);
return other;
}
/// <summary>
/// Adds a child to this <see cref="Node"/>.
/// </summary>
/// <param name="node">The node to be added</param>
public void AddChild(Node node)
{
if (node != this && node.Parent == null)
{
node.Parent = this;
Children.Add(node);
}
}
/// <summary>
/// Removes a child from this <see cref="Node"/>.
/// </summary>
/// <param name="node">The node to be removed</param>
public void RemoveChild(Node node)
{
if (node != this && Children.Contains(node))
{
Children.Remove(node);
}
}
/// <summary>
/// Performs a superficial search, returning the children on the first level.
/// </summary>
/// <returns>An <see cref="IEnumerable{Node}"/>containing the search result</returns>
public IEnumerable<Node> GetChildren()
{
return Children.AsEnumerable();
}
/// <summary>
/// Performs a recursive search, returning all the children on all levels
/// </summary>
/// <returns>An <see cref="IEnumerable{Node}"/>containing the search result</returns>
public IEnumerable<Node> GetChildrenRecursive()
{
var root = DeepCopy();
// No descendants have children. No recursion neeeded.
if (root.Children.All(x => x.Children.Count == 0))
{
return GetChildren();
}
// Some (or all) descendants have children. Use recursion
else
{
var allChildren = new List<Node>();
var searchQueue = new Queue<Node>();
// Adds the first generation of children into the queue
GetChildren().ToList()
.ForEach((x) => searchQueue.Enqueue(x));
// Loops until the queue is empty
while (searchQueue.Any())
{
// Adds the first children in the queue to the final collection
allChildren.Add(searchQueue.Peek());
// Checks if the first children in the queue has descendants
if (searchQueue.Peek().HasChildren)
{
// Adds the descendants of the children being searched on the queue
searchQueue.Peek().Children
.ForEach((x) => searchQueue.Enqueue(x));
}
// Removes the first node on the queue, since it has been searched already.
searchQueue.Dequeue();
}
return allChildren;
}
}
/// <summary>
/// Override for the <code><see cref="object"/>.ToString()</code> method
/// </summary>
/// <returns>The string representation of this node's value</returns>
public override string ToString()
{
return $"{Value?.ToString()}";
}
}
</pre>
<p>Also, I'm including some tests I've made, all of them are passing as of now.<br></p>
<ul>
<li>NodeTest.cs</li>
</ul>
<pre>[TestClass]
public class NodeTest
{
[TestMethod]
public void Node_DeepCopy_CopySuccessful()
{
// Arrange
var root = new Node(null);
var node1 = new Node(null);
var node2 = new Node(null);
var copyNode = new Node(null);
// Act
root.AddChild(node1);
root.AddChild(node2);
copyNode = root.DeepCopy();
var actual = copyNode.HasChildren;
// Assert
Assert.AreEqual(true, actual);
}
[TestMethod]
public void Node_DeepCopy_CopyIsIndependent()
{
// Arrange
var root = new Node(null);
var node1 = new Node(null);
var node2 = new Node(null);
var copyNode = new Node(null);
// Act
root.AddChild(node1);
root.AddChild(node2);
copyNode = root.DeepCopy();
root.AddChild(new Node(null));
var actual = root.Count != copyNode.Count;
// Assert
Assert.AreEqual(true, actual);
}
[TestMethod]
public void Node_Search_ReturnsAllElements()
{
// Arrange
const int EXPECTED_CHILDREN_COUNT = 3;
var root = new Node(null);
var root_child1 = new Node(null);
var root_child2 = new Node(null);
var root_child3 = new Node(null);
// Act
root.AddChild(root_child1);
root.AddChild(root_child2);
root.AddChild(root_child3);
int actual = root.Count;
// Assert
Assert.AreEqual(EXPECTED_CHILDREN_COUNT, actual);
}
[TestMethod]
public void Node_RecursiveSearch_ReturnsAllElements()
{
// Arrange
const int EXPECTED_CHILDREN_COUNT = 9;
var root = new Node("Root node");
var rc1 = new Node("[Gen 1] 1st child of: root");
var rc2 = new Node("[Gen 1] 2nd child of: root");
var rc3 = new Node("[Gen 1] 3rd child of: root");
var rc2_1 = new Node("[Gen 2] 1st child of: root's 2nd child");
var rc2_2 = new Node("[Gen 2] 2nd child of: root's 2nd child");
var rc3_1 = new Node("[Gen 2] 1st child of: root's 3rd child");
var rc2_1_1 = new Node("[Gen 3] 1st child of: root's 2nd child's 1st child");
var rc3_1_1 = new Node("[Gen 3] 1st child of: root's 3rd child's 1st child");
var rc3_1_1_1 = new Node("[Gen 4] 1st child of: root's 3rd child's 1st child's 1st child");
// Act
rc2_1.AddChild(rc2_1_1);
rc2.AddChild(rc2_1);
rc2.AddChild(rc2_2);
rc3_1_1.AddChild(rc3_1_1_1);
rc3_1.AddChild(rc3_1_1);
rc3.AddChild(rc3_1);
root.AddChild(rc1);
root.AddChild(rc2);
root.AddChild(rc3);
int actual = new List<Node>(root.GetChildrenRecursive()).Count;
// Assert
Assert.AreEqual(EXPECTED_CHILDREN_COUNT, actual);
}
}
</pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:38:54.187",
"Id": "435874",
"Score": "0",
"body": "@dfhwze I'm sure there is a better/faster alternative to my approach to this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:40:03.340",
"Id": "435875",
"Score": "0",
"body": "@dfhwze Thinking now, If I don't find anything related to it in the MS assemblies, I'll just remove the tag"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:43:34.730",
"Id": "435878",
"Score": "0",
"body": "@dfhwze removed it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:43:57.957",
"Id": "435879",
"Score": "0",
"body": "meanwhile, I answered your question :) Btw, good to see unit tests in a question."
}
] |
[
{
"body": "<h2>Reading Material</h2>\n\n<blockquote>\n <p><em>.. any reading material about searching algorithms on trees</em></p>\n</blockquote>\n\n<p>These are the most common tree walkers:</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Breadth-first_search\" rel=\"noreferrer\">Breadth-First Search</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Depth-first_search\" rel=\"noreferrer\">Depth-First Search</a></li>\n</ul>\n\n<hr>\n\n<h2>Review</h2>\n\n<p>There is a bug with IsRoot. Also, why not provide a property <code>Root { get; }</code>?</p>\n\n<blockquote>\n <p><em>if the parent is the root of the tree, then the parent is set to null</em></p>\n \n <p><code>public bool IsRoot { get { return Parent != null; } }</code></p>\n</blockquote>\n\n<p>You should also take advantage of the sweet syntactic sugar of the language (for all your properties):</p>\n\n<pre><code> public bool IsRoot => Parent == null;\n</code></pre>\n\n<hr>\n\n<p>Since <code>Children</code> is private and you always instantiate a list, there is no reason to use null-propagation here:</p>\n\n<blockquote>\n <p><code>public int Count { get { return Children?.Count ?? 0; } }</code></p>\n</blockquote>\n\n<pre><code>public int Count => Children.Count;\n</code></pre>\n\n<hr>\n\n<p><code>AddChild</code> should throw exceptions on invalid input. You don't check for an invalid tree, what if the <code>node</code> is a <em>grand-parent</em> of the the current instance? Perform similar checks for <code>RemoveChild</code>.</p>\n\n<pre><code>public void AddChild(Node node)\n{\n node = node ?? throw new ArgumentNullException(nameof(node));\n if (IsAncestorOrSelf(node)) // <- you should implement such method\n throw new ArgumentException(\"The node can not be an ancestor or self\");\n if (IsDescendant(node)) // <- you should implement such method\n throw new ArgumentException(\"The node can not be a descendant\");\n node.Parent = this;\n Children.Add(node);\n}\n</code></pre>\n\n<hr>\n\n<p><code>GetChildren</code> should return an immutable copy of the list containing the children.</p>\n\n<pre><code>public IEnumerable<Node> GetChildren()\n{\n return Children.ToArray();\n}\n</code></pre>\n\n<hr>\n\n<p>I don't know why you would need <code>DeepCopy</code> functionality.</p>\n\n<hr>\n\n<p><code>GetChildrenRecursive</code> should be called <code>GetDescendants</code>. I would implement it using recursion. This is implemented as depth-first (DFS).</p>\n\n<pre><code>public IEnumerable<Node> GetDescendants()\n{\n foreach (var child in Children)\n {\n yield return child;\n foreach (var descendant in child.GetDescendants())\n {\n yield return descendant;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:55:14.990",
"Id": "435881",
"Score": "1",
"body": "Thank you for taking your time and reviewing the code. Apparently I was paranoid that my first implementation of this method would mess up with the original object. I fixed the following: A) IsRoot code (now, if the parent is not set, then it's considered as the root `Parent == null`; B) Removed the null check on Children; C) Search method now returns immutable copies of the descendants"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:57:31.873",
"Id": "435882",
"Score": "1",
"body": "I used recursion in _GetDescendants_ because you have tagged your question as such. It is also possible without. I am sure someone will review that part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:59:27.423",
"Id": "435883",
"Score": "0",
"body": "Ok. About the addition of new children, I'm doing the following check: `return !node.Children.Contains(this) && node != this && !Children.Contains(node);`. If it's false, then ArgumentException is thrown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:01:15.523",
"Id": "435884",
"Score": "0",
"body": "Once this question has sufficient answers, you can always ask a follow-up question with the new code. I will be happy review that question as well. For now, I can say, this new check does not cover all edge cases :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:02:31.357",
"Id": "435885",
"Score": "1",
"body": "I was worried about changing the code (which isn't allowed here). As you said, once there are sufficient suggestions, I'll do a follow-up. And again, thanks for you time spent into this matter :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:42:28.627",
"Id": "224697",
"ParentId": "224691",
"Score": "10"
}
},
{
"body": "<blockquote>\n<pre><code>public Node DeepCopy()\n{\n var other = (Node)MemberwiseClone();\n\n other.Children = new List<Node>(collection: Children);\n other.Parent = Parent?.DeepCopy();\n other.Value = new Node(value: Value);\n\n return other;\n}\n</code></pre>\n</blockquote>\n\n<p>You should be careful when using this, because it actually clones the entire tree (via <code>Parent</code> and <code>Children</code>). Besides that, I think <code>MemberwiseClone</code> copies the <code>Children</code> and <code>Parent</code> recursively. So by creating a new list for the <code>Children</code> and calling <code>DeepCopy()</code> on the <code>Parent</code> you actually get a mix of copies and existing <code>Node</code> objects, that can lead to unexpected behavior if you change either the copy or the original later on. And the child instances (<code>other</code>) will not be part of the parents <code>Children</code> list in the copy.</p>\n\n<p>Why does <code>other.Value</code> become a <code>Node(Value)</code>? - <code>Value</code> is by the way also covered by <code>MemberwiseClone</code>.</p>\n\n<p>Consider if it is of any use and possibly skip it. I can't see any use of it?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void RemoveChild(Node node)\n{\n if (node != this && Children.Contains(node))\n {\n Children.Remove(node);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>It is safe to call <code>Children.Remove(node)</code> even if <code>node</code> is not in the list or is <code>null</code>, so you can omit the <code>Contains()</code> check. <code>node != this</code> - I suppose this should be avoided in the <code>Add</code> method - but why can't <code>this</code> be removed if provided as <code>node</code>? You could consider to return the <code>bool</code> values returned from <code>Children.Remove(node)</code>, to let the client known if the operation was succesful or not.</p>\n\n<hr>\n\n<p>You could consider to make the <code>Node</code> class generic:</p>\n\n<pre><code>public class Node<T>\n{\n public T Value { get; }\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>As of <code>GetChildrenRecursive()</code> it seems to work, but looks rather complicated as a BFS algorithm. Remember that you have private access to the properties and fields of <code>Node</code> instances, so you can for instance call <code>Children</code> on any <code>Node</code> not just <code>this</code>. Below is a revised version, that is a little easier to follow:</p>\n\n<pre><code> public IEnumerable<Node> GetChildrenRecursive()\n {\n if (!HasChildren) yield break;\n\n Queue<Node> queue = new Queue<Node>(this.Children);\n\n while (queue.Count > 0)\n {\n var node = queue.Dequeue();\n yield return node;\n\n if (node.HasChildren)\n {\n foreach (Node child in node.Children)\n {\n queue.Enqueue(child);\n }\n }\n }\n }\n</code></pre>\n\n<p>It uses <code>yield return</code> instead of creating a concrete <code>List<Node></code> object which is more in line with the return value <code>IEnumerable<Node></code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T20:06:32.877",
"Id": "435895",
"Score": "2",
"body": "I think he meant _GetChildrenRecursive_ as search function :) btw I reached my vote limit of today :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T20:30:56.893",
"Id": "435898",
"Score": "1",
"body": "@Henrik Hansen *GetChildrenRecursive()* is the method I'm talking about, if you are doing this because I got something mixed up (**I can't blame you**), then that went completely over my head. As of the *DeepCopy(Node)*, I removed it, there was no use to it. And I'm planning to make this a generic type, I used the `object` type because gave more freedom over what can be inserted in the tree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T20:32:38.607",
"Id": "435899",
"Score": "0",
"body": "And I will remove the null check when removing nodes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T20:35:56.193",
"Id": "435900",
"Score": "3",
"body": "Node<T> can always be used as Node<object> if you need to. So making it generic can't hurt your design."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:48:49.447",
"Id": "224700",
"ParentId": "224691",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "224697",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T17:44:28.623",
"Id": "224691",
"Score": "10",
"Tags": [
"c#",
"recursion",
"unit-testing",
"tree"
],
"Title": "Recursive search on Node Tree with Linq and Queue"
}
|
224691
|
<p>I've made the following to draw a series of zooming in images of a fractal.</p>
<pre><code>using Distributed, FileIO, ImageCore, Images, ImageView
@everywhere function mandel_pow(z::Complex, p::Number)
c = z
maxiter::UInt8 = 255
for n = 1:maxiter
if abs2(z) > 4
return n-1
end
z = z^p + c
end
return maxiter
end
@everywhere function mandel(z)
mandel_pow(z, 2)
end
@everywhere function julia_pow(z::Complex, c::Complex, p::Number)
maxiter::UInt8 = 255
for n = 1:maxiter
if abs2(z) > 4
return n-1
end
z = z^p + c
end
return maxiter
end
@everywhere function julia(z)
julia(z, 2)
end
function gen_frame(min_coord::Complex,
max_coord::Complex, res, fn)
x_res, y_res = res
arr = @distributed hcat for i in range(real(min_coord), real(max_coord), length=x_res)
col = Vector{UInt8}(undef, y_res)
for j in enumerate(range(imag(max_coord), imag(min_coord), length=y_res))
col[j[1]] = fn(i+j[2]*im)
end
col
end
fetch(arr)
end
function zoom_in(image, zoom, scale)
y_res, x_res = size(image)
zoom = zoom/2
xmin = 1+round(Int, x_res*(.5-zoom))
xmax = round(Int, x_res*(.5+zoom))
ymin = 1+round(Int, y_res*(.5-zoom))
ymax = round(Int, y_res*(.5+zoom))
v = @view image[ymin:ymax, xmin:xmax]
imresize(v, div.(size(image), scale))
end
function draw_zoom(center, half_size, fps, seconds, fn)
res = (1920,1080)
scale = 2
for t in 0:seconds
print(t)
zoom = scale^convert(Float64, -t)
base = normedview(gen_frame(center - half_size*zoom,
center + half_size*zoom,
res.*scale, fn));
println(size(base))
for i in 0:fps
zoom = scale^(-i/fps)
save("mandel" * lpad(string(i+fps*t),4,'0') * ".jpg", zoom_in(base, zoom, scale))
end
println(" done.")
end
end
c = -0.5-0im
half_size = 1.5+1im
draw_zoom(c, half_size, 1, 1, mandel)
</code></pre>
<p>It can draw 10 seconds of frames at 30fps in about a minute using all cores of my computer.
I'm specifically looking for ways to improve the way <code>gen_frame</code> is parallelized, and ideally make the saving zoomed in strings happen while the next computation is being done. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T12:33:03.727",
"Id": "496565",
"Score": "1",
"body": "Quick comment, asserting `maxiter::UInt8 = 255` has no effect, since `1:maxiter` will make a `UnitRange{Int}` anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:17:53.393",
"Id": "496593",
"Score": "0",
"body": "Wow. This is a blast from the past. I think this was the first real program I wrote in Julia. The pre 1.3 is really showing (as is me not knowing what I'm doing)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T18:10:16.020",
"Id": "224693",
"Score": "6",
"Tags": [
"performance",
"graphics",
"fractals",
"julia"
],
"Title": "Julia set in Julia (and other fractals)"
}
|
224693
|
<p><strong>update1</strong>: </p>
<p><em>- I need to make two different api calls.
- from the result of first api call I am getting id in the variable firstAPIid,
<a href="https://reqres.in/api/users?page=2" rel="nofollow noreferrer">https://reqres.in/api/users?page=2</a>
- I need to pass this id firstAPIid to the second api call.</em></p>
<ul>
<li>can you review my code.</li>
<li>I did multiple api calls through promise.</li>
<li>right way is through promise or async or call back.</li>
<li>providing my code snippet and sandbox below.</li>
</ul>
<p><a href="https://codesandbox.io/s/redux-async-actions-xjdo7" rel="nofollow noreferrer">https://codesandbox.io/s/redux-async-actions-xjdo7</a></p>
<pre class="lang-or-tag-here prettyprint-override"><code><FetchButton
onFetchClick={() => {
store.dispatch(dispatchFunc => {
dispatchFunc({ type: "FETCH_DATA_START" });
axios
.get("https://reqres.in/api/users?page=2")
// axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log("response.data.data---->", response.data.data);
console.log(
"response.data.data[0].id---->",
response.data.data[0].id
);
//First of all we'll create the number of requestes base on the previous Response
const promises = response.data.data.reduce(
(previousValue, { id }) => {
previousValue.push(
axios.get(
`https://jsonplaceholder.typicode.com/comments?postId=${id}`
)
);
console.log(
" promises previousValue---->",
previousValue
);
return previousValue;
},
[]
);
console.log("promises---->", promises);
//We use the built in function to fetch the data
axios.all(promises).then(responses => {
//Here you have all responses processed
const emailsMapped = responses.reduce(
(previousValue, { data }) => {
const emails = data.map(({ email }) => email);
previousValue.push(...emails);
return previousValue;
},
[]
);
//You send the emails you want
dispatchFunc({
type: "RECEIVED_DATA",
payload: emailsMapped
});
console.log(emailsMapped);
});
})
.catch(err => {
dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
});
});
}}
/>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:38:21.940",
"Id": "435889",
"Score": "0",
"body": "Could you tell us what your code is about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:42:01.630",
"Id": "435890",
"Score": "0",
"body": "hey updated the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T20:46:46.480",
"Id": "435902",
"Score": "0",
"body": "This code look like the code from https://medium.com/@rk./mutliple-api-calls-with-promise-by-using-map-and-reduce-fa223058ed4e Are you the author of the code in the your question?"
}
] |
[
{
"body": "<p>First of all, putting all your code in the props of your JSX is making it unreadable. Extract this into a function, and have your JSX reference that instead.</p>\n\n<p>Next, for debugging, I would recommend using breakpoints to debug code. <code>console.log()</code> is fine for a quick peek, but it introduces a lot of noise in the code.</p>\n\n<p>Also, when you expand a logged object in the console, you see the object's structure at the time of expanding, not at the time of logging. The object's contents may have already changed between the time it was logged and when you expanded it. If you're not aware of this quirk, you'll easily think your code is broken.</p>\n\n<p>For <code>promises</code>, you're really just mapping. Use <code>array.map()</code> instead of <code>array.reduce()</code>. For <code>emailsMapped</code>, which is also just a mapping operation, since you're adding multiple items, use <code>array.flatMap()</code> for that.</p>\n\n<p>Lastly, you can modify your code so that you can chain the promises instead of nesting them. You can return the promise of <code>axios.all()</code> to chain it to your <code>axios.get()</code>.</p>\n\n<pre><code>store.dispatch(dispatchFunc => {\n dispatchFunc({ type: \"FETCH_DATA_START\" });\n axios\n .get(\"https://reqres.in/api/users?page=2\")\n .then(response => {\n const promises = response.data.data.map(({ id }) => {\n return axios.get(`https://.../comments?postId=${id}`)\n })\n\n return axios.all(promises)\n })\n .then(responses => {\n const emailsMapped = responses.flatMap(({ data }) => {\n return data.map(({ email }) => email)\n })\n\n dispatchFunc({\n type: \"RECEIVED_DATA\",\n payload: emailsMapped\n })\n })\n .catch(err => {\n dispatchFunc({\n type: \"FETCH_DATA_ERROR\",\n payload: err\n })\n })\n})\n</code></pre>\n\n<p>Now that we've established a more linear flow via chaining, we can take this a bit further and convert it to an <code>async</code> function so that we can use <code>await</code>:</p>\n\n<pre><code>// Note the async here\nstore.dispatch(async dispatchFunc => {\n dispatchFunc({ type: \"FETCH_DATA_START\" });\n\n try {\n // Note the various await before each asynchronous function call\n\n const response = await axios.get(\"https://reqres.in/api/users?page=2\")\n\n const promises = response.data.data.map(({ id }) => {\n return axios.get(`https://.../comments?postId=${id}`)\n })\n\n const responses = await axios.all(promises)\n\n const emailsMapped = responses.flatMap(({ data }) => {\n return data.map(({ email }) => email)\n })\n\n dispatchFunc({\n type: \"RECEIVED_DATA\",\n payload: emailsMapped\n })\n } catch (err) {\n dispatchFunc({\n type: \"FETCH_DATA_ERROR\",\n payload: err\n })\n }\n})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T17:22:20.083",
"Id": "436194",
"Score": "0",
"body": "hey for performance promise or async is good...can you let me know why you used flat map"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T18:09:47.130",
"Id": "224748",
"ParentId": "224698",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:37:17.340",
"Id": "224698",
"Score": "3",
"Tags": [
"javascript",
"html",
"react.js",
"redux",
"axios"
],
"Title": "multiple api calls through promise"
}
|
224698
|
<p>I created an algotrithm that groups a <em>sorted</em> <code>list</code> of coordinates into buckets based on their proximity (30) to one another. </p>
<p>Steps:</p>
<ol>
<li>Create a new key with a list value and pop the first point in the list into it</li>
<li>Scan the list of points for points that are close to it. Push matches to the new list and replace values with <code>None</code></li>
<li>After scan, filter the list, removing <code>None</code> values</li>
<li>Back to one, until <code>points</code> is empty.</li>
</ol>
<p>I can't modify the list by deleting elements because I use indexes.</p>
<p>After I'm done grouping, I take the average of each group of points. </p>
<pre class="lang-py prettyprint-override"><code>def group_points(points):
groups = {}
groupnum = 0
while len(points) > 1:
groupnum += 1
key = str(groupnum)
groups[key] = []
ref = points.pop(0)
for i, point in enumerate(points):
d = get_distance(ref, point)
if d < 30:
groups[key].append(points[i])
points[i] = None
points = list(filter(lambda x: x is not None, points))
# perform average operation on each group
return list([[int(np.mean(list([x[0] for x in groups[arr]]))), int(np.mean(list([x[1] for x in groups[arr]])))] for arr in groups])
def get_distance(ref, point):
# print('ref: {} , point: {}'.format(ref, point))
x1, y1 = ref[0], ref[1]
x2, y2 = point[0], point[1]
return math.hypot(x2 - x1, y2 - y1)
</code></pre>
<p>If possible, I would like to reduce the amount of variables and total loops over the points array. Do I need to use indexes? Is it possible to achieve this in one pass over <code>points</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T23:45:31.997",
"Id": "435916",
"Score": "0",
"body": "How many points do you expect to process? Do the points have any special properties or distribution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T02:06:34.980",
"Id": "435922",
"Score": "0",
"body": "\"a sorted `list`\" - sorted according to what criterium?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T13:18:26.830",
"Id": "435963",
"Score": "0",
"body": "They are sorted by the x value then the y value. The number of points varies, but its almost guaranteed they will all fit in some sort of group with at least one other point."
}
] |
[
{
"body": "<h3>General comments:</h3>\n\n<p>You are basically using the <code>groups</code> dict like a list. Might as well just use a list.</p>\n\n<p>An empty data structure (list, dict, set, tuple) is False in a boolean context, so <code>while len(points) > 1:</code> can be simplified to <code>while points:</code></p>\n\n<p>It is generally slower to pop from the front of a list than the back of a list, because after removing the first item all the rest of the items get moved up one spot.</p>\n\n<p><code>points.pop()</code> actually changes the list passed in. Make sure that's what you want.</p>\n\n<p><code>filter(None, points)</code> filters out all \"False\" items.</p>\n\n<p><code>[ ... ]</code> creates a list. So, <code>list( [ ... ] )</code> is redundant.</p>\n\n<p>You can just use <code>x1, y1 = ref</code>.</p>\n\n<p>Put that all together and you get something like:</p>\n\n<pre><code>def group_points(points):\n groups = []\n while points:\n far_points = []\n ref = points.pop()\n groups.append([ref])\n for point in points:\n d = get_distance(ref, point)\n if d < 30:\n groups[-1].append(point)\n else:\n far_points.append(point)\n\n points = far_points\n\n # perform average operation on each group\n return [list(np.mean(x, axis=1).astype(int)) for x in groups]\n\ndef get_distance(ref, point):\n # print('ref: {} , point: {}'.format(ref, point))\n x1, y1 = ref\n x2, y2 = point\n return math.hypot(x2 - x1, y2 - y1)\n</code></pre>\n\n<p>You also might want to look at functions in <code>scipy.cluster</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:47:38.643",
"Id": "436155",
"Score": "0",
"body": "`return [list(np.mean(x, axis=1).astype(int)) for x in groups]` \n\nWill this work if each element is an array? `[x,y]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:55:55.310",
"Id": "436156",
"Score": "0",
"body": "Also, are lists faster than dicts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T17:40:13.983",
"Id": "436199",
"Score": "1",
"body": "@Josh Sharkey, yes `np.mean()` works on arrays. The axis parameter tells it how to do the calculation. Without `axis` is takes the mean of the whole array. And yes, lists can be faster than dicts and likely use less memory. Like many things in programming there is a tradeoff. In most cases code that is easier to understand is worth the slight performance tradeoff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T19:45:54.430",
"Id": "436231",
"Score": "0",
"body": "so `np.mean(axis=1)` will average the x values and the y values separately and return a single list `[x_avg, y_avg]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T22:02:22.010",
"Id": "436254",
"Score": "1",
"body": "@Josh yes. np.mean(array) returns the mean of the whole array. with axis=0 it returns the mean for each row. with axis=1 it returns the mean of each column."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T02:49:32.687",
"Id": "224711",
"ParentId": "224704",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>while len(points) > 1:\n</code></pre>\n</blockquote>\n\n<p>Shouldn't it be: </p>\n\n<pre><code>while len(points) > 0:\n</code></pre>\n\n<p>or else the last point \"hangs\" unhandled in the points list when finished.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> ...\n groups[key] = []\n ref = points.pop(0)\n ...\n</code></pre>\n</blockquote>\n\n<p>Don't you forget to insert the <code>ref</code> point itself into the new list?:</p>\n\n<pre><code> ...\n ref = points.pop(0)\n groups[key] = [ ref ] \n ...\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>if d < 30:</code></p>\n</blockquote>\n\n<p>I would have this distance (<code>30</code>) as a parameter of the function:</p>\n\n<pre><code>def group_points(points, distance):\n</code></pre>\n\n<p>in order to make it more useful.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>for i, point in enumerate(points):\n d = get_distance(ref, point)\n if d < distance:\n groups[key].append(points[i])\n points[i] = None\npoints = list(filter(lambda x: x is not None, points))\n</code></pre>\n</blockquote>\n\n<p>can be simplified to:</p>\n\n<pre><code>for point in points:\n if get_distance(ref, point) < distance:\n groups[key].append(point)\npoints = list(filter(lambda x: x not in groups[key], points))\n</code></pre>\n\n<p>But as eric.m notices in his comment, the original may be more efficient than my suggestion.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>return list([[int(np.mean(list([x[0] for x in groups[arr]]))), int(np.mean(list([x[1] for x in groups[arr]])))] for arr in groups])\n</code></pre>\n</blockquote>\n\n<p>A rather scary statement. Split it up in meaningful parts:</p>\n\n<pre><code>def points_mean(points):\n return list(np.mean(points, axis = 0).astype(int))\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>return map(points_mean, groups)\n</code></pre>\n\n<p>BtW: Why are you operating in integers and not in floating points?</p>\n\n<hr>\n\n<p>Your method changes the input data set (<code>points.pop()</code>), which you as a client normally don't expect. To avoid that, you can do something like:</p>\n\n<pre><code>def group_points(points, distance):\n if len(points) == 0 or distance < 0: return []\n groups = [[points[0]]]\n for point in points[1:]:\n handled = False\n for group in groups:\n if get_distance(group[0], point) < distance:\n group.append(point)\n handled = True\n break\n\n if not handled:\n groups.append([point])\n\n# perform average operation on each group\nreturn map(points_mean, groups)\n\ndef points_mean(points):\n return list(np.mean(points, axis = 0).astype(int))\n\ndef get_distance(ref, point):\n x1, y1 = ref\n x2, y2 = point\n return math.hypot(x2 - x1, y2 - y1)\n</code></pre>\n\n<hr>\n\n<p>Disclaimer: I'm not that familiar with Python, so something in the above can maybe be done simpler and more succinct, so regard it as an attempt to think along your lines of thoughts and not as a state of the art.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T10:01:32.493",
"Id": "435954",
"Score": "1",
"body": "Wasn't the `points[i] = None` more efficient? It's faster checking wheter `x is not None` than checking if x is inside a list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T10:21:38.407",
"Id": "435958",
"Score": "0",
"body": "@eric.m: you can have a point there. You could maybe use `points.remove(point)` instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T13:13:51.710",
"Id": "435962",
"Score": "0",
"body": "points.remove modifies the list in-place, making it shorter. That screws up the `i` indexing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:34:29.420",
"Id": "435977",
"Score": "0",
"body": "Hold on... where am I? ..this isn't C# :o:o ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:51:17.750",
"Id": "435982",
"Score": "1",
"body": "@dfhwze: needed a little change, and it seems that all C#'ers are on vacation :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:52:26.163",
"Id": "435983",
"Score": "1",
"body": "I get that, I recently started answering Ruby questions myself :s"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:17:44.367",
"Id": "224718",
"ParentId": "224704",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224711",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T21:50:32.070",
"Id": "224704",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"numpy",
"clustering"
],
"Title": "Grouping sorted coordinates based on proximity to each other"
}
|
224704
|
<p>I have two <code>dataframes</code> (<code>x</code> and <code>y</code>) that I need to join, conditional on the timestamp in <code>x</code> falling within the time interval of two columns in <code>y</code>. I've accomplished this using <code>data.table::foverlaps()</code> by adapting some of the code in <a href="https://stackoverflow.com/questions/53694729/r-merge-2-dataframes-with-timestamp-between">this stackexchange question</a>), but in order to get it to work on my data I had to set the <code>key</code> of <code>data.table</code> <code>x</code>, which according to the documentation of <code>foverlaps()</code>, isn't supposed to be necessary. </p>
<p>Am I using this <code>foverlaps()</code>incorrectly? If so, new ideas for how to accomplish this data merging task are welcome.</p>
<pre><code>library(data.table)
</code></pre>
<h2>Data snippets</h2>
<pre><code>x <- structure(list(TagID = c(20161L, 23055L, 45428L, 2627L), DateTimePST = structure(c(1415481096,
1380768444, 1474560076, 1511384035), class = c("POSIXct", "POSIXt"
), tzone = "Pacific/Pitcairn"), Receiver = c(102140L, 112568L,
112568L, 121907L)), class = "data.frame", row.names = c(NA, -4L
))
y <- structure(list(Station = c("YBAAG4", "YBAAG4", "YBCSSW", "YBCSSW",
"YBBCD", "YBAWW"), Receiver = c(102140L, 102140L, 112568L, 112568L,
121907L, 121907L), Start = structure(c(1464979020, 1409256300,
1369945920, 1470761034, 1505494980, 1409246700), class = c("POSIXct",
"POSIXt"), tzone = "Pacific/Pitcairn"), End = structure(c(1473357300,
1421878500, 1382638020, 1479838293, 1513282440, 1421871360), class = c("POSIXct",
"POSIXt"), tzone = "Pacific/Pitcairn")), class = "data.frame", row.names = c(NA,
-6L))
# preview data
> x
TagID DateTimePST Receiver
1 20161 2014-11-08 13:11:36 102140
2 23055 2013-10-02 18:47:24 112568
3 45428 2016-09-22 08:01:16 112568
4 2627 2017-11-22 12:53:55 121907
> y
Station Receiver Start End
1 YBAAG4 102140 2016-06-03 10:37:00 2016-09-08 09:55:00
2 YBAAG4 102140 2014-08-28 12:05:00 2015-01-21 14:15:00
3 YBCSSW 112568 2013-05-30 12:32:00 2013-10-24 10:07:00
4 YBCSSW 112568 2016-08-09 08:43:54 2016-11-22 10:11:33
5 YBBCD 121907 2017-09-15 09:03:00 2017-12-14 12:14:00
6 YBAWW 121907 2014-08-28 09:25:00 2015-01-21 12:16:00
</code></pre>
<p>Because some <code>Receiver</code> numbers are associated with more than one <code>Station</code>, it is important to merge these two datasets on the timestamp (<code>DateTimePST</code>), not on the receiver number.</p>
<h2>Prep data</h2>
<pre><code>x <- as.data.table(x); x$Start = x$DateTimePST; x$End = x$DateTimePST # needs these start and end columns, otherwise foverlaps throws an error
y <- as.data.table(y)
# set keys: if I omit setting the key on x, forverlap() throws an error
setkey(y, Start, End); setkey(x, Start, End)
</code></pre>
<h2><code>foverlaps()</code> join, then discard incorrect <code>Receiver</code> pairs</h2>
<pre><code>result <- data.frame(foverlaps(x, y, type = "within"))
result <- result[result$Receiver == result$i.Receiver, ] # this filters down to the correct receiver matches
</code></pre>
<h2>Clean up results</h2>
<pre><code>rm_col <- c("i.Receiver", "i.Start", "i.End")
result <- result[ , !(colnames(result) %in% rm_col)]
result
Station Receiver Start End TagID DateTimePST
1 YBCSSW 112568 2013-05-30 12:32:00 2013-10-24 10:07:00 23055 2013-10-02 18:47:24
3 YBAAG4 102140 2014-08-28 12:05:00 2015-01-21 14:15:00 20161 2014-11-08 13:11:36
4 YBCSSW 112568 2016-08-09 08:43:54 2016-11-22 10:11:33 45428 2016-09-22 08:01:16
5 YBBCD 121907 2017-09-15 09:03:00 2017-12-14 12:14:00 2627 2017-11-22 12:53:55
</code></pre>
<h2>Wrap in a function:</h2>
<pre><code>getStation <- function(x, y) {
x <- as.data.table(x); x$Start = x$DateTimePST; x$End = x$DateTimePST
y <- as.data.table(y)
setkey(y, Start, End); setkey(x, Start, End)
result <- data.frame(foverlaps(x, y, type = "within"))
result <- result[result$Receiver == result$i.Receiver, ]
result <- result[ , !(colnames(result) %in% c("i.Receiver", "i.Start", "i.End"))]
}
res <- getStation(x, y)
</code></pre>
|
[] |
[
{
"body": "<p>You'll need to use <code>by.x</code> to get around setting <code>x</code>'s key.</p>\n\n<p>Also, note that <code>foverlaps</code> can merge on any number of keys, and then do the overlaps <em>only on the final two</em>. What that means here is that you can do the <code>x.Receiver == i.Receiver</code> filter up-front, which also simplifies the clean-up step.</p>\n\n<pre><code>x = as.data.table(x)\nx[ , end := DateTimePST]\ny = as.data.table(y)\n\nsetkey(y, Receiver, Start, End)\n\nresult = foverlaps(x, y, by.x = c('Receiver', 'DateTimePST', 'end'), type = 'within')\nresult[ , end := NULL]\n\nsetDF(result)\n</code></pre>\n\n<p>I do find it a bit awkward/strange that you've got to define <code>end</code> when <code>by.x = c('Receiver', 'DateTimePST', 'DateTimePST')</code> would appear to be fine, and have filed <a href=\"https://github.com/Rdatatable/data.table/issues/3721\" rel=\"noreferrer\">a feature request</a>.</p>\n\n<p>If you don't need <code>DateTimePST</code> in your output, you might find the non-equi-join version more compact / easier to read:</p>\n\n<pre><code>y[x, on = .(Receiver == Receiver, Start < DateTimePST, End > DateTimePST)]\n# Station Receiver Start End\n# 1: YBAAG4 102140 2014-11-08 13:11:36 2014-11-08 13:11:36\n# 2: YBCSSW 112568 2013-10-02 18:47:24 2013-10-02 18:47:24\n# 3: YBCSSW 112568 2016-09-22 08:01:16 2016-09-22 08:01:16\n# 4: YBBCD 121907 2017-11-22 12:53:55 2017-11-22 12:53:55\n# TagID\n# 1: 20161\n# 2: 23055\n# 3: 45428\n# 4: 2627\n</code></pre>\n\n<p>Note the order <code>y[x</code> -- we're using <code>x</code> to \"look up\" rows of <code>y</code>.</p>\n\n<p>If you <em>do</em> need <code>DateTimePST</code>, it's just a bit of an ugly extension:</p>\n\n<pre><code>y[x, c(.SD, list(DateTimePST=DateTimePST)),\n on = .(Receiver == Receiver, Start < DateTimePST, End > DateTimePST)]\n</code></pre>\n\n<p>Finally, we can think of this as adding columns to <code>x</code> by a non-equi-join with <code>y</code> by reversing the order:</p>\n\n<pre><code>x[y, `:=`(Start = i.Start, End = i.End, Station = i.Station),\n on = .(Receiver == Receiver, DateTimePST > Start, DateTimePST < End)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T05:01:11.693",
"Id": "435924",
"Score": "0",
"body": "Super helpful options, thank you! I do need `DateTimePST`, so the last two methods were both good ones. One note on the \"ugly extension\" one, that only works for me when I set `x$Start = x$DateTimePST`, otherwise I get an error: \"`Error in `[.data.table`(y, x, c(.SD, list(DateTimePST = DateTimePST)), : \n column(s) not found: Start`\" . I'm still learning `data.table` though"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T00:21:37.077",
"Id": "224707",
"ParentId": "224705",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "224707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T22:13:23.220",
"Id": "224705",
"Score": "3",
"Tags": [
"datetime",
"r"
],
"Title": "Merge dataframes on timestamps and time intervals using data.table in R"
}
|
224705
|
<p>I have written a file compressor in python. The program generates a file filled with sequences of the same character with a random length, and compresses that file. I would like feedback on code readability, efficiency, and any other nitpicks that you find. Any and all feedback is considered and appreciated!</p>
<p><strong>compress.py</strong></p>
<pre><code>""" Import Statements """
import os
import random
import re
import string
UNCOMPRESSED_FILE = "code/python/compression/uncompressed.txt"
COMPRESSED_FILE = "code/python/compression/compressed.txt"
RE_UNCOMPRESSED_FILE = "code/python/compression/re_uncompressed.txt"
def get_random_letter(previous_letter):
""" Gets a letter that isn't the previous letter """
letter = random.choice(string.ascii_lowercase)
return letter if letter != previous_letter else get_random_letter(previous_letter)
def generate_file():
""" Generates file to be compressed """
previous_letter = "A"
with open(UNCOMPRESSED_FILE, "w") as file:
for _ in range(random.randint(10000, 100000)):
letter = get_random_letter(previous_letter)
for _ in range(random.randint(3, 9)):
file.write(letter)
previous_letter = letter
def compress_file(file_to_be_compressed):
""" Creates a new compressed file from the past file """
compressed_string = ""
characters = file_to_list(file_to_be_compressed)
count = 0
for i in range(len(characters)):
try:
if characters[i] == characters[i + 1]:
count += 1
else:
compressed_string += f"{characters[i]}{count + 1}"
count = 0
except IndexError:
if characters[len(characters) - 1] == characters[len(characters) - 2]:
count += 1
compressed_string += f"{characters[i]}{count}"
with open(COMPRESSED_FILE, "w") as compressed_file:
compressed_file.write(compressed_string)
def decompress_file(file_to_be_decompressed):
""" Decompresses passed file """
compressed_content = file_to_one_line(file_to_be_decompressed)
decompressed_content = re.findall("..", compressed_content)
#print(decompressed_content)
with open(RE_UNCOMPRESSED_FILE, "w") as re_uncompressed_file:
for pair in decompressed_content:
letter = pair[0]
num = int(pair[1])
re_uncompressed_file.write(letter * num)
def get_file_size(file):
""" Returns the file size, in bytes """
return os.path.getsize(file)
def file_to_one_line(file):
""" Concats all lines in file to one line """
with open(file, "r") as file_to_read:
lines = ""
for line in file_to_read:
lines += line
return line
def file_to_list(file):
""" Converts all the lines into an array of characters"""
with open(file, "r") as file_to_read:
lines = ""
for line in file_to_read:
lines += line
return list(map(str, lines))
if __name__ == '__main__':
generate_file()
print(f"File size before compression: {get_file_size(UNCOMPRESSED_FILE)}")
compress_file(UNCOMPRESSED_FILE)
print(f"File size after compression: {get_file_size(COMPRESSED_FILE)}")
decompress_file(COMPRESSED_FILE)
print(f"File size after decompression: {get_file_size(RE_UNCOMPRESSED_FILE)}")
</code></pre>
|
[] |
[
{
"body": "<h2>DocStrings</h2>\n\n<p><code>\"\"\"Docstrings\"\"\"</code> are not comments. They are extracted by the <code>help()</code> function to return documentation to the user on how to use the module. As written, if someone was to:</p>\n\n<pre><code>>>> import compress\n>>> help(compress)\n</code></pre>\n\n<p>They would be given the description of the module as:</p>\n\n<blockquote>\n <p>Import Statements </p>\n</blockquote>\n\n<p>Use comments lines <code># ...</code> for descriptions about the code, and <code>\"\"\"Doc-strings\"\"\"</code> for descriptions of how to use the module/functions.</p>\n\n<hr>\n\n<h2>Don't use Recursion for Simple Loops</h2>\n\n<pre><code>def get_random_letter(previous_letter):\n letter = random.choice(string.ascii_lowercase)\n return letter if letter != previous_letter else get_random_letter(previous_letter)\n</code></pre>\n\n<p>Here, you want to generate random lowercase letter which is different from the previous letter. If Python used <a href=\"https://stackoverflow.com/questions/310974/what-is-tail-call-optimization\">Tail Call Optimization</a>, this would be fine; the Python compiler would turn the recursive call into a jump statement to the top of the function. But it does (and can't, due to the dynamic interpretive nature). So each recursive call adds another stack-frame. With a 1-in-26 possibility of getting a duplicate letter, the expected stack-frame depth will never get very large, but it is still the wrong control structure. Just use a <code>while</code> loop.</p>\n\n<pre><code>def get_random_letter(previous_letter):\n letter = previous_letter # To ensure loop executes at least once\n while letter == previous_letter:\n letter = random.choice(string.ascii_lowercase)\n return letter\n</code></pre>\n\n<hr>\n\n<h2>O(1) memory</h2>\n\n<p>Compressing a 1,000,0000,000 character file will require over 32,000,000,000 bytes of memory, which seems a bit excessive.</p>\n\n<ul>\n<li>the file is read into memory as a long string</li>\n<li>the long string is split into a list of single character strings.</li>\n<li>each character is an object of at least 28 bytes</li>\n<li>each entry in the list is at 4 or 8 byte pointer to the corresponding object.</li>\n</ul>\n\n<p>Yeouch!</p>\n\n<p>Instead of reading the entire file into memory, and then splitting it, and then writing out the compressed information:</p>\n\n<ul>\n<li>open the input & output files simultaneously</li>\n<li>read in characters one at a time</li>\n<li>increment a count when the character is the same as the last</li>\n<li>write out the character and count when the next character is different.</li>\n</ul>\n\n<p>Active memory usage: 2 characters and 1 integer.</p>\n\n<hr>\n\n<h2>A string is a <code>list</code> of characters</h2>\n\n<p>Well, no, a string is a sequence of characters. But the upshot is the same. If you want to index a string character by character, just index the string. There is no need to turn it into a list:</p>\n\n<pre><code>s = \"HELLO\"\ns[4] == \"O\" # The easy way\n\nl = list(map(str, s)) # Or the hard, and\nl[4] == \"O\" # memory inefficient way\n</code></pre>\n\n<hr>\n\n<h2>Bug / deficiency</h2>\n\n<p>Your <code>generate_file()</code> method avoids generating a sequence of more than 9 entries of the same character, but a compression function should be able to handle that, if it happens.</p>\n\n<p>At present, if you compressed <code>AAAAAAAAAAAAAAABB</code>, it would compress to <code>A15B2</code>, which would be decompressed as <code>A1</code>, a single <code>A</code>, followed by <code>5B</code> which is B occurrences of the the letter <code>5</code> ... which will crash the decompression algorithm.</p>\n\n<p>When your compressing encounters the 9th <code>A</code>, it should emit <code>A9</code> and then reset the count to zero, so <code>AAAAAAAAAAAAAAABB</code> would compress at <code>A9A6B2</code>.</p>\n\n<p>Or your decompression algorithm should look for all of the digits after the letter, and interpret it as a multi digit number.</p>\n\n<hr>\n\n<h2>DRY: Don't Repeat Yourself</h2>\n\n<p><code>file_to_one_line</code> and <code>file_to_list</code> contain the same code. You could write one in terms of the other:</p>\n\n<pre><code>def file_to_list(file):\n return list(map(str, file_to_line(file)))\n</code></pre>\n\n<p>... not that I like this function.</p>\n\n<hr>\n\n<h2>Read the Python Docs</h2>\n\n<p>You are doing a lot of work to read the file line by line and accumulate the result as a string, when Python allows you to read in the entire file as a string:</p>\n\n<pre><code>def file_to_one_line(file):\n \"\"\" Concats all lines in file to one line \"\"\"\n with open(file, \"r\") as file_to_read:\n return file_to_read.read()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T01:49:17.117",
"Id": "224709",
"ParentId": "224706",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224709",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T22:38:13.997",
"Id": "224706",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"compression"
],
"Title": "File compressor"
}
|
224706
|
<p>I recently got a prompt when looking for a job. To spare any details, the company decided not to get back to me, so because I did not get a code-review/feedback from them, I was wondering if someone would review this and tell me how i could improve it. </p>
<p>Here is a link to the full prompt (pretty long) with sample input and expected output: <a href="https://docs.google.com/document/d/1QlJJcf7mr81602QPM_zgz15Ud5kalXSGxkiMjqO74os/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/document/d/1QlJJcf7mr81602QPM_zgz15Ud5kalXSGxkiMjqO74os/edit?usp=sharing</a></p>
<p>The gist of it, is to write a script that manages a system's dependencies for handling the installing/uninstalling of various packages inside a system. In doing some digging around (after I turned it in), I found that this is not only a common interview question, but also is part of <a href="http://www.cs.cornell.edu/Info/Courses/Spring-98/CS211/assgts/assgt3/assgt3.pdf" rel="nofollow noreferrer">Cornell's CS program</a> </p>
<p>I was pretty proud of myself for completing this, and right now, based on the prompt there are only 2 problems. </p>
<ol>
<li><p>I was unable to figure out the proper rendering (in order) of the (first) <code>LIST</code> command. However, in both spots where called, <code>LIST</code> returns all the correct elements</p></li>
<li><p>The <code>HTML</code> component does not output in the <code>REMOVE BROWSER</code> call towards the end, but it does not list in the final LIST command</p></li>
</ol>
<p>This is exactly the code I turned in with no modifications. Here is my code</p>
<pre><code>class DependencyManager
attr_reader :name
attr_accessor :dependencies
def initialize(text_input)
@text_input = text_input
@dependencies = DependencyList.new
end
def call
@text_input.each_line do |line|
line = line.gsub(/[^a-z0-9\s]/i, '')
line_list = line.split(' ')
if line_list[0] == 'DEPEND'
puts "#{line_list.join(' ')}"
depend(line_list)
elsif line_list[0] == 'INSTALL'
puts "INSTALL #{line_list[1]}"
install(line_list)
elsif line_list[0] == 'REMOVE'
puts "REMOVE #{line_list[1]}"
remove(line_list)
elsif line_list[0] == 'LIST'
puts "LIST"
list(line_list)
elsif line_list[0] == 'END'
handle_end
else
print 'INVALID INPUT'
end
end
end
def depend(line_list)
first = line_list.slice(0, 2)
second = line_list.slice(2, line_list.length)
dependency = Dependency.new(first[1])
second.each do |depend|
dep = Dependency.find_by_name(depend)
if dep
dep.depends_on.list.push(dependency)
else
dep = Dependency.new(depend)
dep.depends_on.list.push(dependency)
end
end
dependency.dependencies.list.concat(second)
@dependencies.list.push(dependency)
end
def install(line_list)
dep_name = line_list[1]
elem = Dependency.find_by_name(dep_name)
if elem
# already exists, just install item and all dependencies
elem.dependencies.list.select { |dep|
Dependency.find_by_name(dep).installed == false
}.each { |dep|
Dependency.find_by_name(dep).installed = true ;
p "Installing #{dep}"
}
if elem.installed == true
p "#{elem.name} is already installed."
else
elem.installed = true
p "Installing #{elem.name}"
end
else
dep = Dependency.new(dep_name, true)
p "Installing #{dep.name}"
elem = dep
end
@dependencies.list.push(elem)
end
def remove(line_list)
dep_name = line_list[1]
elem = Dependency.find_by_name(dep_name)
if elem.installed == false
return p "#{elem.name} is not installed."
end
installed_components = @dependencies.list.select { |dep| dep.installed == true }
installed_components.each do |component|
if component.dependencies.list.include?(elem.name)
return p "#{elem.name} is still needed."
end
end
# multi-level removals
elem.installed = false
p "Removing #{elem.name}"
elem.depends_on.list.each do |dep|
dep = Dependency.find_by_name(dep)
if dep
dep.installed = false
p "Removing #{dep}"
end
end
end
def list(line_list)
new_list = []
@dependencies.list.select { |dep| dep.installed == true }.each do |dep|
new_list.push(dep.name)
dep.dependencies.list.each do |inner_dep|
new_list.push(inner_dep)
end
end
# output better?
new_list = new_list.uniq
new_list.each do |item|
p "#{item}"
end
end
def handle_end
puts "END"
end
end
class Dependency
attr_reader :name, :id
attr_accessor :installed, :dependencies, :depends_on
@@id = 1
@@all = []
def initialize(name, installed = false)
@name = name
@installed = installed
# child
@dependencies = DependencyList.new
# parent
@depends_on = DependencyList.new
@id = @@id
@@id += 1
@@all << self
end
# input: string
# output: dependency (if exists) or false (if not exists)
def self.find_by_name(name)
elem = @@all.select { |dep| dep.name == name}
if elem.empty?
return false
else
return elem.pop
end
end
end
class DependencyList
attr_accessor :list
def initialize
@list = []
end
end
sample_input = <<-EOT
DEPEND TELNET TCPIP NETCARD
DEPEND TCPIP NETCARD
DEPEND DNS TCPIP NETCARD
DEPEND BROWSER TCPIP HTML
INSTALL NETCARD
INSTALL TELNET
INSTALL foo
REMOVE NETCARD
INSTALL BROWSER
INSTALL DNS
LIST
REMOVE TELNET
REMOVE NETCARD
REMOVE DNS
REMOVE NETCARD
INSTALL NETCARD
REMOVE TCPIP
REMOVE BROWSER
REMOVE TCPIP
LIST
END
EOT
dependency_manager = DependencyManager.new(sample_input)
dependency_manager.call
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T12:22:18.797",
"Id": "436329",
"Score": "0",
"body": "The problem maps a graph data structure and a topological sort of graph would tell you which components to install in what order, with a dictionary to tell you whether it has been installed already or not. Your solution does not use a proper data structure suitable for the problem."
}
] |
[
{
"body": "<ol>\n<li>In <code>call</code> why do you reassemble string from parts instead just of echoing exact <code>line</code> from input?</li>\n<li>You should use Sets and Hashes, there should be no need to write <code>find_by_name</code> method. <code>LIST</code> should just list items of some <code>installed</code> Set, there should be no need for additional processing.</li>\n<li>Both <code>install</code> and <code>remove</code> probably should use recursion, it is natural way to process dependency graphs.</li>\n<li>I would expect <code>handle_end</code> to stop processing input, currently it does nothing.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:12:09.753",
"Id": "224823",
"ParentId": "224710",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T02:36:09.533",
"Id": "224710",
"Score": "3",
"Tags": [
"ruby",
"interview-questions"
],
"Title": "System Dependency Manager - Ruby"
}
|
224710
|
<blockquote>
<p>The series, <span class="math-container">\$1^1 + 2^2 + 3^3 + \ldots + 10^{10} = 10405071317\$</span>.</p>
<p>Find the last ten digits of the series, <span class="math-container">\$1^1 + 2^2 + 3^3 + \ldots + 1000^{1000}\$</span>.</p>
</blockquote>
<pre><code>def self_power(n):
"""returns sum of self powers up to n."""
total = 0
for i in range(1, n + 1):
total += i ** i
return str(total)[-10:]
if __name__ == '__main__':
print(self_power(1000))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T06:51:23.307",
"Id": "435934",
"Score": "3",
"body": "You got answers to 23 of your 29 questions – is there a reason that you *accepted* only 3 answers too far? And why don't you tag your questions correctly with [python], as pointed out to you repeatedly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:09:05.093",
"Id": "435936",
"Score": "0",
"body": "there is no best answer mostly and my questions are tagged with python-3.x."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:24:48.467",
"Id": "435938",
"Score": "3",
"body": "And, again, the [tag:python-3.x] excerpt states, in the first few words, that you should _\"Use this tag along with the main python tag\"_…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:26:45.100",
"Id": "435939",
"Score": "0",
"body": "you mean in the description?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:30:45.730",
"Id": "435940",
"Score": "0",
"body": "Yes, just hover over the tag in the question and you may see it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:34:09.703",
"Id": "435941",
"Score": "0",
"body": "i'm sorry but I really can't get what you want me to do"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:34:55.230",
"Id": "435942",
"Score": "0",
"body": "Just use the tag [tag:python] along with the tag [tag:python-3.x] so we don't have to add it ourselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:35:58.713",
"Id": "435943",
"Score": "1",
"body": "okay, from now on, all my posts will contain python and python 3.x. Anything else?"
}
] |
[
{
"body": "<p>You can compute the sum of the powers with <code>sum()</code> and a generator expression:</p>\n<pre><code>total = sum(i ** i for i in range(1, n + 1))\n</code></pre>\n<p>instead of a for-loop. Retrieving the last 10 digits can be done with the modulus operator <code>%</code> instead of converting it to a string:</p>\n<pre><code>return total % (10 ** 10)\n</code></pre>\n<p>Your code already runs in fractions of a second. For even larger exponents it would be more efficient to compute only the last 10 digits of each intermediate result. This can be done with the three-argument form of <a href=\"https://docs.python.org/3/library/functions.html#pow\" rel=\"nofollow noreferrer\"><code>pow()</code></a>:</p>\n<blockquote>\n<p><strong>pow(x, y[, z])</strong></p>\n<p>Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z).</p>\n</blockquote>\n<p>Putting it together:</p>\n<pre><code>def self_power(n):\n """returns sum of self powers up to n."""\n MOD = 10 ** 10\n total = sum(pow(i, i, MOD) for i in range(1, n + 1))\n return total % MOD\n</code></pre>\n<p>This runs a tiny bit faster:</p>\n<pre>\n$ # Your version:\n$ python3 -m timeit 'import euler48; euler48.self_power0(1000)'\n50 loops, best of 5: 9.55 msec per loop\n\n$ # Improved version:\n$ python3 -m timeit 'import euler48; euler48.self_power(1000)'\n100 loops, best of 5: 2.19 msec per loop\n</pre>\n<p>But it makes a big difference if the numbers become larger:</p>\n<pre>\n$ # Your version:\n$ python3 -m timeit 'import euler48; euler48.self_power0(10000)'\n1 loop, best of 5: 6.65 sec per loop\n\n$ # Improved version:\n$ python3 -m timeit 'import euler48; euler48.self_power(10000)'\n10 loops, best of 5: 28.6 msec per loop\n</pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:24:00.567",
"Id": "224721",
"ParentId": "224714",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T06:38:09.187",
"Id": "224714",
"Score": "0",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 48 Self powers in Python"
}
|
224714
|
<p>The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual
in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are
permutations of one another.</p>
<p>There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this
property, but there is one other 4-digit increasing sequence.</p>
<p>What 12-digit number do you form by concatenating the three terms in this sequence?</p>
<pre><code>from time import time
def sieve(n):
"""generates primes up to n."""
s = [True] * (n + 1)
for p in range(2, n):
if s[p]:
yield p
for i in range(p * p, n, p):
s[i] = False
def is_permutation(n1, n2):
"""returns True if n1 is permutation of n2"""
to_str_1 = str(n1)
to_str_2 = str(n2)
if n1 == n2:
return False
to_str_1_digits = {digit: to_str_1.count(digit) for digit in to_str_1}
to_str_2_digits = {digit: to_str_2.count(digit) for digit in to_str_2}
if not to_str_1_digits == to_str_2_digits:
return False
return True
def get_permutations(n):
"""generates tuples of 3 permutations each within range n."""
primes = set(sieve(n))
for prime1 in primes:
for prime2 in primes:
if is_permutation(prime1, prime2):
for prime3 in primes:
if is_permutation(prime3, prime1) and is_permutation(prime3, prime2):
yield prime1, prime2, prime3
def check_subtraction(n):
"""checks permutations within range n for subtraction rules.
returns valid permutations."""
permutations = get_permutations(n)
for x, y, z in permutations:
if abs(x - y) == abs(y - z):
return x, y, z
if __name__ == '__main__':
start_time = time()
x, y, z = sorted(check_subtraction(10000))
print(str(x) + str(y) + str(z))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[] |
[
{
"body": "<p><strong>Micro optimisations in <code>is_permutation</code></strong></p>\n\n<p>In <code>is_permutation</code>, you could call the <code>str</code> functions <em>after</em> checking whether <code>n1 == n2</code>.</p>\n\n<p>Also, you could simplify the end of the function with a single <code>return to_str_1_digits == to_str_2_digits</code>.</p>\n\n<p>Taking into account these comments and shortening a bit the variable names, we get:</p>\n\n<pre><code>def is_permutation(n1, n2):\n \"\"\"returns True if n1 is permutation of n2\"\"\"\n if n1 == n2:\n return False\n str1 = str(n1)\n str2 = str(n2)\n digits1 = {digit: str1.count(digit) for digit in str1}\n digits2 = {digit: str2.count(digit) for digit in str2}\n return digits1 == digits2\n</code></pre>\n\n<p><strong>Improving the algorithm</strong></p>\n\n<p>We generate a set of primes and iterate over it with nested loops. A faster way would be to be able to group primes which correspond to the same permutation.</p>\n\n<p>An efficient way to do it would be to use a dictionnary mapping a hashable value to the list of primes being permutations of each other. That value should be chosen to be some kind of signature which would be the same if and only if values are permutations. For instance, we could use the string representation of prime p sorted alphabetically: <code>''.join(sorted(str(p)))</code>.</p>\n\n<p>Once they are grouped, we can easily get the different permutations:</p>\n\n<pre><code>def get_permutations(n):\n \"\"\"generates tuples of 3 permutations each within range n.\"\"\"\n permut_primes = dict()\n for p in sieve(n):\n permut_primes.setdefault(''.join(sorted(str(p))), []).append(p)\n for perms in permut_primes.values():\n for a, b, c in itertools.combinations(perms, 3):\n assert c > b > a\n yield a, b, c\n</code></pre>\n\n<p>This also needs a minor change in <code>check_substraction</code> to ensure we do not find the already provided result:</p>\n\n<pre><code>def check_subtraction(n):\n \"\"\"checks permutations within range n for subtraction rules.\n returns valid permutations.\"\"\"\n permutations = get_permutations(n)\n for x, y, z in permutations:\n if abs(x - y) == abs(y - z) and x != 1487:\n return x, y, z\n</code></pre>\n\n<p>The corresponding code is more than 500 times faster than the original code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:54:47.767",
"Id": "224725",
"ParentId": "224716",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "224725",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T08:33:47.733",
"Id": "224716",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 49 Prime permutations in Python"
}
|
224716
|
<p>For this Code, I am provided a text file that contain several cities. I am suppose to identify the cities mentioned and print their state and country.</p>
<p><strong>Requirements:</strong> If a mentioned city is in two or more countries, I ask the user to mention which city they are talking about. In addition if there is a slight typo, I ask the user if they meant a certain city instead. For example if they type 'Dalls' instead of 'Dallas' I need to provide the user options such as 'Do you mean Dallas instead of Dalls'.</p>
<p><strong>Problem:</strong> My code has been working pretty well, but I feel it can be significantly simplified. Please let me know what concepts I can use to further simplify my code.</p>
<p><strong>File Explanations:</strong> I am using a text called 'world-cities.csv', 'TEXT.txt' and 'usa.txt'. 'world-cities.csv' is a file that contains a lot of cities in the world. 'TEXT.txt' is a file that contains the sentences that I will be analyzing for cities. 'usa.txt' contains common words in the english language. I used it to compare to 'TEXT.txt' to remove common words. I had a problem with words such as 'and' showing up as typos. So this was a bootleg method to get rid of them.</p>
<p>I am trying not to use imports like geotext, and instead focus more on finding the most logically efficient way to program. If I am wrong about this, let me know. </p>
<pre><code>import pandas as pd
import re
#imported dataset
dataset = pd.read_csv('world-cities.csv')
#assigned certain parts of data set to variable
data = dataset.iloc[:,:-1]
city = dataset.iloc[:,0]
state = dataset.iloc[:,2]
country = dataset.iloc[:,1]
#opened and imported textfile
txtfile = open('TEXT.txt','r')
txtfile = txtfile.read()
words = open('usa.txt','r')
words = words.read()
#getting rid of punctation
altered = re.sub("[.,:]",'',txtfile)
templist = [] #holds the cities(state and country) info of the places
mentioned in the paragraph
final = [] #final array
all_cities = [] #holds all the cities mentioned, used to check for
repeating cities
repeat = {} #contains only city names
repeatinfo = [] #contain all infor about repeating cities
stupid = 0
close = 0
typo = []
typodict = {}
typecount = 0
finaltypo = []
altered2 = []
ban = []
temp = []
#finding out where the talked about cities are
for x in altered.split():
count = 0
zcount = 0
for y in city:
if x == y:
zcount +=1
templist.append([city[count], state[count], country[count]])
all_cities.append(city[count])
count+=1
if zcount > 1:
repeat[x] = zcount
#finding two worded cities
for count,y in enumerate(city):
if y in altered:
if y not in all_cities:
if len(y.split()) >1:
zcount +=1
templist.append([city[count], state[count],
country[count]])
all_cities.append(city[count])
temp.append(city[count])
#removing one city words identified from two worded cities (York vs New
York)
#splitting words
split = []
for x in temp:
for y in x.split():
split.append(y)
#removing from all_cities
for x in all_cities:
for y in split:
if y in all_cities:
all_cities.remove(y)
ban.append(y)
#removing from templist
for x in ban:
for y in templist:
if x == y[0]:
templist.remove(y)
#removing form repeat
#print(repeat)
for x in list(repeat):
if x in ban:
repeat.pop(x)
#put in all assumed Typos
for x in altered.split():
if x not in all_cities:
x = x.lower()
if x not in words:
typo.append(x)
#narrow down options of typos
many = 0
for a in typo:
for b in city:
b = b.lower()
if len(a) >= (len(b)-1) and len(a) <= (len(b)+1):
if a[0] == b[0] or a[-1::] == b[-1::]:
if a[0:3] == b[0:3] or a[-3::] == b[-3::]:
#print(f'{a} vs {b}')
many = 0
for x in a:
if x in b:
many+=1
if many >= (len(b)-1) and many <= (len(b)+1):
typodict[b] = a
#let user choose if it is a typo or not
print('TYPO Checking')
for a in typo:
p =0
q = 0
while(p < len(typo) and q == 0):
for x,y in typodict.items():
go2 = True
while(go2 and q==0):
if y == a:
user2 = input(f" Did you mean to type '{x}' instead of
'{y}'? Enter 'y' or 'n': ")
user2 = user2.lower()
if user2 == 'y':
go2 = False
finaltypo.append(x)
p+=1
q+=1
elif user2 == 'n':
go2 = False
else:
print('You have entered a invalid value')
else:
go2 = False
#adding typoed cities into list
for x in finaltypo:
x = x.capitalize()
count = 0
zcount = 0
for y in city:
if x == y:
zcount +=1
templist.append([city[count], state[count], country[count]])
all_cities.append(city[count])
count+=1
if zcount > 1:
repeat[x] = zcount
#finding out what cities repeat and adding all their information to repeat
info
for x in repeat:
rcount = 0
for y in city:
if x == y:
repeatinfo.append([city[rcount], state[rcount],
country[rcount]])
rcount +=1
#determining which country they mean when they mentioned repeating cities
print('\n Which City?')
for x,y in repeat.items():
i = 0
e = 0
while(i < y and e == 0):
go = True
for c in repeatinfo:
go = True
while(go and e == 0):
if x == c[0]:
user = input(f'Do you mean {x} in {c[1]},{c[2]} enter y
or n: ')
user = user.lower()
i +=1
if user == 'y':
final.append(f' {x} in {c[1]}, {c[2]}')
go = False
i +=1
e +=1
elif user == 'n':
go = False
i+=1
else:
print('You have entered a invalid input')
else:
go = False
#removing repeating cities from templist
for y in list(templist):
if y[0] in list(repeat):
templist.remove(y)
#adding remaining elements of templist to final list
for y in list(templist):
final.append(f' {y[0]} in {y[1]}, {y[2]}')
#printing final output
print('\n You have entered the following cities:')
for x in final:
print(x)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:27:36.370",
"Id": "435952",
"Score": "0",
"body": "You probably want to start by looking at the lists comprehension in python, [here](https://www.datacamp.com/community/tutorials/python-list-comprehension) for example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T13:53:16.310",
"Id": "435967",
"Score": "2",
"body": "@Mayeulsgc Comments are for seeking clarification to the question, and may be deleted. Please put all suggestions for improvements in answers, even trivial hints."
}
] |
[
{
"body": "<p>Here are some general comments:</p>\n\n<h3>Close files</h3>\n\n<p>Close files when you are done with them. Or better yet use a <code>with statement</code> to automatically close the file at the end of the code block (the indented part)</p>\n\n<pre><code>with open('TEXT.txt','r') as txtfile:\n text = txtfile.read()\n</code></pre>\n\n<h3>Variable names</h3>\n\n<p>Try to use meaningful variable names. That doesn't mean they have to be long names, depending on the context <code>i,j,k</code> or <code>x,y,z</code> can be meaningful names. 'temp', 'stupid' probably aren't meaningful.</p>\n\n<p>And try to be consistent about a variables represent. In your code, sometimes <code>x</code> is a word in the text file, other times it is a two word city, any city, a typo, or a text line in the final output. So when someone (or you) reading your code sees the variable <code>x</code>, they must look around to see what <code>x</code> is this time.</p>\n\n<h3>Use functions</h3>\n\n<p>The program is one big run of code. That makes it hard to understand and reason about. To help structure and manage the program, try breaking it up into several functions that each do one thing. A rule of thumb is that a function should fit on your screen so you can see all of it at once. </p>\n\n<p>Separate functions lets you test portions of your program to make sure they work as intended. That makes debugging easier. For example, does the code to check if a one word city (e.g. York) should be a two word city (e.g. New York) work correctly if both cities are in the text? Can you test it to make sure? What about cities with more than two words (e.g., Rio de Janeiro).</p>\n\n<p>Functions can also help you keep related code together. In this program, the textfile is read in one place, it is processed to remove (some) punctuation in another place, and split into words in two other places.</p>\n\n<h3>Data structures</h3>\n\n<p>Choosing the right data structure can make a big difference in how complex your code is. For example, <code>data</code>, <code>city</code>, <code>state</code>, and <code>country</code> are parallel lists. So your code keeps track of an index into the <code>city</code> so it can access the other information. If you used a dict keyed by the city, the indexes can be eliminated. The value of a dict entry can be a list of tuples with the state, country, and data info. The list has multiple entries if more than one city has the same name:</p>\n\n<pre><code>cities = { 'Dallas':[('Texas', 'USA', 'dallas data')],\n 'York' :[('North Yorkshire', 'England', 'york england data'),\n ('Maine', 'USA', 'york maine data')],\n 'Mexico':[('Kansas', 'USA', 'mexico kansas data']\n ... etc.\n }\n</code></pre>\n\n<p>Obviously, this would be built from the world_cities.csv file (see below).</p>\n\n<h3>Standard library</h3>\n\n<p>The standard library has lots of useful functions. Some that may be useful here are <code>collections</code>, <code>csv</code>, and <code>difflib</code>:</p>\n\n<p><code>collections.defaultdict</code> is useful for building dictionaries on the fly.</p>\n\n<p>You only use <code>pandas</code> to read in the csv file, but you can use <code>csv</code> from the standard library. <code>csv.reader</code> or <code>csv.DictReader</code> can be used to read a csv file:</p>\n\n<pre><code>import collections\nimport csv\n\ncities = defaultdict(list)\n\nwith open('world_cities.csv', newline='') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n city = row[0]\n state = row[2]\n country = row[1]\n data = row[-1]\n cities[city].append(state, country, data)\n</code></pre>\n\n<p>And <code>difflib.get_close_matches()</code> can be used to search for words in a list that are close enough to a search term. There are parameters to control how close the match needs to be, and a maximum number of matches:</p>\n\n<pre><code>import difflib\n\n# after you built the cities dict above, you would use\n# city_names = list(cities.keys())\n# but for illustration:\ncity_names = ['York', 'New York', 'Devon', 'Peoria', 'Dallas', ]\n\ndifflib.get_close_matches('York', city_names) ==> ['York', 'New York']\n\ndifflib.get_close_matches('dalas', city_names) ==> ['Dallas']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T11:51:32.023",
"Id": "436137",
"Score": "0",
"body": "I am confused with the purpose of 'cities[row[0]print(row['first_name'], row['last_name'])'. It is giving me an error 'invalid syntax' even when I separate cities[row] and the print statement into new lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:29:58.250",
"Id": "436153",
"Score": "0",
"body": "@Susanth Sorry that should not be there. I fixed the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:08:31.830",
"Id": "440681",
"Score": "0",
"body": "you can use unpacking, and do `for city, country, state, data in reader`, which is both shorter, and more clear. You also say to use functions, but then do the assembling of the city data in a plain script instead of showing how you can put something in a logical function"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T06:36:02.693",
"Id": "224785",
"ParentId": "224720",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T09:23:49.100",
"Id": "224720",
"Score": "0",
"Tags": [
"python"
],
"Title": "Python program to identify cities, with spelling check"
}
|
224720
|
<p>I'm calculating now the total garnered hours student get in school using php.</p>
<p>(Same concept in getting the total work hours in employee for timesheets)</p>
<p>So I have an array <code>$attendance</code> where the student check in and out in school.</p>
<pre><code>$attendance = [
"2019-07-01 08:03:00",
"2019-07-01 12:12:00",
"2019-07-01 13:03:00",
"2019-07-01 17:00:00",
];
</code></pre>
<p><strong>$schedules</strong> is on what time the student should check in and out.</p>
<pre><code>$schedules = [
[
"time_start" => "08:00:00",
"time_end" => "12:00:00",
"in_threshold" => 15,
"out_threshold" => 15
],
[
"time_start" => "13:00:00",
"time_end" => "17:00:00",
"in_threshold" => 15,
"out_threshold" => 15
]
];
</code></pre>
<p>The <strong>threshold</strong> is a minute the student should check in/out if the student check in above threshold it will result to late. (Eg. <code>08:16:00</code> checks in. He/she is late )</p>
<p>Code below is for storing time_start and time_end to array which is the basis for time_in and out:</p>
<pre><code>foreach($schedules as $schedule){
// Set time_start and time_end with threshold
$mytime_start[] = date( "H:i:s",
strtotime('+'. $schedule[ 'in_threshold' ] .' minutes',
strtotime ( $schedule[ 'time_start' ]
)));
$mytime_end[] = date( "H:i:s",
strtotime('+'. $schedule[ 'out_threshold' ] .' minutes',
strtotime( $schedule[ 'time_end' ]
)));
// Get time_start and time_end to array
$sched_starts[] = ( $schedule[ 'time_start' ] );
$sched_ends[] = ( $schedule[ 'time_end' ] );
}
</code></pre>
<p>Note: The schedule time_start and time_end can be change. Function <code>getClosestTime</code> will get the <strong>closest time</strong> of each attendance. It will identify if the logs is for schedule <code>time_start</code> or <code>time_end</code>.</p>
<pre><code>function getClosestTime( $array, $date ){
foreach( $array as $day ){
$interval[] = abs(strtotime($date) - strtotime($day));
}
asort($interval);
$closest = key($interval);
return $array[$closest];
}
</code></pre>
<p>Get <code>$attendance</code> by 2. for Punch IN and OUT</p>
<pre><code>for ($index = 0; $index < count($attendance); $index += 2)
</code></pre>
<p>Expected the two element of array is in and out.</p>
<pre><code>$date_start = $attendance[$index]; // Punch In
$date_end = $attendance[$index + 1]; // Punch Out
</code></pre>
<p>Get only date in $attendance (If the schedule cross midnights)</p>
<pre><code>$to_date_start = date("Y-m-d", strtotime($date_start));
$to_date_end = date("Y-m-d", strtotime($date_end));
</code></pre>
<p>Get closest Time for each element in <code>$attendance</code></p>
<pre><code>$time_start = getClosestTime($mytime_start, date('H:i:s',strtotime($date_start)));
$time_end = getClosestTime($mytime_end, date('H:i:s',strtotime($date_end)));
</code></pre>
<p>If there's an instance if the student check in late and the closest time is not the exact <code>time_start</code> for its <code>time_end</code>.</p>
<pre><code>if ($time_start > $time_end) {
$time_start = date("Y-m-d", strtotime($date_start));
}
</code></pre>
<p>Add dates in schedule time start and time_end</p>
<pre><code>$time_start = date('Y-m-d H:i:s', strtotime("$to_date_start $time_start"));
$time_end = date('Y-m-d H:i:s', strtotime("$to_date_end $time_end"));
</code></pre>
<p>Set the exact datetime when the student should check in/out</p>
<pre><code>$time_minus_start = date("Y-m-d H:i:s", strtotime("-15 minutes $time_start"));
$time_minus_end = date("Y-m-d H:i:s", strtotime("-15 minutes $time_end"));
</code></pre>
<p>Check <code>check in</code> if it is above the threshould same logic for <code>check out</code></p>
<pre><code>if ($date_start > $time_start) {
$start = $late;
$total_late += 1;
}else {
$start = $exact_in;
}
</code></pre>
<p>If <code>$attendace</code> is exact time_start and time_end return its date</p>
<pre><code>if (isBetween($time_minus_start, $time_start, $date_start)
&& isBetween($time_minus_end, $time_end, $date_end)) {
$start = $within_in;
$end = $within_out;
} else if (isBetween($time_minus_start, $time_start, $date_start) && $date_end > $time_end) {
$start = $within_in;
$end = $late_out;
}
</code></pre>
<p>Sum check in and check out result</p>
<pre><code>$total_garner_hours += ($end - $start);
</code></pre>
<p>In my algorithm:</p>
<p>Student <strong>check in early</strong> and <strong>check out late</strong> then <code>$start</code>/<code>$end</code> return the exact time student should check in/out.</p>
<p>Student <strong>check in late</strong> and <strong>check out early</strong> <code>$start</code>/<code>$end</code> return the real-time data.</p>
<p>Here is my live code: <a href="https://3v4l.org/9MaEc" rel="nofollow noreferrer">https://3v4l.org/9MaEc</a></p>
<p>I would like to make the code more <strong>efficient</strong> and <strong>reliable</strong>. I'm a beginner and I admit it, my code is so messed up.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T22:42:39.880",
"Id": "436023",
"Score": "0",
"body": "So is this just a repost of the same question after your first post gathered no reviews? Do you want to delete the first one? I don't know why CodeReview would want the redundance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T22:53:59.270",
"Id": "436024",
"Score": "0",
"body": "Its not. Its different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T02:16:20.420",
"Id": "436041",
"Score": "0",
"body": "Are you not asking for a review of the same script, duplicating lots of the same question body content, and sharing the same 3v4l demo link? Looks _rather_ similar at a glance. Do explain the difference please, because it is not instantly obvious to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T04:52:25.680",
"Id": "436059",
"Score": "0",
"body": "A lot of difference but have same function. In previous I only modify the attendance if it is ```early``` or ```out``` but here It calculate the total hours"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T04:53:37.577",
"Id": "436060",
"Score": "0",
"body": "It's a continuation of attendance in biometrics in php. Do I need to edit my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T04:59:32.200",
"Id": "436061",
"Score": "1",
"body": "That's okay, I just wanted to be clear about the difference. I intend to review your scripts, but have been too busy at work. When I find time, I didn't want to do the same review twice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-31T15:36:31.893",
"Id": "437337",
"Score": "0",
"body": "If this is a follow on question it is possible to link to the previous question."
}
] |
[
{
"body": "<p>The algorithm does not allow for the possibility of a transition from daylight time to standard time or vice versa.</p>\n\n<p>Without knowing the mechanism for obtaining the date and time, it's impossible to say if the algorithm needs to be aware of time zones. In principle, the student could be attending by video conference and be in a different time zone.</p>\n\n<p>If the time and date is obtained from a device belonging to the student, the student may prefer to operate the device on a time zone different from the school. For example, both the student and the school could be located in New York but the student corresponds with people all over the world, so keeps her laptop set to UTC.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:28:35.053",
"Id": "224736",
"ParentId": "224728",
"Score": "2"
}
},
{
"body": "<p>Adding to what Gerard has answered, there are some PHP libraries that deal with time very well which you could implement. One example is <a href=\"https://carbon.nesbot.com/docs/\" rel=\"nofollow noreferrer\">Carbon</a>.</p>\n\n<p>I would separate out your date comparisons into its own function. May be useful elsewhere and is a little clearer. Everything in your for loop up to your first if statement could be its own function.</p>\n\n<p>You could improve your formatting a little (don't know if copy and pasting into Stack Exchange has caused it) but you can take a look at <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a>. Naming variables a little clearer will be helpful to you, those reviewing your code and to anybody who may now/in the future work on this code, e.g. <code>mytime_start</code> doesn't make it clear what time you are talking about, and <code>index</code> could simply be referred to as the standard <code>i</code>.</p>\n\n<p>Remember to <a href=\"http://docs.php.net/manual/da/language.oop5.typehinting.php\" rel=\"nofollow noreferrer\">type hint</a> your parameters and give <a href=\"https://mlocati.github.io/articles/php-type-hinting.html\" rel=\"nofollow noreferrer\">return values</a>.</p>\n\n<p>Hope this helps a bit!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T04:34:07.910",
"Id": "436774",
"Score": "0",
"body": "Like these? https://3v4l.org/XDTsI"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T16:05:48.497",
"Id": "224910",
"ParentId": "224728",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T12:12:06.290",
"Id": "224728",
"Score": "5",
"Tags": [
"beginner",
"php",
"array",
"datetime"
],
"Title": "Algorithm in getting total garnered hours for student"
}
|
224728
|
<p>I've been working on a a text based game with a very simple battling system. There are way to many questions I can ask to get reviewed about this project, but I'll take small steps at a time (this is my first post).</p>
<p>I'm mostly concerned about how I handle command input and the execution of said commands within the game. Just to give a simple example of what a command might look like:</p>
<pre><code>go north
go - command (called action in the code, as Command is the whole class)
north (and anything after that) - arguments, you most likely know about these
</code></pre>
<h2>INPUT</h2>
<p>Currently, I've made it work using the <code>readline</code> package from Node. The input is being sent to a "commander" where it is parsed, made into a <code>Command</code> which will in the end be passed to an "executor" which will execute the command. Here's the code:</p>
<pre class="lang-js prettyprint-override"><code>//Player.ts
import readline from 'readline';
//other imports...
class Player extends Entity {
// fields, constructor and other methods...
async getInput(questionPrompt?: string): Promise<string> {
return new Promise((resolve, _) => {
const prompt = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const question = (questionPrompt) ? questionPrompt : ">";
prompt.question(question, (answer) => {
prompt.close()
resolve(answer);
})
})
}
}
export default Player;
</code></pre>
<pre class="lang-js prettyprint-override"><code>//commander.ts (technically it's inside commander/index.ts)
import Command from '../models/Command';
import Player from '../models/Player';
const actions = ['go', 'look', 'take', 'equip', 'inventory', 'help'];
export const parse = (text: string): (Command | null) => {
const action = text.split(' ')[0];
const args = text.split(' ').slice(1);
if (!actions.find((a) => action === a))
return null;
return new Command(action, args);
}
export const execute = (command: Command, receiver: Player) => {
switch (command.action) {
case 'go':
const success = receiver.move(command.args[0]);
if (success) {
return console.log(`You have entered a new room.\n${receiver.currentRoom.getDescription()}`);
} else {
return console.log(`You can't go there. Please try another one.`);
}
case 'look':
const text = `You are in ${receiver.currentRoom.name}.\n` +
`${receiver.currentRoom.description}`;
return console.log(text);
case 'take':
const item = receiver.currentRoom.takeItem(command.args[0]);
if (item)
return receiver.takeItem(item);
else
return console.log(`A ${command.args[0]} couldn't be found.`);
case 'equip':
return receiver.inventory.map((i) => {
if (i.name === command.args[0]) {
receiver.equip(i.id);
}
})
case 'inventory':
return console.log(receiver.inventory);
case 'help':
return console.log("No help for now... Maybe later?");
default:
console.log('Command error.');
return console.log(command);
}
}
export default {
parse,
execute,
}
</code></pre>
<p>I'm not entirely sure if this is an appropriate way to handle this use case, but this is all I could come up with. The other solution I managed to think of was to have the different commands in a separate folder where I could have them as modules and I could try to import them. This way they can maybe be classes and have their own help messages which will also make it easier to document the commands. The reason I decided to stick with this approach is because it seems a bit easier, and having the commands as separate modules kinds seems overkill to me, maybe I'm totally wrong.</p>
<p>I know I've probably missed something very important, so a link to the whole project can be found <a href="https://github.com/Federlizer/zuul-game/tree/8ff93ac48027dd6ba4d4f85d52fe5d451e983775" rel="nofollow noreferrer">here</a>.</p>
|
[] |
[
{
"body": "<p>From my experiences in MUDs and text games, I think you would do well to create a class/module that handles each command then inject them into your processor (even manually). It will help a lot with the maintainability but also isolating commands.</p>\n\n<pre><code>import {registerLook} from \"./commands/look\";\nimport {registerGo} from \"./commands/go\";\n\n// Build up a hash of commands. With a MUD style, you would register the shorten\n// versions also (so look registers as \"l\", \"lo\", \"loo\", and \"look\") but removes\n// entries that would have a conflict (so \"left\" would remove the \"l\" for look but\n// register \"le\", \"lef\", and \"left\".\nlet commands = {};\n\nregisterLook(commands);\nregisterGo(commands);\n\n// Then when you are running the command.\nif (command.action in commands\n{\n commands[command.action].run(command, receiver);\n}\nelse\n{\n // Show error of missing command\n}\n</code></pre>\n\n<p>You could go further with the SOLID implementation by having the commands injected from the top-level, but the main reason for doing this is to let you have the complex logic for the commands moved into a separate file that does one thing only (Single Responsibility Principle) while treating the switch of the commands against an interface (functions inserted into the hash by a register).</p>\n\n<p>Ideally, having a DI figure out the commands would be nice, but I haven't found a good DI system for Typescript I like. (You could also scan the <code>commands</code> directory and inject the commands that way.)</p>\n\n<p>It also lets you nest the commands if you need to. So if you have <code>look at</code> and <code>look into</code>, you could have <code>commands/look.ts</code> break apart the first word and then pass it into look commands (<code>commands/look/at.ts</code>) to further isolate it. Or whatever makes sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T16:08:26.910",
"Id": "224739",
"ParentId": "224729",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224739",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T12:30:16.430",
"Id": "224729",
"Score": "5",
"Tags": [
"node.js",
"typescript",
"adventure-game"
],
"Title": "Zork look-a-like written in TypeScript"
}
|
224729
|
<p>I've written a <a href="http://practicalcryptography.com/ciphers/caesar-cipher/" rel="nofollow noreferrer">Caesar Cipher</a> in python (a more in-depth explanation is provided in the docstring at the top of the program). At first, it was supposed to just be the cipher, but I expanded it to have the user guess the original string, given the encoded string. I would like feedback on the caesar algorithm, and any other nitpicks you can find in my program. Any and all feedback is appreciated and considered!</p>
<p><a href="https://github.com/karan/Projects#security" rel="nofollow noreferrer">Link to github prompt</a></p>
<p><strong>cipher.py</strong></p>
<pre><code>""" Import Statements """
import random
"""
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet
(A to Z). The encoding replaces each letter with the 1st to 25th next letter in the
alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI"
to "BC". This simple "monoalphabetic substitution cipher" provides almost no security,
because an attacker who has the encoded message can either use frequency analysis to
guess the key, or just try all 25 keys.
Input is all lowercase, so using ord() should use 97-122 a-z
"""
WORDS = [
"thisisarandomstring", "hellomynameisben", "whatisyourname", "thiswaswrittenonamac",
"macsarethebestcomputer", "thisprogramisinpython", "thisonlyhasletters", "andeveryother",
"stringinthislist", "isonlyusingletters", "becausethatshowitworks", "andifyoudontlikeit",
"thenyoucangetyour", "naysayerselfoutofhere", "thatshowiroll"
]
CHART = {
97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g',
104: 'h', 105: 'i', 106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n',
111: 'o', 112: 'p', 113: 'q', 114: 'r', 115: 's', 116: 't', 117: 'u',
118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z'
}
def encode(text, rotations):
""" Encodes the passed text, rotating `rotations` times """
encoded_text = ""
for index in range(len(text)):
new_position = ord(text[index]) + (rotations % 26)
if new_position > 122:
new_position = 97 + (new_position - 122)
encoded_text += CHART[new_position]
return encoded_text
def decode(text, rotations):
""" Decodes the passed text, with the passed rotations """
decoded_text = ""
for index in range(len(text)):
new_position = ord(text[index]) - (rotations % 26)
if new_position < 97:
diff = 97 - new_position
new_position = 122 - diff
decoded_text += CHART[new_position]
return decoded_text
def check_guess(guess):
""" Checks how close the guess is to the original string """
if len(guess) != len(DECODED):
return "Guess must be same length to check guess!"
response = ""
for i in range(len(guess)):
if guess[i] == DECODED[i]:
response += guess[i]
else:
response += " "
return response
if __name__ == '__main__':
ROTATIONS = random.randint(3, 26)
ENCODED = encode(random.choice(WORDS), ROTATIONS)
DECODED = decode(ENCODED, ROTATIONS)
print(f"""
Encoded: {ENCODED}
Length: {len(ENCODED)}
""")
print(f"What is the original string?")
GUESS = input(">>> ")
GUESSES = 1
while GUESS != DECODED:
print(f">>> {check_guess(GUESS)}")
GUESS = input(">>> ")
GUESSES += 1
print("Correct!")
print(f"""
Encoded: {ENCODED}
Original: {DECODED}
Guesses: {GUESSES}
""")
</code></pre>
|
[] |
[
{
"body": "<p>First comment - <code>\"Import Statements\"</code> - is unnecessary.</p>\n\n<hr>\n\n<p>I would add few empty lines to make code more readable - ie. before <code>return</code>, <code>for</code></p>\n\n<hr>\n\n<p>Document <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a> suggest to use <code>UPPER_CASE_NAMES</code> for constant values - <code>WORDS</code> and <code>CHARS</code> you can treat as constant values but <code>ROTATIONS</code>, <code>ENCODED</code>, <code>DECODED</code>, <code>GUESS,</code>GUESSES` are not constant values.</p>\n\n<hr>\n\n<p>Instead of <code>range(len(..))</code> in</p>\n\n<pre><code>for index in range(len(text)):\n new_position = ord(text[index]) - (rotations % 26)\n</code></pre>\n\n<p>you can iterate list</p>\n\n<pre><code>for char in text:\n new_position = ord(char) - (rotations % 26)\n</code></pre>\n\n<hr>\n\n<p>There is similar situation in other loop. </p>\n\n<pre><code>for i in range(len(guess)):\n if guess[i] == DECODED[i]:\n response += guess[i]\n</code></pre>\n\n<p>But here you need <code>i</code> to get <code>DECODED</code> so you can use <code>enumerate()</code> </p>\n\n<pre><code> for i, char in enumerate(guess):\n if char == DECODED[i]:\n response += char\n else:\n response += \" \"\n</code></pre>\n\n<hr>\n\n<p>You can calculate <code>rotations % 26</code> only once - before <code>for</code> loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:51:11.290",
"Id": "224775",
"ParentId": "224730",
"Score": "2"
}
},
{
"body": "<p>Instead of using a <code>CHART[new_position]</code>, I'd recommend using <code>chr(new_position)</code> function instead. Good thing is you're using <code>odr()</code> already.</p>\n<p>Your functions now look like [also as the first answer says, made some changes in way of iterating over elements because you don't need the index anyway]:</p>\n<pre><code>def encode(text, rotations):\n'''\nEncodes the passed text, rotating `rotations` times\n'''\nencoded_text = ""\n for character in text:\n new_position = ord(character) + (rotations % 26)\n if new_position > 122:\n new_position = 97 + (new_position - 122)\n encoded_text += chr(new_position)\n return encoded_text\n\ndef decode(text, rotations):\n'''\nDecodes the passed text, with the passed rotations \n'''\n decoded_text = ""\n for character in text:\n new_position = ord(character) - (rotations % 26)\n if new_position < 97:\n diff = 97 - new_position\n new_position = 122 - diff\n decoded_text += chr(new_position)\n return decoded_text\n</code></pre>\n<p>Not a big deal but you can also pass <code>(rotations % 26)</code> as a third parameter to <code>encode</code> and <code>decode</code> function and calculate <code>(rotations % 26)</code> in the <code>main</code> function. So that your functions look like:</p>\n<pre><code>def encode(text, rotations, rem):\n'''\nEncodes the passed text, rotating `rotations` times\n'''\n encoded_text = ""\n for character in text:\n new_position = ord(character) + rem\n if new_position > 122:\n new_position = 97 + (new_position - 122)\n encoded_text += chr(new_position)\n return encoded_text\n\ndef decode(text, rotations, rem):\n'''\nDecodes the passed text, with the passed rotations \n'''\n decoded_text = ""\n for character in text:\n new_position = ord(character) - rem\n if new_position < 97:\n diff = 97 - new_position\n new_position = 122 - diff\n decoded_text += chr(new_position)\n return decoded_text\n</code></pre>\n<p>And you call them up in main function like this:</p>\n<pre><code>if __name__ == '__main__':\n\n rem = (rotations % 26)\n ROTATIONS = random.randint(3, 26)\n ENCODED = encode(random.choice(WORDS), ROTATIONS, rem)\n DECODED = decode(ENCODED, ROTATIONS, rem)\n</code></pre>\n<p>Happy Coding :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T21:37:45.773",
"Id": "225219",
"ParentId": "224730",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224775",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T13:07:54.447",
"Id": "224730",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"caesar-cipher"
],
"Title": "Caesar Cipher Guesser"
}
|
224730
|
<p>The prime 41, can be written as the sum of six consecutive primes:</p>
<p>41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.</p>
<p>The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.</p>
<p>Which prime, below one-million, can be written as the sum of the most consecutive primes?</p>
<pre><code>from time import time
def is_prime(n):
"""returns True for a prime number, False otherwise."""
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def sieve(n):
"""generates primes in range n."""
initial = [True] * n
initial[0] = initial[1] = False
for (i, prime) in enumerate(initial):
if prime:
yield i
for index in range(i * i, n, i):
initial[index] = False
def make_prime_partitions(min_size):
"""Assumes minsize an integer, initializes a prime sequence of length min_size."""
primes = sieve(1000000)
prime_sequence = [next(primes) for _ in range(min_size)]
start_point = 0
while start_point < len(prime_sequence):
for i in range(start_point, min_size):
yield prime_sequence[start_point: i + 1]
start_point += 1
def check_partitions(min_size=1000, max_total=1000000):
"""Assumes min_size is the minimum size of the initial prime sequence to generate
and max total is the maximum total of consecutive prime sequences generated.
generates sequences that sum up to less than max total."""
prime_partitions = make_prime_partitions(min_size)
for sequence in prime_partitions:
if len(sequence) > min_size // 2:
total = sum(sequence)
if is_prime(total) and total <= max_total:
yield sequence
if __name__ == '__main__':
start_time = time()
all_sequences = check_partitions()
longest_sequence = max(all_sequences, key=len)
print(f'Maximum length: {len(longest_sequence)}')
print(f'Maximum sum: {sum(longest_sequence)}')
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T15:30:00.657",
"Id": "435984",
"Score": "6",
"body": "We have established that you can brute force your way through programming challenges. When you implement a next algorithm, do you take into account the feedback you've gotten on previous and very similar questions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T15:31:50.240",
"Id": "435985",
"Score": "0",
"body": "what do you think?"
}
] |
[
{
"body": "<h2>Meta Information</h2>\n\n<p>I'm glad to see you are now tagging your questions with all of the appropriate tags. Well done.</p>\n\n<h2>Project Euler</h2>\n\n<p>Project Euler is a series of challenging mathematical/computer programming problems. Since all problems should be solvable in less than 60 seconds on a computer, efficiency is important when attempting to solve problems. This can often mean sacrificing proper code structuring in an effort to eek out every last cycle of computing speed.</p>\n\n<p>While programming exercises are essential in learning how to program, or learning how to program in a new language, the Project Euler problems are not designed to target learning aspects of any given language. They are problem solving exercises designed to tax the limits of computers if solved via naive methods. The solution isn't to write a program; it is to write a smart program. If you are trying to learn how to program, perhaps Project Euler is not the problem set you should be tackling.</p>\n\n<p>This Stack Exchange is dedicated to Reviewing Code, in order to increase the quality of written code. It is not intended as a evaluation forum for Project Euler solutions. We are not grading your solutions. More over, Project Euler asks that you not post solutions to problems in other online forums in order to allow others the euphoric experience of solving the problems themselves. If you do post your code here for review, you should first review it yourself looking for good variable names, understandable comments, no unused variables or functions, etc. You shouldn't post a hacky \"it works, please make it pretty\" solution; you should be proud of code you submit to Code Review before you submit it. Then the members here will feel more inclined to help you polish the code.</p>\n\n<h2>Yield</h2>\n\n<p>The <code>yield</code> statement is powerful, but comes with several costs. The generator function requires its own call stack. The interpreter must keep switching back and forth between the tasks, which takes time, evicts memory out of cache, so takes even more time. The <code>yield</code> statement slows down code.</p>\n\n<p>If you can write the code without the <code>yield</code>, your code will be faster. It will be more understandable, too, because functions run to completion. There are uses for <code>yield</code>, and there are times when you trying to avoid <code>yield</code> is more work than its worth. This isn't it.</p>\n\n<h2>Doc-Strings</h2>\n\n<p>Doc-strings are designed to be extracted by various tools and turned into help documentation for other users to read in order to understand what the function does, and what it requires. In a Python shell, try out <code>help(make_prime_partitions)</code>. Does the description make sense? It says it \"initializes\" something. But the function actually is a generator, and it returns stuff. A bit of a disconnect, and less than helpful.</p>\n\n<p>Then there is this function:</p>\n\n<pre><code>def check_partitions(min_size=1000, max_total=1000000):\n \"\"\"Assumes min_size is the minimum size of the initial prime sequence to generate\n and max total is the maximum total of consecutive prime sequences generated.\n generates sequences that sum up to less than max total.\"\"\"\n prime_partitions = make_prime_partitions(min_size)\n for sequence in prime_partitions:\n if len(sequence) > min_size // 2:\n # ...\n</code></pre>\n\n<p>This looks like a wall of text. My aging eyes can't see where the doc-string ends and the code begins. Putting the <code>\"\"\"</code> delimiters on their own line, and add a blank line after the doc-string goes a long way towards improving readability.</p>\n\n<pre><code>def check_partitions(min_size=1000, max_total=1000000):\n \"\"\"\n Assumes min_size is the minimum size of the initial prime sequence to generate\n and max total is the maximum total of consecutive prime sequences generated.\n generates sequences that sum up to less than max total.\n \"\"\"\n\n prime_partitions = make_prime_partitions(min_size)\n for sequence in prime_partitions:\n if len(sequence) > min_size // 2:\n # ...\n</code></pre>\n\n<h2>Magic Numbers</h2>\n\n<p>Where did these numbers come from?</p>\n\n<pre><code>def check_partitions(min_size=1000, max_total=1000000):\n</code></pre>\n\n<p>The <code>1000000</code> is for problem you are trying to solve. It should not be a default argument. The caller, who wants to solve PE50 should pass in the desired limit.</p>\n\n<p>What is the <code>1000</code>? Is it the square-root of <code>max_total</code>? Where did it come from and what does it mean? Is it a \"minimum size\"? It seems to be the maximum length of the sequence of prime numbers you generate ... not a minimum of anything!</p>\n\n<pre><code>primes = sieve(1000000)\n</code></pre>\n\n<p>Why is <code>1000000</code> hard-coded in the <code>make_prime_partitions</code> function? Is this not the same as <code>max_total</code>? Perhaps it should be passed as an argument into the function??</p>\n\n<h2>Testing</h2>\n\n<p>When I am trying to solve a Project Euler problem, I write my main code like:</p>\n\n<pre><code>if __name__ == '__main__':\n pe50_solve(100)\n pe50_solve(1_000)\n pe50_solve(1_000_000)\n</code></pre>\n\n<p>And I expect to get the output showing that 41 is the sum of 6 consecutive primes (from 2 to 13) under 100, that 953 is the sum of 21 consecutive primes (and what the start/end primes are) under 1000, and the actual desired answer to the problem.</p>\n\n<ol>\n<li>This gives me confidence in my solution. It works for the two examples given in the problem text.</li>\n<li>It requires a reasonable interface for solving the problem. No extra magic numbers are being passed in.</li>\n</ol>\n\n<h2>Assumptions</h2>\n\n<p>You can speed up your code by making assumptions about the answer. For this question, you've are generating 1000 primes, assuming the answer will use primes in that range.</p>\n\n<p>Is it reasonable?</p>\n\n<p>Below 1000, longest sequence was 21 terms. So below 1 million, the longest sequence will be at least 21 terms. Since these primes are sequential, they will all be fairly close together, so we can reason about them. They would fall around an average. What would the largest possible average be? 1000000 / 21 = 41619.04... so perhaps stopping the prime generation at 50000 would be a reasonable limit? The longer the sequence, the smaller the average, and the lower the limit would become, but how can you come up with an upper limit for the longest sequence?</p>\n\n<p>What is this <code>len(sequence) > min_size // 2</code>? Oh sure, it speeds up your code. But why? Because you know the answer's sequence length is between 500 and 1000? What if the question is changed to a limit of 750 thousand? 2 million? 2.5 million? 10 million? Is it still valid? You only know it is valid for the 1 million case because you've already run it the slow way, and found the answer. But it isn't justifiable.</p>\n\n<h2><code>is_prime</code></h2>\n\n<p>In this function, you are going through successive numbers up to <span class=\"math-container\">\\$\\sqrt n\\$</span> looking for any number that evenly divides n. This is an <span class=\"math-container\">\\$O(\\sqrt n)\\$</span> operation. If only you could weed out some of the divided you don't need to check. You skip the even numbers by counting by 2's, but you don't skip <code>9</code>, or <code>15</code>, or <code>21</code>, or <code>25</code>. If only you generated some prime numbers you could use as a list of possible divider, you could reduce this to <span class=\"math-container\">\\$O(\\frac{\\sqrt n}{\\log \\sqrt n})\\$</span>. Oh wait, you have generated a list of prime numbers ... why aren't you using it?</p>\n\n<p>Better yet, the <code>sieve()</code> produces an array of boolean flags in the <code>initial</code> list, and <code>initial[x]</code> is <code>True</code> if <code>x</code> is prime. You could make the <code>is_prime(x)</code> function <span class=\"math-container\">\\$O(1)\\$</span>. But, you'd have to expose <code>initial</code> to the outside world, instead of it being an internal workspace. And no I don't recommend using <code>global initial</code>; there is a better way. You could simply <code>return initial</code> from your sieve. But then it can't be a generator, but I advocated getting rid of the <code>yield</code> above anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T23:24:32.510",
"Id": "224934",
"ParentId": "224731",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224934",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T13:30:09.600",
"Id": "224731",
"Score": "-2",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 50 Consecutive prime sum in Python"
}
|
224731
|
<p>Could someone share some light and check if this is okay for apache httpd security/good standards? I'm using apache httpd to call my Node.js app that is running with Express and also configuring SSL.</p>
<p>apache2.conf:</p>
<pre><code>DefaultRuntimeDir ${APACHE_RUN_DIR}
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
Include ports.conf
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
IncludeOptional sites-enabled/*.conf
Protocols h2 http/1.1
KeepAlive Off
<IfModule mpm_prefork_module>
StartServers 4
MinSpareServers 20
MaxSpareServers 40
MaxClients 200
MaxRequestsPerChild 4500
</IfModule>
ServerTokens Prod
ServerSignature Off
FileETag None
TraceEnable off
</code></pre>
<p>site-name.conf:</p>
<pre><code><VirtualHost *:80>
ServerName www.site-name.com
ProxyRequests Off
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Redirect permanent / https://site-name.com
</VirtualHost>
</code></pre>
<p>site-name-ssl.conf:</p>
<pre><code><IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerName site-name.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
ProxyRequests Off
SSLCertificateFile /etc/letsencrypt/live/site-name.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/site-name.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
ProxyPass /api http://site-name.com:3000/api
ProxyPassReverse /api http://site-name.com:3000/api
ProxyPass / http://site-name.com:4226/
ProxyPassReverse / http://site-name.com:4226/
</VirtualHost>
</IfModule>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T13:53:36.580",
"Id": "224732",
"Score": "2",
"Tags": [
"linux",
"http",
"server",
".htaccess",
"ssl"
],
"Title": "Apache reverse proxy security configuration"
}
|
224732
|
<p>This works but it doesn't really seem ideal. Is there a better way to write this using react-router? Initialization and pagination are just React containers holding logic. <code>DisplaySaves</code> is a component that renders some stuff to the screen.</p>
<pre><code><div>
<BrowserRouter>
<Route path="/authorize_callback" exact component={Initialization} />
<Route path="/authorize_callback" exact component={Pagination} />
<Route path="/authorize_callback" exact component={DisplaySaves} />
</BrowserRouter>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:37:17.627",
"Id": "435978",
"Score": "2",
"body": "Could you add more code, for instance .. the components?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T09:53:12.977",
"Id": "437498",
"Score": "0",
"body": "Do they need to be rendered in all routes? If so, you can put them in a higher level outside the Router. And them you Route only what needs to change."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T14:36:30.793",
"Id": "224737",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"redux"
],
"Title": "React-Router, render multiple components"
}
|
224737
|
<p>I have a <code>mutableListOf</code> a sealed class.
I am trying to compare the result coming from the api with the ones saved in the db so I can update my UI base on <code>isSaved</code> attribute. Here is my code :</p>
<pre><code>sealed class MasterList(val type: Type) {
data class FavoriteList(
val list: List<Info>
): MasterList(Type.FAVORITE)
data class Child1List(
val title: String,
val list: List<Info1>
) : MasterList(Type.CHILD_1)
data class Child2List(
val title: String,
val list: List<Info2>
) : MasterList(Type.CHILD_2)
}
data class Info(
val fname: String,
val lname: String,
val age: String,
val address: String
)
data class Info1(
val fname: String,
val lname: String,
val isSaved: Boolean
)
data class Info2(
val age: String,
val address: String,
val isSaved: Boolean
)
enum class Type {
FAVORITE,
CHILD_1,
CHILD_2
}
fun loadInfo(): List<MasterList>? {
val resultList = mutableListOf<MasterList>()
val savedResult = MasterList.FavoriteList(localStroage.getAllFavorite())
val feedResult = api.fetchAllInfo()
return if (feedResult == null)
null
else {
resultList.add(0, savedResult)
resultList.addAll(feedResult)
markSavedInfo(feedResult,savedResult.list)
// I need to compare my savedResult with feedResult to put isSaved to true if it exist
return resultList
}
}
private fun markSavedInfo(feedResult: List<MasterList>, favoriteList: List<Info>) {
feedResult.forEach {
when (it.type) {
Type.CHILD_1 -> {
(it as MasterList.Child1List).list.forEach {
val name = it.fname
for (saved in favoriteList) {
if (name == saved.fname)
println("Result $name")
}
}
}
Type.CHILD_2 -> {
(it as MasterList.Child2List).list.forEach {
val age = it.age
for (saved in favoriteList) {
if (age == saved.age)
println("xxx: Result $age")
}
}
}
}
}
}
</code></pre>
<p>this is the best I could do , it's <code>markSavedInfo</code> function but I don't think it's the best solution !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T10:11:47.930",
"Id": "437125",
"Score": "2",
"body": "What exactly should the function `markSavedInfo` do? And why are you posting \"mocked\" code here. If you want review than post your real code. If it's real code then it's not bad but naming is terrible. What is Child, Child1, Info1, fname, lname etc.?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T15:45:13.887",
"Id": "224738",
"Score": "1",
"Tags": [
"kotlin"
],
"Title": "Match favorite data from db with data coming from api"
}
|
224738
|
<p>Just starting out trying to do some python for data analysis. I am a total beginner and have figure out how to brute force somethings, but I know it is inefficient but don't know how to do it without messing up what i have.</p>
<p>I have multiple webpages to scrape and then store data in a data frame. The code is identical for all of the pages. How do I set it up as a routine instead just repeating the same code over and over again.</p>
<p>As an example the two urls are: <a href="https://etfdb.com/etf/IWD/" rel="nofollow noreferrer">https://etfdb.com/etf/IWD/</a> <a href="https://etfdb.com/etf/IWF/" rel="nofollow noreferrer">https://etfdb.com/etf/IWF/</a></p>
<p>The html is identical so the web scraping working exactly the same for both.</p>
<p>Once scraped, I want them in a single data frame.</p>
<p>The below works, but is me taking the least sophisticated approach since I know so little. The actual code is likely not pretty but it works.</p>
<p>Any help appreciated on how this should be improved.</p>
<pre><code>import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import pandas as pd
import numpy as np
from IPython.display import display
iwd_url = 'https://etfdb.com/etf/IWD/'
uClient = uReq(iwd_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
#Isolate header to get name and symbol
h1 = page_soup.h1
#Isolate stock symbol
title = h1.findAll("span",{"class":"label-primary"})
titlet = title[0].text
#print(titlet)
#strip space and line break
strip1 = h1.text.strip()
#strip stock symbol
strip2 = strip1.strip(titlet)
#strip remaining line break
strip3 = strip2.strip()
#print(strip3)
IWD = page_soup.findAll("table",{"class":"chart base-table"})[1]
#Create lists to fill
sectordata=[]
sectorname=[]
sectorweight=[]
for row in IWD.findAll("td"):
sectordata.append(row.text)
#list created
#Assign every other value to proper list to get 2 columns
sectorname = sectordata[::2]
sectorweight = sectordata[1::2]
#Insert name/symbol for clarification/validation
sectorweight.insert(0,titlet)
sectorname.insert(0,strip3)
# create empty data frame in pandas
df = pd.DataFrame()
#Add the first column to the empty dataframe.
df['Sector'] = sectorname
#Now add the second column.
df['Weight'] = sectorweight
##display(df)
### NEXT
iwf_url = 'https://etfdb.com/etf/IWF/'
uClient = uReq(iwf_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
#Isolate header to get name and symbol
h1 = page_soup.h1
#Isolate stock symbol
title = h1.findAll("span",{"class":"label-primary"})
titlet = title[0].text
#print(titlet)
#strip space and line break
strip1 = h1.text.strip()
#strip stock symbol
strip2 = strip1.strip(titlet)
#strip remaining line break
strip3 = strip2.strip()
#print(strip3)
IWD = page_soup.findAll("table",{"class":"chart base-table"})[1]
#Create lists to fill
sectordata=[]
sectorname=[]
sectorweight=[]
for row in IWD.findAll("td"):
sectordata.append(row.text)
#list created
#Assign every other value to proper list to get 2 columns
sectorname = sectordata[::2]
sectorweight = sectordata[1::2]
#Insert name/symbol for clarification/validation
sectorweight.insert(0,titlet)
sectorname.insert(0,strip3)
# create empty data frame in pandas
df2 = pd.DataFrame()
#Add the first column to the empty dataframe.
df2['Sector'] = sectorname
#Now add the second column.
df2['Weight'] = sectorweight
#display(df2)
results = df.merge(df2, on = "Sector")
results.columns = ['Sector', 'IWD', 'IWF']
display(results)
</code></pre>
<p>Like I said, this works, but it isn't automated and its ham-handed way of getting there. Please help me to get better!</p>
|
[] |
[
{
"body": "<p>I created function <code>get_soup</code> because this code is offen used many times in code. In this code I could put all in <code>get_data</code>.</p>\n\n<p><code>get_data</code> gets <code>url</code> and uses <code>get_soup</code> with this <code>url</code>. Later it scrapes data from html, creates DataFrame and returns it</p>\n\n<p>Main part uses <code>get_data</code> with two urls and gets two dataframes.</p>\n\n<p>I put some other comments in code.</p>\n\n<pre><code># <-- remove not used modules\n# <-- use more popular names \nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup as BS\nimport pandas as pd\nfrom IPython.display import display\n\n# --- functions ---\n# <-- all functions before main part\n\ndef get_soup(url):\n # <-- more readable names (and more popular)\n response = urlopen(url)\n html = response.read()\n response.close()\n soup = BS(html, \"html.parser\")\n return soup\n\n\ndef get_data(url):\n\n soup = get_soup(url)\n\n #Isolate header to get name and symbol\n h1 = soup.h1\n\n #Isolate stock symbol\n # <-- find() to get only first item\n title = h1.find(\"span\",{\"class\":\"label-primary\"}).text\n\n #print(title)\n\n #strip space and line break\n # <-- use the same variable instead strip,strip2, strip3\n # <-- maybe too much comments \n header = h1.text.strip()\n\n #strip stock symbol\n header = header.strip(title)\n\n #strip remaining line break\n header = header.strip()\n\n #print(strip)\n\n # <-- use better name 'table'\n table = soup.find_all(\"table\",{\"class\":\"chart base-table\"})[1]\n\n #Create lists to fill\n #sector_data = [row.text for row in table.find_all(\"td\")]\n sector_data = []\n # <-- remove lists which will be created later\n\n for row in table.find_all(\"td\"):\n sector_data.append(row.text)\n\n #Assign every other value to proper list to get 2 columns\n sector_name = sector_data[::2]\n sector_weight = sector_data[1::2]\n\n #Insert name/symbol for clarification/validation\n sector_weight.insert(0, title)\n sector_name.insert(0, header)\n\n # create dataframe in pandas\n # <-- create DF directly with data\n df = pd.DataFrame({\n 'Sector': sector_name,\n 'Weight': sector_weight,\n })\n\n #display(df)\n\n return df\n\n# --- main ---\n\n# <-- the same variable `url` because it keep the same type of data\n# and I will no need this value later - so I can resuse this name.\nurl = 'https://etfdb.com/etf/IWD/'\ndf1 = get_data(url)\n\nurl = 'https://etfdb.com/etf/IWF/'\ndf2 = get_data(url)\n\nresults = df1.merge(df2, on=\"Sector\")\nresults.columns = ['Sector', 'IWD', 'IWF']\ndisplay(results)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:14:04.233",
"Id": "224769",
"ParentId": "224740",
"Score": "1"
}
},
{
"body": "<p>Pandas <a href=\"https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.read_html.html\" rel=\"nofollow noreferrer\"><code>read_html</code></a> allows to</p>\n\n<blockquote>\n <p>Read HTML tables into a list of DataFrame objects.</p>\n</blockquote>\n\n<p>Using this we can store the urls in a list.</p>\n\n<pre><code>l=['https://etfdb.com/etf/IWD/','https://etfdb.com/etf/IWF/']\n</code></pre>\n\n<p>Then we read the urls and store them in a list:</p>\n\n<pre><code>dfs=[pd.read_html(i)[5].rename(columns={'Percentage':i.split('/')[-2]}) for i in l] \n</code></pre>\n\n<hr>\n\n<p>Once we have this list of dataframes, we can use a reduce merge to merge all the dataframes in the list:</p>\n\n<pre><code>from functools import reduce\ndf_final = reduce(lambda left,right: pd.merge(left,right,on='Sector'), dfs)\nprint(df_final)\n</code></pre>\n\n<hr>\n\n<p><strong><em>Output</em></strong></p>\n\n<pre><code> Sector IWD IWF\n0 Financials 23.02% 3.21%\n1 Healthcare 12.08% 14.04%\n2 Industrials 9.27% 9.39%\n3 Energy 8.98% 0.35%\n4 Consumer, Non-Cyclical 8.85% 4.69%\n5 Communications 7.7% 11.27%\n6 Technology 6.13% 36.46%\n7 Consumer, Cyclical 5.86% 14.24%\n8 Real Estate 5.15% 2.31%\n9 Other 3.54% 2.55%\n10 Basic Materials 2.74% 1.34%\n11 ETF Cash Component 0.33% 0.14%\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T05:34:57.500",
"Id": "224782",
"ParentId": "224740",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T16:14:16.027",
"Id": "224740",
"Score": "4",
"Tags": [
"python",
"beginner",
"web-scraping",
"pandas",
"beautifulsoup"
],
"Title": "Web-scraping investment fund data into Pandas"
}
|
224740
|
<p>I've written below python script just to invoke parallel threads of a command <code>nslookup linux-host01 dns-server</code>, i'm Just trying to flood the DNS Server <code>dns-server</code> with multiple number of queries in parallel way.</p>
<p>As an argument to this script i'm passing a <code>hostlist</code> file example <code>linux-host01</code> , <code>linux-host02</code> etc.</p>
<p>To achieve this i'm using <code>threading</code> module with the below code and this works fine, However, i'm using the the threading first time hence would like to know if this can be simplified of enhanced further.</p>
<pre><code>import os
import threading
from sys import argv, exit
lock = threading.Lock()
hostfile = argv[1]
lst = []
with open(hostfile, 'r') as frb:
for line in frb:
lst.append(line.strip("\n"))
threads = []
thread_count = len(lst)
def pop_queue():
host = None
lock.acquire()
if lst:
host = lst.pop()
lock.release()
return host
def dequeue():
while len(lst) != 0:
host = pop_queue()
if not host:
return None
else:
dolookup(host)
def dolookup(name):
while True:
os.system("/usr/bin/nslookup %s dns-test01" %name)
for i in range(thread_count):
t = threading.Thread(target=dequeue)
t.start()
print "started thread %s" %i
threads.append(t)
[t.join() for t in threads]
</code></pre>
<p>Appreciate any help on this.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T08:06:34.463",
"Id": "436099",
"Score": "0",
"body": "python has [GIL (Global Interpreter Lock)](https://wiki.python.org/moin/GlobalInterpreterLock) so threads don't run in parallel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T21:35:20.123",
"Id": "475752",
"Score": "2",
"body": "Another issue is that `os.system()` is quite an inefficient way to do a hostname lookup; it starts a new shell process, and that shell starts the `nslookup` binary. Try to use [`socket.getaddrinfo()`](https://docs.python.org/3/library/socket.html#socket.getaddrinfo) instead."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T16:18:23.053",
"Id": "224741",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"multithreading"
],
"Title": "Invoking parallel threads of a nslookup command in python"
}
|
224741
|
<p>Can anybody find anything to pick apart in this script?</p>
<pre class="lang-py prettyprint-override"><code># Copyright (c) 2019. Legorooj
import sys
import os
docstring = '''
add_alias [alias] [command]'''
if len(sys.argv) <= 1:
print(docstring)
else:
alias, cmd = sys.argv[1], sys.argv[2]
print('Adding alias...')
os.system(f'echo "alias {alias}={cmd}" >> ~/.bashrc && source ~/.bashrc')
print('Alias added')
</code></pre>
<p>If ran like:</p>
<p><code>add_alias bob "echo bob"</code>, it adds an alias as if you ran </p>
<p><code>echo "alias bob="echo bob"" >> ~/.bashrc && source ~/.bashrc</code></p>
|
[] |
[
{
"body": "<p>We need to do some basic sanity checking of the inputs - alias names can't contain whitespace, for example, and any newlines in the expansion will be treated as the end of the alias definition (and the following text will then be a new command in your <code>.bashrc</code>).</p>\n\n<p>The <code>source ~/.bashrc</code> in the call to <code>os.system()</code> looks pointless, as that shell terminates immediately after.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T16:40:46.653",
"Id": "224744",
"ParentId": "224742",
"Score": "4"
}
},
{
"body": "<p>The script is missing a shebang. (For example <code>#!/usr/bin/env python</code>)</p>\n\n<p>The length check <code>len(sys.argv) <= 1</code> is not enough, <code>sys.argv[2]</code> will crash with <code>IndexError</code> when there is only one script argument instead of two. (You probably meant to write <code>len(sys.argv) <= 2</code>)</p>\n\n<p>I don't think this script has enough value over adding aliases manually.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T05:44:35.367",
"Id": "224859",
"ParentId": "224742",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T16:18:38.927",
"Id": "224742",
"Score": "3",
"Tags": [
"python",
"bash",
"configuration"
],
"Title": "Script to create shell aliases"
}
|
224742
|
<p>I often find in codebases something on the order of <code>if (sprockets.Count() > 0)</code> which is easily replaced with LINQ's <code>if (sprockets.Any())</code>. This keeps the entirety of <code>sprockets</code> from having to be iterated over completely (to get the count) then comparing to zero. Further, the business logic often reads something like "if there are any sprockets, inform the user of the subtotal". I <em>also</em> often see similar logic for exactly one of something: <code>if (sprockets.Count() == 1)</code> which doesn't have an easy, low-cost LINQ alternative. So I've created one here:</p>
<pre><code>public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
return enumerator.MoveNext() && !enumerator.MoveNext();
}
}
</code></pre>
<p>Usage is <code>if (sprockets.ExactlyOne())</code> Here are unit tests. There is one helper method called <code>Infinite()</code> which is a never-ending enumerable, which will baffle <code>sprockets.Count()</code>, but not <code>sprockets.ExactlyOne()</code>:</p>
<pre><code>[TestClass]
public sealed class ExactlyOneTests
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestNull()
{
int[] nullArray = null;
Assert.IsFalse(nullArray.ExactlyOne());
}
[TestMethod]
public void TestZero()
{
int[] zero = Array.Empty<int>();
Assert.IsFalse(zero.ExactlyOne());
}
[TestMethod]
public void TestOne()
{
int[] one = { 1 };
Assert.IsTrue(one.ExactlyOne());
}
[TestMethod]
public void TestTwo()
{
int[] two = { 1, 2 };
Assert.IsFalse(two.ExactlyOne());
}
[TestMethod]
public void TestInfinite()
{
IEnumerable<int> infinite = Infinite();
Assert.IsFalse(infinite.ExactlyOne());
}
private static IEnumerable<int> Infinite()
{
while (true)
{
yield return 0;
}
}
}
</code></pre>
<p>Looking for overall review - is the code readable, maintainable, performant. Do the tests cover the expected cases or are there more to consider?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T05:55:54.567",
"Id": "436066",
"Score": "2",
"body": "This discards the element. Have you considered designs that preserve the element, but also tell you if it's the only one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T11:02:25.150",
"Id": "436123",
"Score": "5",
"body": "Wouldn't it be better to use `SingleOrDefault()` in such cases? Or `Single()` if there has to be a value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:42:21.737",
"Id": "436149",
"Score": "2",
"body": "@BCdotWEB SingleOrDefault() throws an exception if there are multiple elements that fulfill the same criteria."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:46:02.720",
"Id": "436154",
"Score": "1",
"body": "@MY_G True, but that's what you want IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:17:13.920",
"Id": "436160",
"Score": "0",
"body": "@BCdotWEB @Alexander: if you want the value, use `.First()` instead of `.Any()`. `.Single()` is analagous to `.ExactlyOne()` in that respect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:36:53.390",
"Id": "436166",
"Score": "4",
"body": "Just as a reference F# has an implementation of `ExactlyOne` and it's pretty much what you have: https://github.com/fsharp/fsharp/blob/6819e1c769269edefcea2263c98f993e90b623e2/src/fsharp/FSharp.Core/seq.fs#L1412"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:39:45.720",
"Id": "436168",
"Score": "1",
"body": "@Ringil neat! Thanks for pointing that out. Brings me back to my Haskell days in college."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T19:28:52.153",
"Id": "436228",
"Score": "1",
"body": "@BCdotWEB Another option is to create a method _bool TryGetSingle<T>(out T value)_ conform naming and signature conventions of .NET Framework."
}
] |
[
{
"body": "<h2>Q&A</h2>\n\n<blockquote>\n <p>Is the code readable?</p>\n</blockquote>\n\n<ul>\n<li><code>ExactlyOne</code> states very clearly what the method is supposed to do.</li>\n<li><code>source is null</code> seems odd to me (does that even compile?). I'd prefer <code>source == null</code>. (Edit from comments: a topic about <a href=\"https://www.gullberg.tk/blog/is-null-versus-null-in-c/\" rel=\"nofollow noreferrer\">is null vs == null</a>)</li>\n<li><code>IEnumerator<TSource> enumerator = source.GetEnumerator()</code> can be written as <code>var enumerator = source.GetEnumerator()</code>.</li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>Is the code maintainable?</p>\n</blockquote>\n\n<ul>\n<li>Since you are looking for a sibling function of <code>Any<T>()</code>, I would also include a <code>ExactlyOne<T>(Func<T, bool> predicate)</code>.</li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>Is the code performant?</p>\n</blockquote>\n\n<ul>\n<li>It does seem so, right? But notice that LINQ is optimized for <code>IEnumerable<T></code> that is also <code>ICollection<T></code>, in which case <code>Count</code> is used. Implementations should have an eager implementation of this property. Your method <em>could</em> also use this optimization <code>Count == 1</code>. </li>\n<li>I actually noticed (in my eyes) unexpected behavior in LINQ: <code>Count<T>()</code> is optimized for <code>ICollection<T></code> but <code>Any<T()</code> is not. This means you arguably could make a slightly faster implementation than LINQ. </li>\n<li>An in-depth comparison is required to find the most optimized approach. As discussed in the comments, testing the different implementations against a variety of input sources should yield us which method perfoms best under which conditions.</li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>Do the tests cover the expected cases or are there more to consider?</p>\n</blockquote>\n\n<p>You cover <code>null</code>, empty, 1, multiple, early exit on infinite.. but perhaps also test on <code>ICollection<T></code> and custom <code>IEnumerable<T></code> implementations with eager and/or lazy loading.</p>\n\n<hr>\n\n<h2>Reference Source: <a href=\"https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs\" rel=\"nofollow noreferrer\">LINQ Any vs Count</a></h2>\n\n<pre><code>// not optimized for ICollection<T> (why ??)\npublic static bool Any<TSource>(this IEnumerable<TSource> source) {\n if (source == null) throw Error.ArgumentNull(\"source\");\n using (IEnumerator<TSource> e = source.GetEnumerator()) {\n if (e.MoveNext()) return true;\n }\n return false;\n}\n\npublic static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {\n if (source == null) throw Error.ArgumentNull(\"source\");\n if (predicate == null) throw Error.ArgumentNull(\"predicate\");\n foreach (TSource element in source) {\n if (predicate(element)) return true;\n }\n return false;\n}\n\n// optimized for ICollection<T>\npublic static int Count<TSource>(this IEnumerable<TSource> source) {\n if (source == null) throw Error.ArgumentNull(\"source\");\n ICollection<TSource> collectionoft = source as ICollection<TSource>;\n if (collectionoft != null) return collectionoft.Count;\n ICollection collection = source as ICollection;\n if (collection != null) return collection.Count;\n int count = 0;\n using (IEnumerator<TSource> e = source.GetEnumerator()) {\n checked {\n while (e.MoveNext()) count++;\n }\n }\n return count;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:02:16.497",
"Id": "436003",
"Score": "0",
"body": "Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementing `ExactlyOne<T>(Func<T, bool> predicate)` from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical to `Count<T>(Func<T, bool> predicate) == 1`. I suppose it would be orthogonal to implement it as that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:03:50.540",
"Id": "436004",
"Score": "1",
"body": "Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:06:50.247",
"Id": "436006",
"Score": "0",
"body": "You're right. I can optimize. I'm going to add an answer just for reference's sake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:13:29.277",
"Id": "436008",
"Score": "2",
"body": "`source is null` - I read about that as well as `source is object` (sorta like `source != null`) on some twitter feed from a noted developer, but the gist of it can be found here: https://www.gullberg.tk/blog/is-null-versus-null-in-c/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:15:09.987",
"Id": "436009",
"Score": "4",
"body": "so _is null_ means _ReferenceEquals(null, source)_ then? I did not know this one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:17:31.340",
"Id": "436010",
"Score": "1",
"body": "And I just added your suggested `ICollection` optimization using C#7 pattern matching: `if (source is ICollection<TSource> collection) return collection.Count == 1;` before the `using`. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T05:55:56.533",
"Id": "436067",
"Score": "0",
"body": "@JesseC.Slicer using Count for ICollection is a pessimization, and you'd better remove it. While Collections, as opposed to general Enumerables, HAVE a specific count of elements, finding it is NOT guaranteed to be a cheap O(1) operation. In most cases it is, and whenever possible it should be, but there's no guarantee, and in some lazy-loading cases there's no practical possibility. BTW this explains a lack of special case for Any() inside LINQ: while Count() can safely assume that the Count property is at least not slower than naive iteration, Any() can't assume that Count is fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T06:11:35.783",
"Id": "436069",
"Score": "1",
"body": "@JesseC.Slicer take a look at LINQ reference code: a few extension methods, like Single(), have a special case for IList, but not for ICollection. Apparently, Lists are at least expected to have fast access time and count.\nhttps://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T06:59:16.883",
"Id": "436076",
"Score": "1",
"body": "@IMil It's interesting to see which LINQ methods optimize for which types of collections. I would have hoped to find a great article about it by some microsoft guru."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:57:09.387",
"Id": "436179",
"Score": "0",
"body": "@IMil after benchmarking with and without the \"pessimization\" (I like this neologism), the without version performs better, in even the simple cases where `ICollection` is backed by an array or list. So, nuked it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:02:08.687",
"Id": "436180",
"Score": "0",
"body": "@IMil Jesse, should I include your test results in my answer to provide insights why Any isn't 'pessimized' while Count is optimized?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:33:45.843",
"Id": "436185",
"Score": "0",
"body": "@dfhwze So, using BenchmarkDotNet, version with `ICollection` check gives 7.823us, version without gives **7.725us**, and t3chb0t version gives 7.927us."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:40:26.213",
"Id": "436187",
"Score": "0",
"body": "@JesseC.Slicer Perhaps it's even better if you would make another self answer with comparison of each the provided methods on a variety of input sources (array, list, custom enumerable that yields results, custom enumerable that knows the Count, but uses lazy enumeration, ..)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T00:45:00.443",
"Id": "436264",
"Score": "0",
"body": "@JesseC.Slicer my point is not that a special case for ICollection WILL be slower, but that it MAY be slower for certain implementations of ICollection. If this is your code, and you know which exact concrete classes your projects are likely to use, then it's fine. But LINQ definitely couldn't use this \"optimization\", because the extension methods work on any user-defined collections, and there's no guarantee that Count works faster than a couple iterator manipulations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T01:02:21.847",
"Id": "436266",
"Score": "0",
"body": "@JesseC.Slicer also it's conceivable that Count is a bit faster, but an extra cast eats all the savings. Anyway, +- 0.1 microsecond is probably just noise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T06:12:17.993",
"Id": "436281",
"Score": "1",
"body": "I love the answer but i would say the null check is entirely superfluous because as soon the code reaches source.GetEnumerator() the exact same exception is thrown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T06:51:07.850",
"Id": "436284",
"Score": "1",
"body": "@dfhwze [This blog comes close](https://codeblog.jonskeet.uk/category/edulinq/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T06:52:51.497",
"Id": "436285",
"Score": "2",
"body": "@Robert the null check is consistent with the API of Linq. Fail early is never a bad thing."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T19:57:55.760",
"Id": "224754",
"ParentId": "224752",
"Score": "15"
}
},
{
"body": "<p>This is for <a href=\"https://codereview.stackexchange.com/users/200620/dfhwze\">dfhwze</a> as per comment:</p>\n\n<pre><code>public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)\n{\n if (source is null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n if (predicate is null)\n {\n throw new ArgumentNullException(nameof(predicate));\n }\n\n bool gotOne = false;\n\n foreach (TSource element in source)\n {\n if (!predicate(element))\n {\n continue;\n }\n\n if (gotOne)\n {\n return false;\n }\n\n gotOne = true;\n }\n\n return gotOne;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:09:33.813",
"Id": "436007",
"Score": "1",
"body": "Seems as optimized as I can think of. Early exit is the best you can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T05:22:04.057",
"Id": "436063",
"Score": "1",
"body": "The predicate should be allowed to not be provided though, no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:20:43.270",
"Id": "436161",
"Score": "1",
"body": "@MathieuGuindon that version is what the original question has. Use them both together."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:07:52.493",
"Id": "224755",
"ParentId": "224752",
"Score": "11"
}
},
{
"body": "<p>mhmmm... I'm not so sure about this implementation. @dfhwze's points are valid but still, I find it's overengineered.</p>\n\n<p>I prefer chaining these two alraedy available extensions that can do all mentioned <em>tricks</em>:</p>\n\n<pre><code>return source.Take(2).Count() == 1\n</code></pre>\n\n<p>or with a predicate</p>\n\n<pre><code>return source.Where(predicate).Take(2).Count() == 1;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:15:59.543",
"Id": "436082",
"Score": "1",
"body": "Interesting alternative way of looking at the problem. You got my vote!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:30:21.410",
"Id": "436164",
"Score": "0",
"body": "Tossing my vote in because I like the brevity (specifically, the predicate one), but, for a lack of a better term, I'm trying to get the \"first principles\" of `.Any()` which could have also been written as `return source.Take(1).Count() == 1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T18:26:01.217",
"Id": "436213",
"Score": "0",
"body": "@JesseC.Slicer I have a similar case with [`SingleOrThrow`](https://github.com/he-dev/reusable/blob/dev/Reusable.Core/src/Extensions/EnumerableExtensions.cs#L271) that I find is super ugly ;-] so I rewrote it with `Take` + `Count` + `ToList` [here](https://github.com/he-dev/reusable/blob/dev/Reusable.Core/src/Extensions/EnumerableExtensions.cs#L311) and now I like it ;-) I wonder that I didn't have this idea earlier haha"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T18:39:08.833",
"Id": "436215",
"Score": "3",
"body": "@JesseC.Slicer [`SingleOrDefault`](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,1213) with a predicate is even so similar to mine that they also use a `swith`. ok, but their solution is really stupid, it'll enumerate the entire collection! :-o I'm shocked: `new [] { 1, 2, 3, 4}.Select(x => x.Dump()).SingleOrDefault(n => true).Dump();` the inner `Dump` will output everything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T18:45:01.833",
"Id": "436218",
"Score": "1",
"body": "@dfhwze did you know that? `SingleOrDefault` is dangeours when used with a predicate :-\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T18:46:20.747",
"Id": "436219",
"Score": "0",
"body": "@t3chb0t I did not. The more I browse through the reference source of LINQ, to more I realise I should have done it way sooner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T19:02:31.323",
"Id": "436221",
"Score": "0",
"body": "@t3chb0t I am sure this must be a copy-paste bug from the argument-free overload. This is a shock indeed!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T19:52:29.467",
"Id": "436232",
"Score": "2",
"body": "@t3chb0t the scary part is, there's likely code dependent on the suboptimal behavior (side effects) so they'll not rework it properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T20:50:26.457",
"Id": "436238",
"Score": "2",
"body": "@JesseC.Slicer: Exactly. It's been fixed in .net core, but they are hesitant to backport it to the Framework for the exact reason that you mentioned. See https://github.com/dotnet/corefx/issues/25079 for details."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T06:57:50.287",
"Id": "224787",
"ParentId": "224752",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "224754",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T19:37:56.657",
"Id": "224752",
"Score": "17",
"Tags": [
"c#",
"unit-testing",
"linq",
"extension-methods"
],
"Title": "ExactlyOne extension method"
}
|
224752
|
<p>I am traversing two objects that may share a common ancestor. To make the code small enough to show here, I have changed it into two dictionaries with values. As you can see, <code>a_d</code> and <code>b_d</code> are the inverse of each other. The idea is to step into each dictionary step by step until we find an overlapping value for the two. At each step the 'distance' is increased.</p>
<p>For the example case <code>get_distance('b', 'y')</code>, the output will print (comments added):</p>
<pre><code># init
start= b
end= y
# both a and b changed value (dist +1 for both) but no overlap found
start= c
end= x
# both a and b changed value (dist +1 for both) and an overlap was found!
start= d
end= d
Found overlap d
connected True
</code></pre>
<p>I hope that it is clear what this code does and what I am trying to do. Please keep in mind that the actual code works with elaborate objects and their properties, but the idea is similar. The issue that I am having is that the code is very repetitive and probably not as efficient as it could be. But I am not sure how I can improve on it. Ideas welcome!</p>
<pre class="lang-py prettyprint-override"><code>def get_distance(start, end):
start_d = {
'a': 'b',
'b': 'c',
'c': 'd',
'd': 'x',
'x': 'y',
'y': 'z',
'z': 'z'
}
end_d = {
'z': 'y',
'y': 'x',
'x': 'd',
'd': 'c',
'c': 'b',
'b': 'a',
'a': 'a'
}
connected = False
start_dist = 0
end_dist = 0
while True:
print('start=', start)
print('end=', end)
print()
# Check whether a and b are the same, if so break
if start == end:
print(f"Found overlap {end}")
connected = True
break
# Check whether the next a value is the same as b, if so break and increase a_dist
elif start_d[start] == end:
print(f"Found overlap {end}")
start_dist += 1
connected = True
break
# Check whether the next b value is the same as a, if so break and increase b_dist
elif end_d[end] == start:
print(f"Found overlap {start}")
end_dist += 1
connected = True
break
# If for a and b all options are exhausted, break
if start == start_d[start] and end == end_d[end]:
break
# If a is not exhausted, get its dict value and increase distance
if start != start_d[start]:
start_dist += 1
start = start_d[start]
# If b is not exhausted, get its dict value and increase distance
if end != end_d[end]:
end_dist += 1
end = end_d[end]
dist = start_dist + end_dist
print('connected', connected)
return dist
if __name__ == '__main__':
dist = get_distance('b', 'y')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:59:45.617",
"Id": "436032",
"Score": "0",
"body": "text `a=` and `b=` can be missleading when you have also nodes `a` and `b`. Maybe `start=`, `end=` could be more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T01:01:40.420",
"Id": "436033",
"Score": "0",
"body": "what if you have loops in data ? You will never exit from `while`. You should check how many steps you made - it can't be more then number of nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T01:07:21.297",
"Id": "436036",
"Score": "0",
"body": "Maybe traversing in two directions can be sometimes faster - if one direction checked data faster then other direction - but traversing in one direction would need shorter code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T01:09:45.410",
"Id": "436037",
"Score": "0",
"body": "Loops cannot occur (the actual, object-oriented data is on hierarchical data), so you don't have to think about that for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T05:48:19.667",
"Id": "436065",
"Score": "0",
"body": "I think better names would help understanding. Especially, what's the d in start_d and end_d ? And you talk about a tree, but if start/end correspond to actual parent/child, then you probably need something different, for when a node has several children. If it's for a tree again, I wouldn't bother traversing in 2 directions, you can just start from one node (unless you have very particular complexity requirements and statistics)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:29:59.327",
"Id": "436144",
"Score": "0",
"body": "@Gnurfos I often hint towards the type of my variables when I know that type won't change. `start_d` can be dictionary, `start_l` would be a list, and so on. Considering my code is working bottom up until a common ancestor is found, I would suspect that that is faster than working in only one direction since in one direction you would always have to check all descendants, agnostically?"
}
] |
[
{
"body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <code>docstring</code> at the beginning of every method, class, and module you write. This will help documentation identify what your methods/classes/modules are supposed to accomplish.</li>\n<li><strong>Simplicity</strong>: Rather than <code>dist = start_dist + end_dist</code> then returning <code>dist</code>, you can simply return <code>start_dist + end_dist</code>. You can return the addition of the two values, rather than creating a variable to only use it once to return. This is a personal preference, but it helps reduce the number of variables in the program, which helps me; and may also help you.</li>\n<li><strong>Constants</strong>: Any constants in your program should be UPPERCASE. You only have one in your code, but you should keep in practice for when you write bigger programs.</li>\n<li><strong>Printing</strong>: You use <code>print(..., ...)</code> and <code>print(f\"...\")</code> interchangeably. You should stick to using only one for consistency sake. As my preference, I changed all of them to <code>print(f\"...\")</code>, but you change choose your preference.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nTraverses two objects that may share a common ancestor\n\"\"\"\n\ndef get_distance(start, end):\n \"\"\"\n Gets the distance from `start` to `end` in the trees\n \"\"\"\n start_d = {\n 'a': 'b',\n 'b': 'c',\n 'c': 'd',\n 'd': 'x',\n 'x': 'y',\n 'y': 'z',\n 'z': 'z'\n }\n\n end_d = {\n 'z': 'y',\n 'y': 'x',\n 'x': 'd',\n 'd': 'c',\n 'c': 'b',\n 'b': 'a',\n 'a': 'a'\n }\n\n connected = False\n start_dist = 0\n end_dist = 0\n\n while True:\n print(f\"Start: {start}\")\n print(f\"End: {end} \\n\")\n\n # Check whether a and b are the same, if so break\n if start == end:\n print(f\"Found overlap: {end}\")\n connected = True\n break\n\n # Check whether the next a value is the same as b, if so break and increase a_dist\n elif start_d[start] == end:\n print(f\"Found overlap: {end}\")\n start_dist += 1\n connected = True\n break\n\n # Check whether the next b value is the same as a, if so break and increase b_dist\n elif end_d[end] == start:\n print(f\"Found overlap: {start}\")\n end_dist += 1\n connected = True\n break\n\n # If for a and b all options are exhausted, break\n if start == start_d[start] and end == end_d[end]:\n break\n\n # If a is not exhausted, get its dict value and increase distance\n if start != start_d[start]:\n start_dist += 1\n start = start_d[start]\n\n # If b is not exhausted, get its dict value and increase distance\n if end != end_d[end]:\n end_dist += 1\n end = end_d[end]\n\n print(f\"Connected: {connected}\")\n return start_dist + end_dist\n\nif __name__ == '__main__':\n DISTANCE = get_distance('b', 'y')\n print(f\"Distance: {DISTANCE}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-02T01:15:07.727",
"Id": "225389",
"ParentId": "224753",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T19:47:24.113",
"Id": "224753",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"recursion",
"iteration"
],
"Title": "Traversing two trees until a common value has been found"
}
|
224753
|
<p>I currently have an event listener tied to Laravel's <code>Attempting</code> class. The listener is designed to rehash an old password to something newer. The current DB stores the pass in an old crypt format. I'm just silently converting that old hash to a newer one. This works when going to the site to login. Now I want to be a good developer and get tests down. I have a test made that passes. I am not certain however this is the proper way to test it. I would also like to make sure that passwords are not stored in plain text at any time. I am new to testing so I would like to know if this is correct test to use. </p>
<pre><code><?php
namespace Tests\Unit;
use Illuminate\Auth\Events\Attempting;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class PasswordTest extends TestCase
{
use RefreshDatabase;
/** @test */
function user_is_able_to_login_with_old_rs_password()
{
$user = factory('App\User')->create(['password' => '<old badly used hash>']);
$response = $this->post('/login',[
'email' => $user->email,
'password' => 'secret'
]);
$response->assertRedirect('/');
}
/** @test */
function user_password_changed_to_new_hash()
{
Event::fake();
$user = factory('App\User')->create(['password' => '<old badly hashed pass>']);
$this->post('/login',[
'email' => $user->email,
'password' => 'secret'
]);
Event::assertDispatched(Attempting::class);
$pw = 'secret';
$this->assertTrue(Hash::check($pw, $user->password));
$this->post('/logout');
$this->post('/login',[
'email' => $user->email,
'password' => $pw
]);
$this->assertFalse(Hash::check($pw, $pw));
}
}
</code></pre>
<p>This test does return green.. but I have doubts. I would love any tips or tricks so I can improve.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T21:26:00.010",
"Id": "436020",
"Score": "0",
"body": "If the login mechanism involves transmitting the password to the server, then there is no way to know for sure that the server isn't [storing or logging](https://newsroom.fb.com/news/2019/03/keeping-passwords-secure/) a plaintext copy of the password somewhere, unless you inspect the source code of the server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T02:53:09.627",
"Id": "436045",
"Score": "0",
"body": "I haven't changed anything changed anything from laravel's default login system, so I'm pretty sure there's no plain text passwords anywhere.. but that link had good reading so I'll be double checking just in case."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:22:55.403",
"Id": "224756",
"Score": "2",
"Tags": [
"php",
"unit-testing",
"authentication",
"laravel"
],
"Title": "Laravel testing for compatibility between old and new password-hashing schemes"
}
|
224756
|
<p>I have simple class that I want to ask if is there any possible to improve it? I mean, for me it looks poor. Is there any way to use here try-with-resources, stream or <code>optional</code>?</p>
<pre><code>package bookstore.scraper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
@Slf4j
public class JSoupConnector {
public static Document prepareConnectionToURL(String URL) {
Document document = null;
try {
document = Jsoup.connect(URL).get();
} catch (IOException e) {
log.warn("Cannot connect to URL!");
}
return document;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T02:47:18.373",
"Id": "436043",
"Score": "0",
"body": "Welcome to Code Review. Do not fall into *solution looking for a problem*."
}
] |
[
{
"body": "<p>This error handling looks pretty useless to me:</p>\n\n<ul>\n<li>The log message doesn't record which URL was inaccessible.</li>\n<li>If an error occurs, then the code will continue to execute. That means that whoever calls this function will have to handle the possibility of a <code>null</code> result. If that isn't done, then it will cause a <code>NullPointerException</code>.</li>\n</ul>\n\n<p>A better idea would be to simply propagate the exception, so that the caller will stop trying to process a <code>Document</code> that isn't there.</p>\n\n<p>Furthermore, what does it mean to \"prepare a connection\"? It looks like this code goes way beyond preparing a connection — it actually makes the connection and fetches the content as a <code>Document</code>!</p>\n\n<p>So, the class should look more like this:</p>\n\n<pre><code>public class JSoupConnector {\n public static Document connect(String url) throws IOException {\n try {\n return Jsoup.connect(url).get();\n } catch (IOException e) {\n log.warn(\"Cannot connect to URL \" + url);\n throw e;\n }\n }\n}\n</code></pre>\n\n<p>At that point, this wrapper is hardly doing anything at all, and you might consider eliminating this helper functional altogether.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:56:35.937",
"Id": "436017",
"Score": "0",
"body": "I have a lot of methods that use it I wanted to eliminate error handling with IOException in every method (I read that `throws ...` in every method is bad practice). Is it good idea to change `throw e` to `System.exit(1)` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:59:00.873",
"Id": "436018",
"Score": "0",
"body": "ahh... I see that you deleted `Document document=null`, so I need to return something in `catch` statement. As I said is there any way to handle the exception here so that I do not have to do it in the future (methods that use `connect` method)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T21:17:49.877",
"Id": "436019",
"Score": "0",
"body": "The whole point of the `IOException` is to force the caller to deal with the abnormal condition, and also to make it convenient to handle the abnormal condition. Use the exception mechanism to your advantage. Just keep propagating it by declaring a `throws` clause, until you reach a caller that can handle it in a meaningful way. (If you showed more of your code, I could illustrate it better.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T21:29:33.060",
"Id": "436021",
"Score": "0",
"body": "As I said, I'm using it in a lot of Services, so it is hard to handle in a lot of places. Here is a gist: https://gist.github.com/must1/0124f5b294160d8ad5824fe9f52903fe I just added 2 to illustrate how I am using it, but I have 2 more. Thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T07:42:24.577",
"Id": "436300",
"Score": "0",
"body": "If you will have free time, please illustrate it, stil waiting :D .Thanks in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T16:43:26.953",
"Id": "436834",
"Score": "0",
"body": "Is there any way to get it?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:48:54.793",
"Id": "224761",
"ParentId": "224757",
"Score": "1"
}
},
{
"body": "<p>You can fail safe and explicitly handle connection issues by changing the intention of the method:</p>\n\n<pre><code>package bookstore.scraper;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\n\nimport java.io.IOException;\n\n@Slf4j\npublic class JSoupConnector {\n\n public static Optional<Document> attemptConnectionTo(String url) {\n try {\n return Optional.of(Jsoup.connect(url).get());\n } catch (IOException e) {\n log.warn(\"Failed to connect to URL {}: {}\", url, e.getMessage());\n }\n return Optional.empty();\n }\n}\n</code></pre>\n\n<p>This way you emphasize that clients of your utility class should explicitly handle the absence of a document as part of their logic.\nIf your clients would be in an invalid state or there responsibility does not stretch to handling missing documents, then throw an application exception instead to fail fast and delegate to an exception handler.\nMy conclusion is don't return null but clarify your intention as this class is tightly integrated with your app's domain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T15:54:38.343",
"Id": "225040",
"ParentId": "224757",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:25:19.293",
"Id": "224757",
"Score": "2",
"Tags": [
"java",
"error-handling",
"web-scraping"
],
"Title": "Jsoup connection to URL"
}
|
224757
|
<p>I made a task scheduler to practice allocators and type erasure. With my project, you can delay execution of any callable (functions (using <code>std::ref</code>), lambdas...) in time by inserting it in a <code>TaskScheduler</code>, and by giving a <code>std::chrono::time_point</code> (you can also make a task be called multiple times by giving a period (<code>std::chrono::duration</code>) and optionally a number of call)).</p>
<p>This project does not use threads, so to make the tasks called, you have to call <code>TaskScheduler::update</code> (likely in a main loop), which will then call the tasks if needed. I have only basic knowledge on multi-threading so if you have any advice in order to make <code>TaskScheduler</code> thread-safe, I am interested.</p>
<p>Moreover, I have implemented type-erasure (so any callable can fit in the <code>TaskScheduler</code>) so I am interested on comments about the type-safety of this implementation.</p>
<p>Here is the code :</p>
<p><strong>TaskScheduler.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef TASK_SCHEDULER_J_VERNAY
#define TASK_SCHEDULER_J_VERNAY
#include <vector>
#include <chrono>
#include <memory_resource>
#include <tuple>
class TaskTraits {
public:
using clock = std::chrono::system_clock;
using time_point = clock::time_point;
using duration = clock::duration;
};
class Task {
friend class TaskScheduler;
public:
TaskTraits::time_point when() const noexcept { return _when; }
void delay(TaskTraits::duration delay_) noexcept { _when += delay_; }
void set_when(TaskTraits::time_point when_) noexcept { _when = when_; }
void cancel() noexcept { _fun = nullptr; }
void execute() { if (_fun) (*_fun)(*this); }
// for usage in std::sort for TaskScheduler
static bool before(Task const& a, Task const& b) noexcept { return a._when < b._when; }
private:
Task(void(*fun_)(Task&), void* args_, std::size_t size_, TaskTraits::time_point when_) noexcept :
_fun{fun_}, _args{args_}, _size{size_}, _when{when_}
{}
TaskTraits::time_point _when;
void(*_fun)(Task&);
void* _args;
std::size_t _size;
};
class TaskScheduler : private std::pmr::vector<Task> {
using _base = vector;
public:
using _base::value_type;
using _base::reference;
using _base::const_reference;
using _base::difference_type;
using _base::size_type;
using _base::allocator_type;
using _base::iterator;
using _base::const_iterator;
using _base::reverse_iterator;
using _base::const_reverse_iterator;
TaskScheduler(allocator_type a_ = {}) : _base(a_) {}
TaskScheduler(TaskScheduler const& ts_, allocator_type a_ = {}) : _base(ts_, a_) {}
TaskScheduler(TaskScheduler&& ts_) noexcept : _base(ts_) {}
TaskScheduler(TaskScheduler&& ts_, allocator_type a_ = {}) noexcept : _base(ts_, a_) {}
template<typename Fun>
void insert(TaskTraits::time_point when_, Fun const& fun_);
template<typename Fun>
void insert_loop(TaskTraits::time_point when_, TaskTraits::duration loop_, Fun const& fun_);
template<typename Fun>
void insert_loop(TaskTraits::time_point when_, TaskTraits::duration loop_, int nbloops_, Fun const& fun_);
void update();
// with these iterators, you could first: sort the tasks with std::sort and Task::before,
// then: iterate by chronological order. But notice the order will likely be modified by update()!
using _base::begin;
using _base::end;
using _base::cbegin;
using _base::cend;
using _base::rbegin;
using _base::rend;
using _base::crbegin;
using _base::crend;
using _base::empty;
using _base::size;
using _base::clear;
void erase(iterator pos) noexcept; // O(1) because order is not preserved
private:
std::pmr::memory_resource* get_resource() const { return get_allocator().resource(); }
template<typename Fun>
void* store_args(Fun const&);
};
template<typename Fun>
void* TaskScheduler::store_args(Fun const& fun_) {
void* args = nullptr;
if constexpr (sizeof(fun_) <= sizeof(void*)) {
get_allocator().construct(reinterpret_cast<Fun*>(&args), fun_);
} else {
args = get_resource()->allocate(sizeof(fun_));
get_allocator().construct(reinterpret_cast<Fun*>(args), fun_);
}
return args;
}
template<typename Fun>
void TaskScheduler::insert(TaskTraits::time_point when_, Fun const& fun_) {
void* args = store_args(fun_);
auto fun = static_cast<void(*)(Task&)>(
[](Task& t) {
if constexpr (sizeof(Fun) <= sizeof(void*))
reinterpret_cast<Fun&>(t._args)();
else
(*reinterpret_cast<Fun*>(t._args))();
t.cancel();
});
push_back(Task(fun, args, sizeof(fun_), when_));
}
template<typename Fun>
void TaskScheduler::insert_loop(TaskTraits::time_point when_, TaskTraits::duration loop_, Fun const& fun_) {
auto data = std::make_tuple(fun_, loop_);
using data_t = decltype(data);
void* args = store_args(data);
auto fun = static_cast<void(*)(Task&)>(
[](Task& t) {
data_t* data = nullptr;
if constexpr (sizeof(data_t) <= sizeof(void*))
data = reinterpret_cast<data_t*>(&t._args);
else
data = reinterpret_cast<data_t*>(t._args);
std::get<Fun>(*data)();
t.delay(std::get<TaskTraits::duration>(*data));
});
push_back(Task(fun, args, sizeof(data_t), when_));
}
template<typename Fun>
void TaskScheduler::insert_loop(TaskTraits::time_point when_, TaskTraits::duration loop_, int nbloops_, Fun const& fun_) {
if (nbloops_ <= 0) return;
auto data = std::make_tuple(fun_, loop_, nbloops_);
using data_t = decltype(data);
void* args = store_args(data);
auto fun = static_cast<void(*)(Task&)>(
[](Task& t) {
data_t* data = nullptr;
if constexpr (sizeof(Fun) <= sizeof(void*))
data = reinterpret_cast<data_t*>(&t._args);
else
data = reinterpret_cast<data_t*>(t._args);
std::get<Fun>(*data)();
if (--std::get<int>(*data) <= 0)
t.cancel();
else
t.delay(std::get<TaskTraits::duration>(*data));
});
push_back(Task(fun, args, sizeof(data_t), when_));
}
#endif //TASK_SCHEDULER_J_VERNAY
</code></pre>
<p><strong>TaskScheduler.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "TaskScheduler.h"
void TaskScheduler::update() {
TaskTraits::time_point now = TaskTraits::clock::now();
std::size_t userdata_size = 0;
for (std::size_t i = 0, c = size(); i < c; ++i) {
auto task = begin() + i;
while (task->when() < now) {
task->execute();
if (!task->_fun) {
erase(task);
--c;
if (i >= c) return;
task = begin() + i;
}
}
}
}
void TaskScheduler::erase(TaskScheduler::iterator pos) noexcept {
if (pos->_size > sizeof(void*))
get_resource()->deallocate(pos->_args, pos->_size);
*pos = back();
pop_back();
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <thread> // std::this_thread::sleep_for
#include <iostream>
#include <string>
#include "TaskScheduler.h"
using namespace std::chrono_literals;
void print_the_end() { std::printf("==== THE END ====\n"); }
int main() {
std::string a = "Hello", b = "World";
auto begin = TaskTraits::clock::now();
TaskScheduler ts;
ts.insert_loop(begin, 200ms, 25, [begin, &a, i = 0]() mutable { // looping during 200ms * 25 = 5s
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(TaskTraits::clock::now() - begin);
std::printf("Iter %2d, t=%4dms : a = %s\n", ++i, (int)ms.count(), a.c_str());
});
for (std::size_t i = 0; i < 5; ++i) // changing a every 1 second
ts.insert(begin + 500ms + i * 1s, [&a, b, i] {
a[i] = b[i];
std::printf("== a has changed! ==\n");
});
ts.insert(begin + 5s, std::ref(print_the_end));
while (!ts.empty()) { // main loop
ts.update();
std::this_thread::sleep_for(5ms);
}
return 0;
}
</code></pre>
<p><strong>Possible output</strong></p>
<pre><code>Iter 1, t= 0ms : a = Hello
Iter 2, t= 200ms : a = Hello
Iter 3, t= 402ms : a = Hello
== a has changed! ==
Iter 4, t= 605ms : a = Wello
Iter 5, t= 802ms : a = Wello
Iter 6, t=1004ms : a = Wello
Iter 7, t=1200ms : a = Wello
Iter 8, t=1402ms : a = Wello
== a has changed! ==
Iter 9, t=1605ms : a = Wollo
Iter 10, t=1801ms : a = Wollo
Iter 11, t=2001ms : a = Wollo
Iter 12, t=2202ms : a = Wollo
Iter 13, t=2404ms : a = Wollo
== a has changed! ==
Iter 14, t=2602ms : a = Worlo
Iter 15, t=2804ms : a = Worlo
Iter 16, t=3002ms : a = Worlo
Iter 17, t=3202ms : a = Worlo
Iter 18, t=3401ms : a = Worlo
== a has changed! ==
Iter 19, t=3601ms : a = Worlo
Iter 20, t=3801ms : a = Worlo
Iter 21, t=4002ms : a = Worlo
Iter 22, t=4201ms : a = Worlo
Iter 23, t=4402ms : a = Worlo
== a has changed! ==
Iter 24, t=4602ms : a = World
Iter 25, t=4801ms : a = World
==== THE END ====
</code></pre>
<p>Thank you for any review! =)</p>
|
[] |
[
{
"body": "<p>I like:</p>\n\n<ul>\n<li>good include-guards, unlikely to collide with others</li>\n<li>careful use of scoped names</li>\n<li>efficient storage of small values (though the repeated access code could perhaps be refactored to a utility method in <code>Task</code>)</li>\n</ul>\n\n<p>I dislike:</p>\n\n<ul>\n<li>identifiers that differ only in <code>_</code> prefix or suffix</li>\n<li>pointless parens around value arguments to <code>sizeof</code> that make them look like type arguments</li>\n<li>our types are in the global namespace</li>\n</ul>\n\n<p>Specific issues:</p>\n\n<ul>\n<li><blockquote>\n<pre><code>Task(void(*fun_)(Task&), void* args_, std::size_t size_, TaskTraits::time_point when_) noexcept :\n _fun{fun_}, _args{args_}, _size{size_}, _when{when_}\n{}\n</code></pre>\n</blockquote>\n\n<p>It's misleading to write the <code>_when</code> initializer last, as it will be initialized first. In this specific case, it doesn't matter, because there's no interdependencies, but I recommend always writing the initializers in the same order as the members.</p></li>\n<li><blockquote>\n<pre><code>void TaskScheduler::update() {\n std::size_t userdata_size = 0;\n</code></pre>\n</blockquote>\n\n<p>This local variable is never used.</p></li>\n<li><p>I don't see any reason why <code>Task</code> needs to be a publicly-visible class. Since we can't insert or obtain one, it should probably be a private <code>struct</code> within <code>TaskScheduler</code>.</p></li>\n<li><p>When scheduling new tasks, we ought to accept a forwarding reference to a <code>Fun</code>, and use <code>std::fwd()</code> as appropriate, rather than copying from a const reference.</p></li>\n<li><p>We're over-constraining the allocator by letting the alignment default to <code>alignof(std::max_align_t)</code> rather than using the actual alignment requirements like this:</p>\n\n<pre><code>args = get_resource()->allocate(sizeof fun_, alignof(Fun));\n</code></pre></li>\n<li><p>The linear search for tasks to run might be a performance drag when there are lots of tasks. This is a problem for which the <em>heap</em> structure is a perfect fit (<code>std::priority_queue</code>).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T07:48:52.683",
"Id": "437104",
"Score": "0",
"body": "Thank you for your review. `Task` is publicly-visible because you can iterate using begin(), end(), etc, so that you can cancel tasks or delay some. Because of this, something like a heap (or sorting using std::sort) should be recreated each `update` call"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-30T08:16:27.540",
"Id": "437105",
"Score": "0",
"body": "If you're adding tasks one at a time, then don't sort each time - just use `std::binary_search` to insert each item in the right place. You'll still pay for moving the subsequent elements, but that's less than sorting the whole container. Or change to a `std::multiset`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:28:16.993",
"Id": "224809",
"ParentId": "224758",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224809",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:33:07.670",
"Id": "224758",
"Score": "4",
"Tags": [
"c++",
"memory-management",
"timer",
"c++17",
"type-safety"
],
"Title": "Single-thread Task Scheduler with type erasure and allocator-aware"
}
|
224758
|
<p>I have a list of 2D matrices. Each matrix is filled using the function “fillMatrices”. This function adds a number of individuals to each day 0 in a matrix and updates the columns “a_M”, “b_M” and “c_M”. The numbers of individuals come from an initial matrix “ind”. The code works but it is slow when the number of matrices within the list is large.
For example with n = 10000:</p>
<pre><code>user system elapsed
3.73 0.83 4.55
</code></pre>
<p>Here is the code:</p>
<pre><code>rm(list=ls(all=TRUE))
library(ff)
library(dplyr)
set.seed(12345)
## Define the number of individuals
n <- 10000
###############################################
###############################################
## Section 1
## Build the list of 2D matrices
v_date <- as.vector(outer(c(paste(seq(0, 1, by = 1), "day", sep="_"), paste(seq(2, 5, by = 1), "days", sep="_")), c("a_M", "b_M", "c_M"), paste, sep="|"))
col_mat <- c("year", "day", "time", "ID", "died", v_date)
list_matrices <- list()
for(i in 1:n){
print(i)
list_matrices[[i]] <- ff(-999, dim=c(3650, length(col_mat)), dimnames=list(NULL, col_mat), vmode="double", overwrite = TRUE)
}
## test <- list_matrices[[1]]
## dim(list_matrices[[1]])
## Fill the first row of each matrix
for(i in 1:n){
print(i)
list_matrices[[i]][1,] <- c(1, 1, 1, i-1, 0, rep(0, length(v_date)))
}
## test <- list_matrices[[2]]
## Build the matrix "individual"
ind <- as.matrix(data.frame(year = rep(1, n), day = rep(1, n), time = rep(1, n), died = rep(0, n), ID = (seq(1, n, 1))- 1, a_M = sample(1:10, n, replace = T), b_M = sample(1:10, n, replace = T), c_M = sample(1:10, n, replace = T)))
## print(ind)
###############################################
###############################################
## Section 2
## Function to convert a data frame into a matrix
convertDFToMat <- function(x){
mat <- as.matrix(x[,-1])
ifelse(is(x[,1], "data.frame"), rownames(mat) <- pull(x[,1]), rownames(mat) <- x[,1])
## Convert character matrix into numeric matrix
mat <- apply(mat, 2, as.numeric)
return(mat)
}
## Define the function that is used to fill the matrices within the list
fillMatrices <- function(dt_t_1, species, maxDuration, matrixColumns){
## Format data
dt <- as.data.frame(dt_t_1) %>%
reshape::melt(id = c("ID")) %>%
arrange(ID) %>%
dplyr::mutate_all(as.character)
## summary(dt)
## Break out the variable "variable" into different columns, with one row for each individual-day
dt_reshape_filter_1 <- dt %>%
dplyr::filter(!variable %in% c("year", "day", "time", "ID", "died")) %>%
dplyr::mutate(day = variable %>% gsub(pattern = "\\_.*", replacement = "", x = .), col = variable %>% gsub(pattern = ".*\\|", replacement = "", x = .)) %>%
dplyr::select(-variable) %>%
tidyr::spread(col, value) %>%
dplyr::mutate_all(as.numeric) %>%
dplyr::arrange(ID, day)
## summary(dt_reshape_filter_1)
## Apply requested transformations and build the data frame
dt_transform <- dt_reshape_filter_1 %>%
dplyr::rename_at(vars(species), ~ c("a", "b", "c")) %>%
dplyr::mutate(day = day + 1) %>%
dplyr::filter(day < maxDuration + 1) %>%
dplyr::bind_rows(tibble(ID = ind[,c("ID")], day = 0, a = ind[,c("a_M")], b = ind[,c("b_M")])) %>%
dplyr::mutate(c = a + b) %>%
dplyr::rename_at(vars("a", "b", "c"), ~ species) %>%
dplyr::arrange(ID, day)
## summary(dt_transform)
## Take different columns of the data frame and gather them into a single column
dt_gather <- dt_transform %>%
tidyr::gather(variable, value, species) %>%
dplyr::mutate(day = if_else(day > 1, paste0(day, "_days"), paste0(day, "_day"))) %>%
tidyr::unite(variable, c("day", "variable"), sep = "|") %>%
dplyr::rename(var2 = ID) %>%
dplyr::mutate_all(as.character)
## summary(dt_gather)
## Add the other columns in the data frame and convert the resulting data frame into a matrix
dt_reshape_filter_2 <- dt %>%
dplyr::rename(var2 = ID) %>%
dplyr::filter(variable %in% c("year", "day", "time", "ID", "died")) %>%
tidyr::spread(variable, value) %>%
dplyr::arrange(as.numeric(var2)) %>%
dplyr::mutate(year = ind[,c("year")],
day = ind[,c("day")],
time = ind[,c("time")],
ID = ind[,c("ID")],
died = ind[,c("died")]) %>%
tidyr::gather(variable, value, c(year, day, time, ID, died)) %>%
dplyr::arrange(as.numeric(var2)) %>%
dplyr::mutate_all(as.character)
## summary(dt_reshape_filter_2)
## Build the output matrix
dt_bind <- bind_rows(dt_reshape_filter_2, dt_gather) %>%
tidyr::spread(var2, value) %>%
dplyr::arrange(match(variable, matrixColumns)) %>%
dplyr::select("variable", as.character(ind[,c("ID")]))
## summary(dt_bind)
dt_mat <- convertDFToMat(dt_bind)
## summary(dt_mat)
return(dt_mat)
}
###############################################
###############################################
## Section 3
## Run the function "fillMatrices"
indexTime <- 1
dt_t_1 <- do.call(rbind, lapply(list_matrices, function(x) x[1,]))
dt_t <- fillMatrices(dt_t_1 = dt_t_1, species = c("a_M", "b_M", "c_M"), maxDuration = 5, matrixColumns = col_mat)
## Fill the matrices within the list
system.time(for(i in 1:n){
list_matrices[[i]][indexTime + 1,] <- dt_t[,i]
})
## test <- list_matrices[[1]]
</code></pre>
<p>If possible, I would like to reduce the elapsed time to <= 1 sec and increase the n to 720000 matrices. I think that the code is slow because I use different data structures (i.e., both matrices and data frames) at each time step (see the <strong>function "fillMatrices" in the section 2</strong>). In addition, the loop “for” is not efficient enough (see <strong>loop "for" in the section 3</strong>). I don’t look for way to optimize the section 1 in the code because this section is used only to initialize the matrices. In my example, the function is used to fill matrices for one species. In reality, the function is used for 3 species (i.e., is applied three times) by changing the argument <code>“species = c("a_M", "b_M", "c_M")”</code>. How can I speed up my code? Any advice would be much appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T10:47:29.267",
"Id": "437506",
"Score": "2",
"body": "Preallocating the list should make this code faster without making any major changes `list_matrices <- vector(mode = \"list\", length = n)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:41:12.370",
"Id": "438685",
"Score": "0",
"body": "Thank you very much for your answer. How can I fill the lists using `list_matrices <- vector(mode = \"list\", length = n)` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:08:54.347",
"Id": "443113",
"Score": "0",
"body": "could you confirm whether the preallocation sped this up? Maybe post some timings, please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T14:22:39.473",
"Id": "511047",
"Score": "0",
"body": "I can confirm that the pre-allocation took 6120 to 5650 ms."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:40:39.640",
"Id": "224760",
"Score": "3",
"Tags": [
"performance",
"linked-list",
"r"
],
"Title": "Efficient way to fill 2D matrices by rows in a list using R"
}
|
224760
|
<p>I’m trying to generate 5 characters from the ranges 0–9 and a–Z. Is my solution optimal or did I overthink it a little? Would hardcoding a character list be more optimal?</p>
<pre><code>const numbers = [
...Math.random()
.toString(36)
.substr(2, 5),
].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join('');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:29:21.497",
"Id": "436013",
"Score": "2",
"body": "Possible duplicate of [Generate random string/characters in JavaScript](https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:34:26.660",
"Id": "436015",
"Score": "1",
"body": "Optimal in terms of readability, speed, number of characters, or something else? Also, does it need to be unguessable (secure)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:35:30.047",
"Id": "436016",
"Score": "5",
"body": "This question is too broad for StackOverflow, however *is* on topic for CodeReview as others have suggested. I find this to be a helpful reference in these situations: [**A guide to Code Review for Stack Overflow users**](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users). You'll notice that it clarifies StackOverflow questions require a specific goal (which 'more optimal' doesn't seem to reach), whereas CodeReview is tolerant of open-ended questions and answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T23:05:38.830",
"Id": "436025",
"Score": "0",
"body": "Example: https://gitlab.com/maurygta2/fcppandjs/blob/master/Text Random/randomtext.js"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T23:20:16.333",
"Id": "436029",
"Score": "0",
"body": "https://en.wikipedia.org/wiki/KISS_principle"
}
] |
[
{
"body": "<p>There's at least one problem with this approach.</p>\n\n<p>What happens if <code>Math.random()</code> generates a number that can be represented with just a few digits, like <code>0.25</code>? You've got only one random character in that case, not five. Instead of using the fractional part of a number, maybe it would make more sense to generate integers in the range 36^4 to 36^5-1, to ensure that you have exactly 5 base-36 digits. Or use zero for the lower end of the range and pad the result with zeros, if it's important that the first character can be 0.</p>\n\n<p>Also, should these be uniform? A <code>z</code> is only half as likely to be generated as a <code>9</code>, due to only letters being transformed by uppercasing.</p>\n\n<p>Aside from that, converting a string to an array and then back to a string feels a bit convoluted. You could write something like this to get the same result:</p>\n\n<pre><code>Math.random().toString(36).substr(2, 5).replace(/./g,\n m => Math.random() > 0.5 ? m.toUpperCase() : m)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T21:50:39.357",
"Id": "224763",
"ParentId": "224762",
"Score": "2"
}
},
{
"body": "<h2>Small Bias</h2>\n<p>First a nit pick, <code>Math.random()</code> generates a number from 0 to < 1. It will never generate 1. Thus to get a statistical odds of 1/2 you must test either <code>Math.random() < 0.5</code> or <code>Math.random() >= 0.5</code>. Testing <code>Math.random() > 0.5 ? char : char.toUpperCase()</code> will give a very (VERY) small bias in favor of upper case characters.</p>\n<h2>Dramatic Bias</h2>\n<p>Also there is a very strong bias towards numerals in your function with a 0-9 being 2 times more likely than a-z or A-Z</p>\n<p>The following snippet counts the occurrence of each character generated by your function and plots them (normalized) on a graph.</p>\n<p>I animated it slowly for dramatic effect.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>canvas.width = innerWidth - 10;\nconst ctx = canvas.getContext(\"2d\");\nconst w = canvas.width;\nconst h = canvas.height;\nconst chars = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nvar testCount = 2;\nconst val = new Array(chars.length)\nval.fill(0);\nconst func = randString;\nfunction randString() {\n return [\n ...Math.random()\n .toString(36)\n .substr(2, 5),\n ].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join('');\n}\nfunction testRandomness() {\n var i = testCount;\n while (i--) {\n const a = func();\n for (const c of a) { val[chars.indexOf(c)] += 1 }\n }\n \n const max = Math.max(...val);\n ctx.clearRect(0, 0, w, h);\n const ww = w / val.length;\n i = val.length;\n ctx.fillStyle = \"blue\";\n while (i--) {\n if (chars[i] === \"z\") { ctx.fillStyle = \"green\" }\n if (chars[i] === \"9\") { ctx.fillStyle = \"red\" }\n const v = val[i] / max * h;\n ctx.fillRect(i * ww, h - v, ww- 2, v)\n }\n setTimeout(testRandomness, 1000 / 30);\n}\ntestRandomness();\ncanvas.addEventListener(\"click\",()=> (testCount = 10000,d.textContent = \"Sample rate ~300,000per sec\") ,{once:true});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body { font-family: arial black; }\ncanvas {\n padding: 0px;\n}\n#a { color:red; }\n#b { color:green; }\n#c { color:blue; }\n#d { font-family: arial; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\"></canvas>\n<span id=\"a\">Red</span> 0-9 <span id=\"b\">Green</span> a-z <span id=\"c\">Blue</span> A-Z <span id=\"d\">Click graph to increase sample rate to 10000</span></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Click the graph to increase the tests per sample to 10000 per 30th second (approx) and you will see that apart from the numeral bias the graph quickly becomes very flat showing no other major bias (the uppercase bias is way to small to see)</p>\n<p>The reason for the bias is that you split the characters a-z in two when you convert half to uppercase.</p>\n<p>Also note as pointed out in the other answer, there is a small chance that the returned string is less than 5 characters long.</p>\n<h2>Performance</h2>\n<p>In terms of performance using a lookup table is around 3 times faster ie calculate 1.5million strings in the time yours calculates 0.5million.</p>\n<pre><code>const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\nfunction randString(size = 5) {\n var str = "";\n while (size--) { str += chars[Math.random() * chars.length | 0] }\n return str;\n}\n</code></pre>\n<p>As a function it is much more flexible, and can easily be adapted to include extra characters, or reduced character sets.</p>\n<p>If all that matters is performance you can get around 10% faster by avoiding some of the readability introduce overhead with</p>\n<pre><code>function randString() {\n return chars[Math.random() * 62 | 0] +\n chars[Math.random() * 62 | 0] +\n chars[Math.random() * 62 | 0] +\n chars[Math.random() * 62 | 0] +\n chars[Math.random() * 62 | 0];\n}\n</code></pre>\n<p>Or (on chrome) the following is on average 2% faster than the one above but only after it has been run many time so that the optimizer knows what it does. If run only a few time it is slower than above</p>\n<pre><code>function randString3() {\n return `${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}`;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T21:35:02.517",
"Id": "436253",
"Score": "1",
"body": "Definitely deserves a +1 for the animation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T22:20:48.920",
"Id": "224767",
"ParentId": "224762",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "224767",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T20:26:22.743",
"Id": "224762",
"Score": "1",
"Tags": [
"javascript",
"random"
],
"Title": "Generate random characters from ranges 0–9 and a–Z"
}
|
224762
|
<p>I've developed a small memory game, the game contains a function to flip cards for every turn. I'm looping thru the array containing the images every time to pick one card. I'm sure there's away to optimize this function so I don't have to loop through the array every time in order to just turn one card. But I'm a bit clueless how to proceed and would like to get some guidance of how I possibly could optimize this function with vanilla javascript and without objects.</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 flipCards() {
var i; // Loopvariabel
// For loop
for (i = 0; i < cardsElems.length; i++) {
if (this == cardsElems[i]) {
if (cardsCounter > 1) {
return;
}
cardsElems[i].className = "brickFront";
cardsElems[i].src = "pics/" + allCards[i] + ".png";
removeListener(cardsElems[i], "click", flipCards);
if (cardsCounter < 1) {
card1 = i;
} else {
card2 = i;
}
cardsCounter += 1;
}
}
if (cardsCounter < 2) {
nextBtn.disabled = true; // Avaktivera knapp
}
if (cardsCounter == 2) {
turns += 1;
turnNr.innerHTML = turns;
nextBtn.disabled = false; // Aktivera knapp
}
if (brickBack.length == 0) {
endGame();
}
} // End flipCards</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T11:48:12.927",
"Id": "436136",
"Score": "0",
"body": "Before you start optimizing, is it actually too slow? Do you have any profiling data to share?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T22:02:24.023",
"Id": "224764",
"Score": "3",
"Tags": [
"javascript",
"dom"
],
"Title": "Function to flip cards in a memory game"
}
|
224764
|
<p>Work flow is:</p>
<ul>
<li>Copy Previous Year Reports Folder</li>
<li>Update Following Templates</li>
<li>Save</li>
<li>Close</li>
</ul>
<p>There are 19 workbooks in the Source Folder and in the NewYear Folder. Each Workbook has to save the final data from the end of the year (the "YTD ACTUAL" pages) along with resetting and prepping the month sheets for the new year.</p>
<p>Don't be afraid to trash me or offend me. I obviously am new to this, and there has to be a better way to do it.</p>
<pre><code>Private Sub Workbook_Open()
Dim CYR As Variant, PYR As Integer, InputError As Integer, SourceFolder As String, NewYearFolder As String, NewYearFiles As String, oFSO As Object, oNewYearFolder As Object, oNewYearFiles As Object, filename As Variant
CYR = InputBox("Input New Year in 4 Digit Format. XXXX")
On Error GoTo ErrorCheck
PYR = CYR - 1
SourceFolder = "C:\Users\nick.hasler\Desktop\Daily Service Reporting\" & PYR & " Service Report - Daily"
NewYearFolder = "C:\Users\nick.hasler\Desktop\Daily Service Reporting\" & CYR & " Service Report - Daily"
NewYearFiles = Dir(NewYearFolder & "\" & "*.xl??")
Application.ScreenUpdating = False
Application.EnableEvents = False
If Dir(NewYearFolder, vbDirectory) = "" Then
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.copyFolder SourceFolder, NewYearFolder
MsgBox "New Year Folder Created"
Set oNewYearFolder = oFSO.GetFolder(NewYearFolder)
Set oNewYearFiles = oNewYearFolder.Files
For Each filename In oNewYearFiles
If filename Like "*" & PYR & "*" Then
NewFileName = Replace(filename, PYR, CYR)
Name filename As NewFileName
End If
Next filename
MsgBox "New Year Files Renamed"
MsgBox "The Next Step Will Take a Few Moments"
NewYearFiles = Dir(NewYearFolder & "\" & "*.xl??")
Do While NewYearFiles <> ""
Workbooks.Open (NewYearFolder & "\" & NewYearFiles)
Workbooks(NewYearFiles).Sheets(PYR & " YTD").Select
Workbooks(NewYearFiles).Sheets(PYR & " YTD").Name = CYR & " YTD"
Workbooks(NewYearFiles).Worksheets("2019 Actual").Select
Workbooks(NewYearFiles).Worksheets(PYR & " Actual").Copy Before:=Workbooks(NewYearFiles).Worksheets(CYR & " YTD")
Workbooks(NewYearFiles).Worksheets(PYR & " Actual (2)").Select
Workbooks(NewYearFiles).Worksheets(PYR & " Actual (2)").Name = CYR & " Actual"
Workbooks(NewYearFiles).Worksheets(PYR & " Actual").Select
Workbooks(NewYearFiles).Worksheets(PYR & " Actual").Cells.Select
Selection.Copy
Workbooks(NewYearFiles).Worksheets(PYR & " Actual").Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Monthly Reporting
Workbooks("Create New Year").Worksheets("Monthly Reporting").Range("A5:AH16").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("Monthly Reporting").Range("A5:AH16")
Workbooks("Create New Year").Worksheets("Monthly Reporting").Range("H76:AH88").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("Monthly Reporting").Range("H76:AH88")
Workbooks(NewYearFiles).Worksheets("Monthly Reporting").Range("A1:AH90").Replace What:="qqq", Replacement:="="
Workbooks(NewYearFiles).Worksheets("Monthly Reporting").Range("A1:J4").Replace What:=PYR, Replacement:=CYR
'Daily Reporting
Workbooks("Create New Year").Worksheets("Daily Reporting").Range("A2:AG18").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("Daily Reporting").Range("A2:AG18")
Workbooks(NewYearFiles).Worksheets("Daily Reporting").Range("A1:AG18").Replace What:="qqq", Replacement:="="
Workbooks(NewYearFiles).Worksheets("Daily Reporting").Range("A3:AG3").Replace What:="Year", Replacement:=CYR
'January
Workbooks("Create New Year").Worksheets("January").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("January").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("January").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("January").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("January").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'February
Workbooks("Create New Year").Worksheets("February").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("February").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("February").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("February").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("February").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'March
Workbooks("Create New Year").Worksheets("March").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("March").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("March").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("March").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("March").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'April
Workbooks("Create New Year").Worksheets("April").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("April").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("April").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("April").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("April").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'May
Workbooks("Create New Year").Worksheets("May").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("May").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("May").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("May").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("May").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'June
Workbooks("Create New Year").Worksheets("June").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("June").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("June").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("June").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("June").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'July
Workbooks("Create New Year").Worksheets("July").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("July").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("July").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("July").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("July").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'August
Workbooks("Create New Year").Worksheets("August").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("August").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("August").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("August").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("August").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'September
Workbooks("Create New Year").Worksheets("September").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("September").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("September").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("September").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("September").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'October
Workbooks("Create New Year").Worksheets("October").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("October").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("October").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("October").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("October").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'November
Workbooks("Create New Year").Worksheets("November").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("November").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("November").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("November").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("November").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
'December
Workbooks("Create New Year").Worksheets("December").Range("A7:AFH46").Copy _
Destination:=Workbooks(NewYearFiles).Worksheets("December").Range("A7:AFH46")
Workbooks(NewYearFiles).Worksheets("December").Range("A1:AFH7").Replace What:=PYR, Replacement:=CYR
Workbooks(NewYearFiles).Worksheets("December").Range("ADZ7:AFH7").Replace What:="PYear", Replacement:=PYR
Workbooks(NewYearFiles).Worksheets("December").Range("A2:AFH46").Replace What:="qqq", Replacement:="="
Application.CutCopyMode = False
Workbooks(NewYearFiles).Save
Workbooks(NewYearFiles).Close
NewYearFiles = Dir()
Loop
MsgBox "New Year Files Reset"
Else
InputError = 1
End If
ErrorCheck:
If CYR = "" Then
MsgBox "You did not input a valid year"
End If
If InputError = 1 Then
MsgBox "That Year Already Exist. Delete the folder if you wish to replace it."
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
'Workbooks("Create New Year").Save
'Workbooks("Create New Year").Close
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T02:53:42.630",
"Id": "436046",
"Score": "2",
"body": "Welcome to Code Review. Consider tagging your question *beginner*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:51:35.060",
"Id": "436169",
"Score": "0",
"body": "@greybeard Done. Any ideas on how to optimize my mess?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:11:25.367",
"Id": "436172",
"Score": "1",
"body": "@NickHasler patience young grasshopper... :) Doing a good code review takes quite a bit of time. I'd expect you'll get at least one good review, but you should expect that it may take 24 or more hours before it's posted. Some folks will take more than an hour of their time to review your code, then another hour or more to write it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:12:26.483",
"Id": "436173",
"Score": "0",
"body": "In the meantime, take the [tour] and read through the [help]. It will pass _some of_ the time and give you an idea of what to expect 'round here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:47:23.220",
"Id": "436178",
"Score": "0",
"body": "@FreeMan I skimmed both of them before posting. That's where the \"don't be afraid to offend me\" came from. I will wait patiently. Just wanted to know if he had any broad tips"
}
] |
[
{
"body": "<blockquote>\n <p>Don't be afraid to trash me or offend me.</p>\n</blockquote>\n\n<p>Ok, I'll bite ;-)</p>\n\n<p>But this isn't about <em>you</em>, it's all about <em>the code</em>. It's always about the code. Reviewers are not here to judge, they're here to help you grow, and improve your programming!</p>\n\n<blockquote>\n <p>I obviously am new to this, and there has to be a better way to do it</p>\n</blockquote>\n\n<p>Oh, yes, absolutely. But first, I need to know what it does. So I glance at the code, and see a <code>Workbook.Open</code> handler - the macro runs every time <code>ThisWorkbook</code> (i.e. the host Excel document) is opened, which - <em>in my opinion</em> - isn't a terrific user experience. I personally prefer opening the workbook on an empty sheet that hides gridlines, row/column headings, and the formula bar; on it you'd find a number of formatted <em>shapes</em>/buttons, each assigned to a <code>Public Sub</code> procedure that lives in a <em>standard module</em>. That way the macro runs as a result of a user action beyond just opening the workbook.</p>\n\n<p>But let's just go with \"well it runs on open, they wanted it that way\".</p>\n\n<p>So the first thing we see is a <em>string</em> of chained declarations:</p>\n\n<blockquote>\n<pre><code>Dim CYR As Variant, PYR As Integer, InputError As Integer, SourceFolder As String, NewYearFolder As String, NewYearFiles As String, oFSO As Object, oNewYearFolder As Object, oNewYearFiles As Object, filename As Variant\n</code></pre>\n</blockquote>\n\n<p>That's great, variables are being declared! Only problem is, <code>Option Explicit</code> is obviously missing at the top of the module, because it wouldn't compile otherwise: <code>NewFileName</code> isn't declared.</p>\n\n<p>One problem with declaring a bunch of variables at the top of a procedure scope like this (ignoring the outrageous horizontal scrolling), is that it makes them look like <em>checking a box</em> off some list of things that need to be done (\"declare variables: check!\") - and the string of variables becomes essentially <em>noise</em>; code that needs to be there, but code that is systematically ignored/skipped, because what do we care about a variable that's used 200 lines below, when we're reading around the top of the procedure?</p>\n\n<p>Compare to declaring variables <em>as close as possible to their first use</em>:</p>\n\n<pre><code>Dim CYR As Variant\nCYR = InputBox(\"Input New Year in 4 Digit Format. XXXX\")\nOn Error GoTo ErrorCheck\n\nDim PYR As Integer\nPYR = CYR - 1\n</code></pre>\n\n<p>Now the wall/string/chain of declarations is gone, and we see variables' declarations exactly where they are relevant.</p>\n\n<p>But we need to stop right here and talk about <em>separation of concerns</em>. Procedures should be simple. Like, <em>stupid</em> simple. This <code>Workbook.Open</code> handler has a <em>cyclomatic complexity</em> of 6, which is a little high. What's that? It's an objective metric that can be used to identify potentially problematic areas in source code. Essentially, <em>how many possible execution paths are there?</em> And the answer here is \"too many!\". In a dream world, an event handler should look like this:</p>\n\n<pre><code>Private Sub SomeObject_SomeEvent()\n DoSomething\nEnd Sub\n</code></pre>\n\n<p>That's right - a <em>high abstraction</em> one-liner! What happens when <code>SomeEvent</code> is fired? We <code>DoSomething</code>! In this case, we might be abstracting the logic behind a procedure named <code>CreateMonthlyReportingBook</code>, and so we would be looking at <code>Workbook_Open</code> and when asked \"what happens when the workbook opens?\" we could say \"we create a monthly reporting book\", and that would be enough information for anyone that doesn't need every little bit of detail of <em>how that's done</em>.</p>\n\n<p>So what would <code>CreateMonthlyReportingBook</code> do? Two or three closely related things:</p>\n\n<pre><code>Private Sub CreateMonthlyReportingBook()\n Dim yearToProcess As Long\n If Not PromptForYearToProcess(yearToProcess) Then Exit Sub\n If Not CreateYearFolder(yearToProcess) Then Exit Sub\n ProcessYearFiles yearToProcess\nEnd Sub\n</code></pre>\n\n<p>Note how pulling the <code>InputBox</code> and input validation into its own function, we instantly get the desired functionality (bail out on invalid input) without needing to track some \"input error\" variable that's actually used... pretty much 200 lines below where it's relevant.</p>\n\n<p>Here <code>PromptForYearToProcess</code> would take the <code>yearToProcess</code> value as a <code>ByRef</code> argument - the function might look like this:</p>\n\n<pre><code>Private Function PromptForYearToProcess(ByRef outYear As Long) As Boolean\n 'prompt for what year to process...\n 'validate user input...\n 'assign outYear parameter with the validated user input...\n 'return true if everything went well and outYear is valid.\nEnd Function\n</code></pre>\n\n<p>The job of <code>CreateYearFolder</code> is to create the folder for the new year and prepare it for processing. If it can't do that (e.g. year folder already exists, or some I/O error is otherwise preventing successful completion), the rest of the procedure bails out.</p>\n\n<p><code>ProcessYearFiles</code> would be where we iterate the folder for the specified year, and start iterating the workbooks to work with - but the \"real work\" would be in another procedure, one that takes a <code>Workbook</code> parameter; perhaps something like <code>ConfigureYearBook</code> - a procedure that's given a workbook and proceeds to do what needs to be done with it: it knows nothing of the bigger picture, all it cares about is that there's a workbook that needs processing, and it knows what that processing needs to be.</p>\n\n<p>And inside this <code>ConfigureYearBook</code> procedure, there would be a call to another procedure - <code>ConfigureMonthSheet</code>, which would be given a <code>Worksheet</code> (and the <code>PYR</code> value), and be responsible for setting up the worksheet for that particular month.</p>\n\n<p>So this copy-pasta repeated chunk...</p>\n\n<blockquote>\n<pre><code>Workbooks(\"Create New Year\").Worksheets(\"January\").Range(\"A7:AFH46\").Copy _\n Destination:=Workbooks(NewYearFiles).Worksheets(\"January\").Range(\"A7:AFH46\")\n\nWorkbooks(NewYearFiles).Worksheets(\"January\").Range(\"A1:AFH7\").Replace What:=PYR, Replacement:=CYR\nWorkbooks(NewYearFiles).Worksheets(\"January\").Range(\"ADZ7:AFH7\").Replace What:=\"PYear\", Replacement:=PYR\nWorkbooks(NewYearFiles).Worksheets(\"January\").Range(\"A2:AFH46\").Replace What:=\"qqq\", Replacement:=\"=\"\n</code></pre>\n</blockquote>\n\n<p>...could actually look like this:</p>\n\n<pre><code>Private Sub ConfigureMonthSheet(ByVal sheet As Worksheet, ByVal previousYear As Long)\n ThisWorkbook.Worksheets(sheet.Name).Range(\"A7:AFH46\").Copy _\n Destination:=sheet.Range(\"A7:AFH46\")\n sheet.Range(\"ADZ7:AFH7\").Replace \"PYear\", prevousYear\n sheet.Range(\"A2:AFH46\").Replace \"qqq\", \"=\"\nEnd Sub\n</code></pre>\n\n<p>So <code>ConfigureYearBook</code> would be iterating an array of month/sheet names, and invoking <code>ConfigureMonthSheet</code> for each destination sheet.</p>\n\n<p>A note about this:</p>\n\n<blockquote>\n<pre><code>Workbooks.Open (NewYearFolder & \"\\\" & NewYearFiles)\n</code></pre>\n</blockquote>\n\n<p>You're discarding the <code>Workbook</code> reference returned by the <code>Workbooks.Open</code> function. Declare a variable...</p>\n\n<pre><code>Dim targetBook As Workbook\nSet targetBook = Workbooks.Open(NewYearFolder & \"\\\" & NewYearFiles)\n</code></pre>\n\n<p>And now you can use that object reference instead of repeatedly dereferencing it from the <code>Workbooks</code> collection every time you need it:</p>\n\n<blockquote>\n<pre><code> Workbooks(NewYearFiles).Sheets(PYR & \" YTD\").Select\n Workbooks(NewYearFiles).Sheets(PYR & \" YTD\").Name = CYR & \" YTD\"\n Workbooks(NewYearFiles).Worksheets(\"2019 Actual\").Select\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual\").Copy Before:=Workbooks(NewYearFiles).Worksheets(CYR & \" YTD\")\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual (2)\").Select\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual (2)\").Name = CYR & \" Actual\"\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual\").Select\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual\").Cells.Select\n Selection.Copy\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual\").Range(\"A1\").Select\n Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=False, Transpose:=False\n</code></pre>\n</blockquote>\n\n<p>Line continuations are useful, but please avoid using them in weird places (the macro recorder likes putting them in stupid arbitrary locations), like between a named argument's name and that named argument's value:</p>\n\n<blockquote>\n<pre><code> Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=False, Transpose:=False\n</code></pre>\n</blockquote>\n\n<p><code>SkipBlanks</code> is the named argument, <code>:=</code> is the operator that makes VBA understand it as such, and <code>False</code> is the argument's value; try to keep named arguments together with their values, seeing the <code>:=</code> operator at the beginning of a line of code means the reader's eyes need to drift upwards and right to find what argument that value is for, and that's ojectively bad.</p>\n\n<blockquote>\n<pre><code> Workbooks(NewYearFiles).Worksheets(PYR & \" Actual\").Copy Before:=Workbooks(NewYearFiles).Worksheets(CYR & \" YTD\")\n Workbooks(NewYearFiles).Worksheets(PYR & \" Actual (2)\").Select\n</code></pre>\n</blockquote>\n\n<p>The <code>Copy</code> should be automatically activating the new sheet, so that <code>.Select</code> is entirely redundant; <code>\" Actual (2)\"</code> is <em>already</em> the <code>ActiveSheet</code> at that point, so the subsequent lines should do something along the lines of...</p>\n\n<pre><code>targetBook.Worksheets(PYR & \" Actual\").Copy _\n Before:=targetBook.Worksheets(CYR & \" YTD\")\n\nDim sheet As Worksheet\nSet sheet = ActiveSheet\n\nsheet.Name = CYR & \" Actual\"\nsheet.Cells.Copy\nsheet.Range(\"A1\").PasteSpecial _\n Paste:=xlPasteValues, _\n Operation:=xlNone, _\n SkipBlanks:=False, _\n Transpose:=False\n</code></pre>\n\n<p>But, there's no need to involve the clipboard here:</p>\n\n<pre><code>'overwrite formulas with their values:\nsheet.UsedRange.Value = sheet.UsedRange.Value\n</code></pre>\n\n<p>Note that doing this with <code>sheet.Cells</code> instead of <code>sheet.UsedRange</code> would very likely result in an \"out of memory\" error - sending <em>every single cell in the worksheet</em> into the clipboard is MASSIVELY inefficient: we're talking 16K columns times over a <em>million</em> rows, i.e. well over a <em>billion</em> cells - most of which empty.</p>\n\n<hr>\n\n<p>There's <em>a lot</em> to say about this code, and many ways it can be improved. Performance-wise, there is quite a bit of I/O work involved (opening files, saving them, closing them) that has very little room for any performance gains. However removing the <code>Select</code>/<code>Activate</code> stuff, minimizing clipboard use, reducing redundant object dereferencing, will all contribute to improve the overall performance.</p>\n\n<p>But before tweaking for performance, my advice would be to tweak for readability and maintainability first. Increase the <em>level of abstraction</em> by extracting \"this chunk of code does XYZ\" instructions into their own procedure scopes, then split these further into smaller, more specialized procedures that do what they need to do and nothing else; use meaningful, fully spelled-out identifier names; if <code>CYR</code> stands for <code>currentYear</code>, then name it that; if <code>PYR</code> stands for <code>previousYear</code>, then name it that; name procedures with a verb, keep nouns for variables.</p>\n\n<p>What you absolutely want to avoid, is looking at a single \"god procedure\" that does everything, knows everything, controls everything. Split. Things. Up. A procedure that's 5-10 lines long can only go wrong in a limited number of ways. A 200-liner procedure has many, many more reasons to fail, and that makes it much more complicated.</p>\n\n<p>A <em>User Experience</em> (UX) note about this:</p>\n\n<blockquote>\n<pre><code>MsgBox \"New Year Files Renamed\"\nMsgBox \"The Next Step Will Take a Few Moments\"\n</code></pre>\n</blockquote>\n\n<p>Avoid obnoxious user prompts like that. One <code>MsgBox</code> is annoying, two back-to-back is <em>irritating</em> (arguably the two messages could be merged into one). Since this is obviously a long-running process that needs to go through a number of files, consider using a <a href=\"https://rubberduckvba.wordpress.com/2018/01/12/progress-indicator/\" rel=\"nofollow noreferrer\">Progress Indicator</a> to let the user know what's going on, instead of message boxes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T21:11:16.507",
"Id": "436246",
"Score": "0",
"body": "Can you further explain the CreateMonthlyReportingBook Sub you have typed up. I don't understand the yeartoprocess variable's purpose and I get a compile error(wrong number of arguments or invalid property assignment) which I can't fix because I don't understand why we're passing a value to the other subs in the first place. If I remove the variable I get a different compile error(expected function or variable). If I completely remove the variable and the if not statements then I can get it to compile and run fine, but im missing the error checking"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T21:29:00.613",
"Id": "436252",
"Score": "1",
"body": "@NickHasler edited to clarify - `yearToProcess` is a `ByRef` output parameter; if the function returns `True` then it's valid and usable. `CreateYearFolder` would also be a `Function`, that returns `True` when everything is in place and good to go, `False` otherwise (whatever the reason is). Parameters should be `ByVal` everywhere, except in `PromptForYearToProcess` where it's passed `ByRef`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T22:30:28.800",
"Id": "436256",
"Score": "0",
"body": "Thank you again for your help"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:44:59.263",
"Id": "224824",
"ParentId": "224766",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T22:15:09.447",
"Id": "224766",
"Score": "3",
"Tags": [
"beginner",
"vba",
"excel"
],
"Title": "Updating yearly reporting templates, ideally before the next year starts"
}
|
224766
|
<p>The simple program reads in some channel data and parameters from text files and should be able to generically transform the data using natural math syntax.</p>
<p>I am primarily concerned about performance. Any improvements in readability, correctness, and defensive coding style will also be appreciated.</p>
<p>main.cpp:</p>
<pre><code>#include <string>
#include <iostream>
#include <stdexcept>
#include "channel.hpp"
#include "parameter.hpp"
using namespace std;
using namespace string_literals;
using namespace channel_processing_system;
int main()
{
try
{
Channel<double> X("channels.txt"s, ',');
Parameters<double> parameters("parameters.txt"s, ',');
Channel<double> Y = X * parameters['m'] + parameters['c'];
Channel<double> A = 1.0 / X;
Channel<double> B = A + Y;
parameters.InsertParameter('b', B.Mean());
Channel<double> C = A + parameters['b'];
std::cout << "The value of b is: " << parameters['b'] << "\n";
return 0;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Program terminated due to an unhandled exception." << std::endl;
}
return -1;
}
</code></pre>
<p>channel.hpp:</p>
<pre><code>#include <vector>
#include <string>
#include <fstream>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <numeric>
#include <stdexcept>
#include <algorithm>
namespace channel_processing_system
{
template <typename DataType>
class Channel
{
const std::string input_file_;
const char delimiter_ = ',';
std::vector<DataType> data_;
char channel_name_;
void ReadFile()
{
try
{
assert(!input_file_.empty());
std::fstream channel(input_file_);
if (!channel.good())
throw std::runtime_error("Could not open channel input file: " + input_file_);
channel >> std::skipws;
channel >> channel_name_;
assert(channel_name_ >= 'A' && channel_name_ <= 'Z');
DataType value;
char delimiter;
while (channel >> delimiter >> value && delimiter == delimiter_)
{
data_.emplace_back(value);
};
assert(data_.size() > 0); // Reading channel from file was not successful
}
catch (const std::exception& e)
{
throw std::runtime_error("Something went wrong whilst trying to parse channel input file: " + std::string(e.what()));
}
}
public:
Channel() = default;
Channel(const std::string& input_file, const char delimiter) :
input_file_(input_file), delimiter_(delimiter)
{
ReadFile();
}
template<typename RHSType>
Channel operator+(const RHSType& rhs)
{
Channel result;
result.data_.reserve(data_.size());
if constexpr (std::is_scalar_v<RHSType>)
{
std::for_each(data_.begin(), data_.end(),
[&](const auto& src) { result.data_.emplace_back(src + rhs); });
}
else
{
if constexpr (std::is_same_v<RHSType, Channel<DataType>>)
{
std::transform(rhs.data_.begin(), rhs.data_.end(), this->data_.begin(),
std::back_inserter(result.data_), std::plus<DataType>());
}
else
{
static_assert(false, "An adaption of operator+ is not provided for the instantiated type.");
}
}
return result;
}
template<typename Scalar>
Channel operator*(const Scalar& rhs)
{
static_assert(std::is_scalar_v<Scalar>, "The operator* is only defined for arguments of scalar type.");
Channel result;
result.data_.reserve(data_.size());
std::for_each(data_.begin(), data_.end(),
[&](const auto& src) { result.data_.emplace_back(src * rhs); });
return result;
}
DataType Mean() const
{
assert(data_.size() > 0);
return std::accumulate(data_.begin(), data_.end(), 0.0) / data_.size();
}
template <typename DataType_, typename Scalar> friend Channel<DataType_> operator/(const Scalar& lhs, const Channel<DataType_>& rhs);
template <typename DataType_> friend std::ostream& operator<<(std::ostream& os, Channel<DataType_> rhs);
};
template <typename DataType, typename Scalar>
Channel<DataType> operator/(const Scalar& lhs, const Channel<DataType>& rhs)
{
static_assert(std::is_scalar_v<Scalar>, "The non-member operator/ is only defined for arguments of scalar type.");
assert(!std::any_of(rhs.data_.begin(), rhs.data_.end(),
[](const auto& src) {return src == (DataType)0; }));
Channel<DataType> result;
result.data_.reserve(rhs.data_.size());
std::for_each(rhs.data_.begin(), rhs.data_.end(), [&](const auto& src) { result.data_.emplace_back(lhs / src); });
return result;
}
template <typename DataType>
std::ostream& operator<<(std::ostream& os, Channel<DataType> rhs)
{
os << "Channel " << rhs.channel_name_ << ": ";
for (const auto& element : rhs.data_)
{
os << element << ", ";
}
os << std::endl;
return os;
}
}
</code></pre>
<p>parameter.hpp:</p>
<pre><code>#pragma once
#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <utility>
#include <stdexcept>
namespace channel_processing_system
{
template <typename ValueType, typename KeyType = char>
class Parameters
{
const std::string input_file_;
const char delimiter_ = ',';
std::map<KeyType, ValueType> parameters_;
void ReadFile()
{
try
{
assert(!input_file_.empty());
std::fstream file(input_file_);
if (!file.good())
throw std::runtime_error("Could not open parameter input file: " + input_file_);
std::string line;
while (std::getline(file, line))
{
assert(line.size() >= 3);
std::stringstream line_ss{ line };
line_ss >> std::skipws;
char name;
line_ss >> name;
assert(name >= 'a' && name <= 'z');
char delimiter;
ValueType value;
line_ss >> delimiter >> value;
assert(delimiter == delimiter_);
InsertParameter(name, value);
}
}
catch (const std::exception& e)
{
throw std::runtime_error("Something went wrong whilst trying to parse parameter input file: " + std::string(e.what()));
}
}
public:
Parameters() = delete;
Parameters(const std::string& input_file, const char delimiter)
: input_file_(input_file), delimiter_(delimiter)
{
ReadFile();
}
ValueType operator[](const KeyType& key) const { return parameters_.at(key); }
void InsertParameter(const KeyType& key, const ValueType& value)
{
const auto check = parameters_.insert(std::make_pair(key, value));
assert(check.second != false); // Tried to insert parameter: key which already exists
}
};
}
</code></pre>
<p>Example test data:</p>
<p>channel.txt</p>
<pre><code>X, 0.814723686393179, 0.905791937075619, 0.126986816293506, 0.913375856139019, 0.63235924622541, 0.0975404049994095, 0.278498218867048, 0.546881519204984, 0.957506835434298
</code></pre>
<p>parameter.txt</p>
<pre><code>m, 3
c, -1
</code></pre>
<p>I have used a small set for this example, but it will need to operate on much larger data sets.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T03:14:14.850",
"Id": "436051",
"Score": "5",
"body": "Can you provide some test cases so that we can get an idea of the syntax?"
}
] |
[
{
"body": "<p>I don't see anything obviously slow, but neither do I see high performance code or multi-threaded compute. It's just straight forward loops.</p>\n\n<p>If you care about performance you should use some math library that uses SSE/AVX/other types of SIMD- instructions to implement data level parallelism. Then you can shard your input data so that you can split the work out over many threads. The number of threads should be CPU threads + 1 in order to maximally exploit instruction level parallelism.</p>\n\n<p>There are many good libraries out there. Personally, I use <a href=\"http://eigen.tuxfamily.org/index.php?title=Main_Page\" rel=\"nofollow noreferrer\">Eigen</a> by default because it performs well, has a syntax that I like and is header only, no need to worry about linking.</p>\n\n<p>In your case, your Channel class can be straight up replaced by the Eigen::VectorXd type that's a specialization of a Nx1 matrix. In general your application seems to translate well to matrix operations and will easily translate to using some linear algebra library.</p>\n\n<p>I'm typing on a phone so I'll stop short of reviewing the code for other aspects as I believe that you should throw most of it away and use a library as noted above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:29:12.190",
"Id": "436143",
"Score": "0",
"body": "I like your new version - thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T10:17:42.450",
"Id": "224802",
"ParentId": "224772",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:34:20.277",
"Id": "224772",
"Score": "3",
"Tags": [
"c++",
"c++17"
],
"Title": "Performance improvements in C++ channel transformer code"
}
|
224772
|
<p>I have a lot of problems making this code look more elegant or to reduce its size. The algorithm is mostly copied from the pseudocode of <a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail" rel="noreferrer">wikipedia page</a>. The difference is I prepare my string with the <code>tokenSplit</code> method.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace YardVer3
{
class Program
{
public class Token
{
public Token()
{
Value = string.Empty;
Info = '?';
Precedence = -1;
}
public Token(string text)
{
Value = text;
}
public string Value;
public char Info; //d - digit f-function r,l - right/left operator e- unHandled
public int Precedence;
}
static void Main(string[] args)
{
string inLine = "3 + 4 × 2 ÷ ( 1 − 5 ) ^ 2 ^ 3";
Token[] lineToken = new Token[inLine.Length];
for (int i = 0; i < lineToken.Length; i++)
{
lineToken[i] = new Token();
}
int tokenIndex = 0;
tokenIndex = tokenSplit(inLine, tokenIndex, lineToken);
//Start of Shunting Yard Algorithm(Referenced by Wikipedia PseudoCode)
Queue<Token> rpnLine = new Queue<Token>();
Stack<Token> opStack = new Stack<Token>();
for (int i = 0; i < tokenIndex; i++)
{
switch (lineToken[i].Info)
{
case 'd':
rpnLine.Enqueue(lineToken[i]);
break;
case 'f':
opStack.Push((lineToken[i]));
break;
case '(':
opStack.Push(new Token("("));
break;
case 'l':
case 'r':
if (opStack.Count>0)
{
Token t = opStack.Peek();
while ( t.Info == 'f' ||
(t.Precedence > lineToken[i].Precedence) ||
(t.Precedence == lineToken[i].Precedence && t.Info == 'l'))
{
rpnLine.Enqueue(opStack.Pop());
t = opStack.Peek();
}
}
opStack.Push(lineToken[i]);
break;
case ')':
while (opStack.Count > 0)
{
if (opStack.Peek().Value != "(")
{
rpnLine.Enqueue(opStack.Pop());
}
else
{
opStack.Pop();
break;
}
}
break;
default:
Console.WriteLine("Problem Accured");
break;
}
}
while (opStack.Count >0)
{
rpnLine.Enqueue(opStack.Pop());
}
Console.WriteLine(inLine);
while (rpnLine.Count > 0)
{
Console.Write(rpnLine.Dequeue().Value);
Console.Write(' ');
}
Console.WriteLine();
}
private static int tokenSplit(string inLine, int tokenIndex, Token[] lineToken)
{
Match digit = Regex.Match(inLine, @"\d+\.?\d*");
Match funct = Regex.Match(inLine, @"[a-zA-Z]+");
for (int i = 0; i < inLine.Length; i++)
{
if (char.IsDigit(inLine[i]))
{
i += digit.Length - 1;
lineToken[tokenIndex].Info = 'd';
lineToken[tokenIndex].Value = digit.Value;
tokenIndex++;
digit = digit.NextMatch();
}
else if (char.IsLetter(inLine[i]))
{
i += funct.Length - 1;
lineToken[tokenIndex].Info = 'f';
lineToken[tokenIndex].Value = funct.Value;
tokenIndex++;
funct = funct.NextMatch();
}
else if (inLine[i] != ' ' && inLine[i] != ',')
{
lineToken[tokenIndex] = tokenInfoFill(inLine[i]);
lineToken[tokenIndex].Value = inLine[i].ToString();
tokenIndex++;
}
}
return tokenIndex;
}
public static Token tokenInfoFill(char c)
{
Token temp = new Token();
switch (c)
{
case '+':
case '-':
case '−':
temp.Precedence = 2;
temp.Info = 'l';
return temp;
case '*':
case '×':
case '/':
case '÷':
temp.Precedence = 3;
temp.Info = 'l';
return temp;
case '^':
temp.Precedence = 4;
temp.Info = 'r';
return temp;
case '(':
case ')':
temp.Precedence = -2;
temp.Info = c;
return temp;
default:
return temp;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>Token</code> class looks a lot like a <code>struct</code> (value type) to me. The main difference between a <code>class</code> and a <code>struct</code> is that two <code>class</code>es can have the exact same data and not be considered the same, while two <code>struct</code>s are considered the same if the data values it contains are the same. Additionally, a <code>struct</code> can never be <code>null</code>, and must have a default value (which appears to be your intention based on the default constructor). If this is how this works, you should change this to a <code>struct</code> and override the <code>.Equals</code> and <code>.GetHashCode</code> functions.</p>\n\n<p>Your <code>Token</code> class should also not be a child class of <code>Program</code>. Child classes are typically used when the child is special to the class--perhaps it will only ever be used within that class, or something.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>string inLine = \"3 + 4 × 2 ÷ ( 1 − 5 ) ^ 2 ^ 3\";\nToken[] lineToken = new Token[inLine.Length];\n</code></pre>\n</blockquote>\n\n<p>Here, you create an array of tokens for each character in the input. You don't appear to account for spaces anywhere, so your array is nearly twice as large as it needs to be. You could use a <code>List</code> here, or a stack or a queue structure, if you only use it in a LIFO or FIFO structure; that would dynamically resize as you pushed tokens to it.</p>\n\n<p>Alternately, you could exclude tokens you don't want from the size. Reading your code, it looks like <code>' '</code> (space) and <code>','</code> (comma) are excluded. You could do <code>inLine.Where(c => c != ' ' && c != ',').Count()</code>, or something.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>for (int i = 0; i < lineToken.Length; i++)\n{\n lineToken[i] = new Token();\n}\n</code></pre>\n</blockquote>\n\n<p>Here, you initialize each item to a non-null <code>Token</code> immediately. If you use a <code>struct</code>, this would be initialized to a non-null default value by default.</p>\n\n<hr>\n\n<blockquote>\n <p><code>private static int tokenSplit(string inLine, int tokenIndex, Token[] lineToken)</code></p>\n</blockquote>\n\n<p>Using <code>camelCase</code> is a Java thing. C# conventions dictate <code>PascalCase</code> for function names.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>case '+':\ncase '-':\ncase '−':\n</code></pre>\n</blockquote>\n\n<p>No need to duplicate a <code>case</code> value.</p>\n\n<hr>\n\n<p>In <code>tokenInfoFill</code>, you pass in a <code>char</code> value. Then you create an empty token, <code>switch</code> over the passed-in value, and assign the <code>Precedence</code> and <code>Info</code> values. Then return this newly-created token and assign the <code>Value</code> to <code>char</code> value you passed in. I would assign the <code>Value</code> when you create the token as well, to make this cleaner for the caller.</p>\n\n<p>Additionally, I would not use a <code>switch</code> here. It's not the worst option--certainly better than <code>if</code>s, but I would use a dictionary and C# 7's value tuples.</p>\n\n<pre><code>private readonly Dictionary<char, (int precedence, char info)> dict = new Dictionary<char, (int precedence, char info)>\n{\n ['+'] = (2, 'l'),\n // ...\n};\n\n// in your method, you can deconstruct the tuple automatically\n(temp.Precedence, temp.Info) = dict[c];\n</code></pre>\n\n<hr>\n\n<p>Finally, I would not use unique <code>char</code>s for the info flag. I would use an <code>enum</code>.</p>\n\n<pre><code>enum Info\n{\n Unknown = 0, // default value\n Digit = 1,\n Function = 2,\n Operator = 3,\n RightParenthesis = 4,\n LeftParenthesis = 5\n}\n</code></pre>\n\n<p>Now you can do <code>temp.Info = Info.Digit</code> and</p>\n\n<pre><code>switch (temp.Info)\n{\n case Info.Digit:\n break;\n}\n</code></pre>\n\n<p>This way, you know exactly what you are looking at by the name. If necessary, you could also create groups of \"info\" flags using bit flags since an <code>enum</code> is an <code>int</code> behind the scenes (by default, that is--you can override that and make it a <code>short</code> or <code>long</code> or other numeric type).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:36:15.923",
"Id": "224811",
"ParentId": "224774",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "224811",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:39:19.537",
"Id": "224774",
"Score": "6",
"Tags": [
"c#",
"algorithm",
"math-expression-eval"
],
"Title": "Shunting-yard Algorithm, implemented based on reference pseudocode"
}
|
224774
|
<p>I'm looking for improvements of a code that filter the output of <code>git status --ignored</code> and <code>git status --ignored -bs</code> commands. I feel that it could be more readable but I'm not sure how since I'm a beginner. Please, all your critics and advice are welcome. </p>
<p>This is my code:</p>
<pre><code>function filter(str, regExp) {
const reg = new RegExp(`(?<=${regExp}\\s+)\\S+`, 'gm');
return str.match(reg);
}
function excludingFilter(str, regExp) {
const reg = new RegExp(
`(?<=(^(?!\\s+(?:${regExp}))(?:\\s*.+:\\s+))|(^(?!${regExp}|#)..\\s))[^\\s].+`,
'gm',
);
return str.match(reg);
}
function extractData(str) {
return str.match(/\b.+/gm);
}
function gitStatusToJsonCase1(str) {
const localBranch = str.match(/(?<=## )\w+\S?\w+/g);
const remoteBranch = str.match(/(?<=##.+\.{3}).+/g);
const addedIndex = filter(str, 'A.');
const modifiedIndex = filter(str, 'M.');
const otherIndex = excludingFilter(str, '(A.|M.| .|!!|\\?\\?)');
const modifiedTree = filter(str, '.M');
const otherTree = excludingFilter(str, '(.M|. |!!|\\?\\?)');
const untracked = filter(str, '\\?\\?');
const ignored = filter(str, '!!');
const json = {
branch: {
local: localBranch,
remote: remoteBranch,
},
index: {
added: addedIndex,
modified: modifiedIndex,
other: otherIndex,
},
tree: {
modified: modifiedTree,
untracked,
ignored,
other: otherTree,
},
};
return json;
}
function gitStatusToJsonCase2(str) {
const gitStatusRegExp = new RegExp(
`On\\sbranch\\s(?<local>.+)\n(?:Your.*'(?<remote>.+)'.)?(?:\\s+)?(?:Changes\\st.+\\s+.+e\\)\n+(?<stage>(?:.+\n)+))?(?:\\s+)?(?:Changes\\sn.+\\s+.+\\s+.+y\\)\n+(?<tree>(?:.+\n)+))?(?:\\s+)?(?:Untracked.+\n\\s+.+\n+(?<untracked>(?:.+\n)+))?(?:\\s+)(?:Ignored.+\n\\s+.+\n+(?<ignored>(?:.+\n)+))?`,
'gm',
);
const groupedData = gitStatusRegExp.exec(str).groups;
const localBranch = groupedData.local;
const remoteBranch = groupedData.remote;
const addedIndex = filter(groupedData.stage, 'new file:');
const modifiedIndex = filter(groupedData.stage, 'modified:');
const otherIndex = excludingFilter(groupedData.stage, '(modified|new)');
const modifiedTree = filter(groupedData.tree, 'modified:');
const otherTree = excludingFilter(groupedData.tree, 'modified:');
const untracked = extractData(groupedData.untracked);
const ignored = extractData(groupedData.ignored);
const json = {
branch: {
local: localBranch,
remote: remoteBranch,
},
index: {
added: addedIndex,
modified: modifiedIndex,
other: otherIndex,
},
tree: {
modified: modifiedTree,
untracked,
ignored,
other: otherTree,
},
};
return json;
}
console.log('TTTTTTTTTTTT git status --ignored -bs TTTTTTTTTTTTTTTT');
console.log(gitStatusToJsonCase1(cases.C));
console.log('TTTTTTTTTTTT git status --ignored TTTTTTTTTTTTTTTT');
console.log(gitStatusToJson(cases.D));
module.exports = { gitStatusToJsonCase1, gitStatusToJson };
</code></pre>
<p>The git status outputs that I'm filtering are like the following:</p>
<p><code>git status --ignored</code>:</p>
<pre><code>On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: a1
new file: prueba2
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: package.json
Untracked files:
(use "git add <file>..." to include in what will be committed)
prueba.txt
test2
Ignored files:
(use "git add -f <file>..." to include in what will be committed)
node_modules/
</code></pre>
<p><code>git status --ignored -bs</code>:</p>
<pre><code>## master...origin/master
A a1
M package.json
A prueba2
?? prueba.txt
?? test1
!! node_modules/
</code></pre>
<p>And my results are like this:</p>
<pre><code>{ branch: { local: [ 'feature/cleanup' ], remote: undefined },
index:
{ added:
[ 'backend/.eslintrc.json.old', 'frontend/.eslintrc.json.old' ],
modified: [ 'README.md', 'parser-preset.js' ],
other: [ 'frontend/.editorconfig -> frontend/.editorconfig.old' ] },
tree:
{ modified:
[ '.eslintignore',
'deploy/docker-compose.yml',
'frontend/.eslintrc.json.old' ],
untracked: [ 'my-app/', 'package-lock.json', 'test3.txt' ],
ignored:
[ 'backend/dist/',
'backend/node_modules/',
'node_modules/' ],
other: null } }
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T03:55:23.440",
"Id": "224779",
"Score": "1",
"Tags": [
"javascript",
"parsing",
"regex"
],
"Title": "git status parser using regular expressions in javascript"
}
|
224779
|
<p>A coding challenge to write a function <code>sortStack</code> that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. At most one additional stack may be used to hold items; no other data structures may be used to copy or hold the elements.</p>
<p>Stack Class:</p>
<pre><code>class Stack {
constructor() {
this.storage = [];
}
push(item) {
this.storage.push(item);
}
pop() {
return this.storage.pop();
}
peek() {
return this.storage[this.storage.length-1];
}
isEmpty() {
return this.storage.length === 0;
}
printContents() {
this.storage.forEach(elem => console.log(elem));
}
}
</code></pre>
<p>Stack:</p>
<pre><code>const s = new Stack();
s.push(4);
s.push(10);
s.push(8);
s.push(5);
s.push(1);
s.push(6);
</code></pre>
<p>My solution: </p>
<pre><code>const sortStack = (stack) => {
sorted = new Stack();
while (stack.storage.length) {
tmp = stack.pop();
if (tmp >= sorted.peek()) {
sorted.push(tmp);
} else {
while (tmp < sorted.peek()) {
stack.push(sorted.pop());
}
sorted.push(tmp);
}
}
return sorted;
}
sortedStack = sortStack(s);
sortedStack.printContents(); // correctly outputs 1, 4, 5, 6, 8, 10
</code></pre>
<p>This iterative solution returns the correct output on multiple test cases, and there are no missing edge cases or other logical flaws that I can see, however I don't like the nested while-loop. </p>
<p>I want to keep the solution iterative, so how could I go about not having to use the nested while-loop?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:46:15.750",
"Id": "436095",
"Score": "2",
"body": "The description of this challenge needs some work, it is virtually incomprehensible as it is. Also: Should you not be using `!stack.isEmpty()` instead of `stack.storage.length`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T08:41:07.293",
"Id": "436106",
"Score": "0",
"body": "@KIKOSoftware Could you suggest an edit to the challenge description?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T20:28:48.423",
"Id": "436235",
"Score": "1",
"body": "Does a recursive function count as using a data structure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T20:54:06.433",
"Id": "436240",
"Score": "0",
"body": "Problem description verbatim from Lambda School: Write a function sortStack that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure. Lambda School: https://lambdaschool.com/"
}
] |
[
{
"body": "<p>You seem to have some extra code in your function that is not needed. The code below does the same thing as your function:</p>\n\n<pre><code>const sortStack = (stack) => {\n sorted = new Stack();\n while (!stack.isEmpty()) {\n tmp = stack.pop(); \n while (tmp < sorted.peek()) {\n stack.push(sorted.pop());\n }\n sorted.push(tmp);\n }\n return sorted;\n}\n</code></pre>\n\n<p>The reason this also works is that whenever <code>tmp < sorted.peek()</code> returns <code>false</code>, <code>tmp >= sorted.peek()</code> would have returned <code>true</code>. So only one comparison is needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:53:32.070",
"Id": "224792",
"ParentId": "224783",
"Score": "4"
}
},
{
"body": "<p>You have access to the stack array directly so you can copy the unsorted stack it to a new stack and sort it in place using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"noreferrer\"><code>Array.sort</code></a></p>\n\n<pre><code>\"use strict\";\nfunction sortStack(stack) {\n const sorted = new Stack();\n while (!stack.isEmpty()) { sorted.push(stack.pop()) }\n sorted.storage.sort((a, b) => a - b);\n return sorted;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>\"use strict\";\nfunction sortStack(stack) {\n const sorted = new Stack();\n sorted.storage = [...stack.storage].sort((a, b) => a - b);\n return sorted;\n}\n</code></pre>\n\n<p>If they did not want you to access the storage array directly they would have protected it in closure. (well if that crossed their minds)</p>\n\n<p>BTW your should always add <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/strict_mode\" rel=\"noreferrer\"><code>\"use strict\"</code></a> to the top of your javascript code as you have neglected to declare any of your variables, making them all global and setting your self up for some horror bugs.</p>\n\n<p>The use strict directive will not let you use undeclared variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T11:38:18.777",
"Id": "224804",
"ParentId": "224783",
"Score": "5"
}
},
{
"body": "<p>It can be slightly more performant:</p>\n\n<ul>\n<li>Keep track of the number of elements you add back to the original stack</li>\n<li>Empty check</li>\n<li>Add first item if not empty (size of one check)</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> class Stack {\n constructor() {\n this.storage = [];\n this.counts = {\n push: 0,\n pop: 0,\n peek: 0,\n isEmpty: 0\n }\n }\n\n push(item) {\n this.counts.push += 1;\n this.storage.push(item);\n }\n\n pop() {\n this.counts.pop += 1;\n return this.storage.pop();\n }\n\n peek() {\n this.counts.peek += 1;\n return this.storage[this.storage.length - 1];\n }\n\n isEmpty() {\n this.counts.isEmpty += 1;\n return this.storage.length === 0;\n }\n\n printContents() {\n this.storage.forEach(elem => console.log(elem));\n }\n\n printCounts() {\n this.counts.total = 0;\n this.counts.total = Object.values(this.counts).reduce((r, v) => r + v, 0);\n console.log(this.counts);\n }\n }\n\n console.log(\"My implementation\");\n\n const stack1 = new Stack();\n stack1.push(4);\n stack1.push(10);\n stack1.push(8);\n stack1.push(5);\n stack1.push(1);\n stack1.push(6);\n\n const sorted1 = sortStack1(stack1);\n sorted1.printContents();\n stack1.printCounts();\n sorted1.printCounts();\n\n console.log(\"Accepted implementation\");\n\n const stack2 = new Stack();\n stack2.push(4);\n stack2.push(10);\n stack2.push(8);\n stack2.push(5);\n stack2.push(1);\n stack2.push(6);\n\n const sorted2 = sortStack2(stack2);\n sorted2.printContents();\n stack2.printCounts();\n sorted2.printCounts();\n\n function sortStack1(stack) {\n const sorted = new Stack();\n if (stack.isEmpty()) // always return a new instance\n return sorted;\n // add first element\n sorted.push(stack.pop());\n while (!stack.isEmpty()) {\n let removeCount = 0;\n const temp = stack.pop(); // element to add\n // move to other stack\n for (removeCount = 0; temp < sorted.peek(); removeCount += 1)\n stack.push(sorted.pop());\n // push new element\n sorted.push(temp);\n // push back to sorted\n for (let i = 0; i < removeCount; i += 1)\n sorted.push(stack.pop());\n }\n return sorted;\n }\n\n function sortStack2(stack) {\n sorted = new Stack();\n while (!stack.isEmpty()) {\n tmp = stack.pop();\n while (tmp < sorted.peek()) {\n stack.push(sorted.pop());\n }\n sorted.push(tmp);\n }\n return sorted;\n }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper {\n top: 0 !important;\n max-height: 100vh !important;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>My function is labeled <code>sortStack1</code>.</p>\n\n<p><strong>Note:</strong> These performance enhancements probably don't matter that much.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:04:41.003",
"Id": "224820",
"ParentId": "224783",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "224792",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T05:46:45.163",
"Id": "224783",
"Score": "3",
"Tags": [
"javascript",
"programming-challenge",
"sorting",
"stack",
"iteration"
],
"Title": "JavaScript Sort Stack Coding Challenge"
}
|
224783
|
<p>I am fairly new to programming. I am writing a script which
gets URLs and parameters through a config and makes http requests to check status, finally push a json string to Open-falcon server.</p>
<p>I am not sure if the logic and writing is reasonable. Could I get some guidance from someone experienced with Go. Really appreciate that. Thanks!</p>
<h3>Code:</h3>
<pre><code>package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/tkanos/gonfig"
)
type Config struct {
Params []struct {
Metric string
URL string
RequestMethod string
Data string
ExpectedString string
Timeout int8
Step int8
}
}
const path = "config/config.json"
var c Config
func parseConfig(path string) Config {
err := gonfig.GetConf(path, &c)
if err != nil {
panic(err)
}
return c
}
type Data struct {
Metric string
Step int8
Value int8
}
var (
l []Data
m Data
)
func makeRequest(c Config) []Data {
for _, i := range c.Params {
m.Metric = i.Metric
m.Step = i.Step
if i.RequestMethod == "get" {
client := &http.Client{Timeout: time.Duration(i.Timeout) * time.Second}
resp, err := client.Get(i.URL)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if i.ExpectedString == "" {
if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
m.Value = 0
} else {
m.Value = 1
}
} else {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
if strings.Contains(string(body), i.ExpectedString) {
m.Value = 0
} else {
m.Value = 1
}
}
} else {
client := http.Client{Timeout: time.Duration(i.Timeout) * time.Second}
resp, err := client.Post(i.URL, "application/json", strings.NewReader(i.Data))
if err != nil {
panic(err)
}
defer resp.Body.Close()
if i.ExpectedString == "" {
if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
m.Value = 0
} else {
m.Value = 1
}
} else {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
if strings.Contains(string(body), i.ExpectedString) {
m.Value = 0
} else {
m.Value = 1
}
}
}
l = append(l, m)
}
fmt.Println(l)
return l
}
type item struct {
Endpoint string `json:"endpoint"`
Metric string `json:"metric"`
Timestamp int64 `json:"timestamp"`
Step int8 `json:"step"`
Value int8 `json:"value"`
CounterType string `json:"counterType"`
Tags string `json:"tags"`
}
type message struct {
Item []item `json:"item"`
}
func prepare(d message) {
apiurl := "http://XXX.XXX.XXX.XXX:1988/v1/push"
jsonStr, _ := json.Marshal(d.Item)
req, err := http.NewRequest("POST", apiurl, bytes.NewBuffer([]byte(jsonStr)))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
}
func pushToFalcon(l []Data) {
for _, i := range l {
var v item
hostName, _ := os.Hostname()
v.Endpoint = hostName
v.Timestamp = time.Now().Unix()
v.Step = i.Step
v.CounterType = "GAUGE"
v.Tags = "service=intranet_service"
v.Metric = i.Metric
v.Value = i.Value
var o message
o.Item = append(o.Item, v)
prepare(o)
}
}
func main() {
parseConfig(path)
makeRequest(c)
pushToFalcon(l)
}
</code></pre>
<h3>Config:</h3>
<pre><code> {
"Params" : [
{
"Metric" : "Test",
"URL" : "http://www.google.com",
"RequestMethod" : "get",
"Data" : "",
"ExpectedString" : "",
"Timeout" : 10,
"Step" : 60
},
{
"Metric" : "Test2",
"URL" : "https://www.baidu.com",
"RequestMethod" : "post",
"Data" : "datapostes",
"ExpectedString" : "haha",
"Timeout" : 10,
"Step" : 60
}
]
}
</code></pre>
|
[] |
[
{
"body": "<p>Not a full review, but several issues pop up at a quick scan:</p>\n\n<ul>\n<li><p>Avoid <code>panic</code>, it's meant for reporting a bug in the program (e.g. dividing by zero, failing a bounds check, dereferencing a nil pointer, etc) and not for user errors (e.g. a failure to complete an HTTP request).</p>\n\n<p>Panics also produce stack traces by default. Users should (almost) never get shown stack traces but instead a simple error report (e.g. if in unix you do <code>ls /non-existant-dir</code> you don't get a stack trace of the internals of the ls command but a report that the directory <code>/non-existant-dir</code> does not exist).</p></li>\n<li><p><code>defer</code> should almost never be used within a loop. The deferred function doesn't run until the enclosing function returns/exits. Here you should be calling <code>resp.Body.Close</code> on each loop iteration before the next one.</p></li>\n<li><p>Avoid using global variables. Here there is no reason that <code>l</code> and <code>m</code> cannot be local to <code>makeRequest</code>.</p></li>\n<li><p>From the <code>net/http</code> documentation:</p>\n\n<blockquote>\n <p>Clients and Transports are safe for concurrent use by multiple\n goroutines and for efficiency should only be created once and re-used.</p>\n</blockquote>\n\n<p>You create a new <code>http.Client</code> on each loop iteration. At minimum you could create just one outside of the loop and then set <code>client.Timeout</code> in each iteration.</p></li>\n<li><p>You repeat a lot of code in each branch of the <code>if i.RequestMethod == \"get\"</code>. I'd instead conditionally create a nil or non-nil <code>body</code> and use a single <code>req, err := http.NewRequest(i.RequestMethod, i.URL, body)</code> and <code>client.Do(req)</code>.</p></li>\n<li><p>Never ignore errors like this:</p>\n\n<blockquote>\n <p><code>jsonStr, _ := json.Marshal(d.Item)</code></p>\n</blockquote>\n\n<p>Either handle/report/return the error as regular or if the surrounding function doesn't have (and shouldn't have) an error return <strong>and</strong> if the code should never fail (e.g. the code is constructing a value that should always be marshallable) then a panic for <code>err != nil</code> is reasonable (i.e. if someone should change the code later that json.Marshal suddenly fails they'll get a panic telling them where they messed up rather than strange failures later on).</p></li>\n<li><p>Instead of\n<code>bytes.NewBuffer([]byte(jsonStr))</code>\ndo\n<code>strings.NewReader(jsonStr)</code></p>\n\n<p>In general, try and avoid or limit <code>[]byte</code> <-> <code>string</code> conversions as they require allocations.</p></li>\n<li><p><code>Config</code> should probably be passed around as a pointer, <code>*Config</code>. Either that or it's <code>Params</code> field should be a slice of pointers (<code>[]*struct</code>). As-is if there the slice was 100 items each time it's passed 100×5 strings need to be copied (which only copies a pointer to the string, but it's still O(n)).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T05:57:12.373",
"Id": "438300",
"Score": "0",
"body": "Thank you for your guidance!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-31T13:21:25.240",
"Id": "225268",
"ParentId": "224789",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "225268",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:21:37.547",
"Id": "224789",
"Score": "1",
"Tags": [
"beginner",
"json",
"go",
"http",
"status-monitoring"
],
"Title": "HTTP status monitoring"
}
|
224789
|
<p>In a part of the project, I had to implement a solution for encapsulation of byte arrays. We do use ssh and secure ports for socket connection but I was in need of an extra layer of protection against man-in-the-middle attacks or a mechanism to drop packages rather fast before reading all the package content. (In case somebody sends an array with 10k elements, continuously to make denial of service). So I created this library which might help me in my case. </p>
<p><a href="https://github.com/skywarth/LiteByteCapsule" rel="nofollow noreferrer">Project repo</a> for further details.</p>
<p><strong>CapsuleConstant Class:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace LiteByte{
/// <summary>
/// Class to generate instances for capsulation constants.
/// </summary>
public class CapsuleConstant : IComparable<CapsuleConstant>
{
private static RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
private byte val;
private int position;//0 is first
private bool head;
/// <summary>
/// Value property of an CapsuleConstant instance. Byte value for constant.
/// </summary>
public byte Val { get => val; set => val = value; }
/// <summary>
/// Position of the constant related to the start position parameter(head). Ex: if position is:0 and head=true, this constant will be the first element in the capsule.
/// </summary>
public int Position { get => position; set => position = value; }
/// <summary>
/// Property to indicate counting for position from start(head) or counting from the end(tail) of the capsule. Ex:Head:false, position:0 will be the last element of the capsule.
/// </summary>
public bool Head { get => head; set => head = value; }
/// <summary>
/// Base constructor of CapsuleConstant class to initiate instances.
/// </summary>
/// <param name="value"></param>
/// <param name="position"></param>
/// <param name="head"></param>
public CapsuleConstant(byte value, int position, bool head)
{
this.val = value;
if (position < 0)
{
throw new ArgumentOutOfRangeException();
}
this.position = position;
this.head = head;
}
private CapsuleConstant(byte value,int headCounter, int tailCounter,bool head)
{
this.val = value;
if (head)
{
this.position = headCounter;
}
else
{
this.position = tailCounter;
}
this.head = head;
}
/// <summary>
///
/// </summary>
/// <param name="amount">Values which vary from 1 to int.max()</param>
/// <returns></returns>
public static Stack<CapsuleConstant> GenerateCapsulationConstants(int amount)
{
try
{
uint unsignedAmount = Convert.ToUInt32(amount);
}
catch (Exception)
{
throw new ArgumentOutOfRangeException();
}
Stack<CapsuleConstant> capsuleConstants = new Stack<CapsuleConstant>();
byte[] randomHolder = new byte[1];
Random rnd = new Random();
int headCounter = -1;
int tailCounter = -1;
bool head;
for (int i = 0; i < amount; i++)
{//TODO stack to string conversion for console writeline, string
rngCsp.GetBytes(randomHolder);
if (rnd.NextDouble() >= 0.5)
{
head = true;
headCounter++;
}
else
{
head = false;
tailCounter++;
//TODO method for searching capsulation stack for certain stuff
}
capsuleConstants.Push(new CapsuleConstant(randomHolder[0], headCounter, tailCounter, head));
}
return capsuleConstants;
}
/// <summary>
/// Implementation of IEnumarable
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(CapsuleConstant other)
{
return this.position.CompareTo(other.position);
}
}
}
</code></pre>
<p><strong>Encapsulation method:</strong></p>
<pre><code>public byte[] ConvertToSyntax(byte[] infactData)
{
if (infactData == null)
{
throw new ArgumentNullException("infactData", "Byte array parameter infactData cannot be null");
}
Stack<CapsuleConstant> capsuleConstantsClone = StackClone<CapsuleConstant>(capsulationConstants);
int capsuleSize = infactData.Length + capsuleConstantsClone.Count;
byte[] capsule = new byte[capsuleSize];
while (capsuleConstantsClone.Count != 0)
{
CapsuleConstant constant = capsuleConstantsClone.Pop();
if (constant.Head)
{
capsule[constant.Position] = constant.Val;
}
else
{
capsule[(capsule.Length - 1) - constant.Position] = constant.Val;
}
}
CapsuleConstant maxHead = (from x in capsulationConstants where x.Head == true select x).Max();
Array.Copy(infactData, 0, capsule, maxHead.Position + 1, infactData.Length);
return capsule;
}
</code></pre>
<p><strong>Example usage as follows:</strong></p>
<pre><code>Stack<CapsuleConstant> constants=CapsuleConstant.GenerateCapsulationConstants(100);
LiteByteCapsule lite=new LiteByteCapsule(constants);
byte[] innerPackage={99,255,0,35,42};
byte[] capsule=lite.ConvertToSyntax(innerPackage);
byte[] decapsulated=lite.CheckSyntax(capsule);
</code></pre>
<p>Unit Test of CheckSyntax (Using XUnit and no mock preset). It takes the most time among other tests. (~80 ms, other tests take about ~1ms. included in repository) </p>
<pre><code>[Fact]
public void CheckSyntax_Base()
{
int amount = 100;
LiteByteCapsule lite = new LiteByteCapsule(CapsuleConstant.GenerateCapsulationConstants(amount));
byte[] package = { 99, 0, 255, 12, 33, 54, 123 };
byte[] capsule=lite.ConvertToSyntax(package);
byte[] inner=lite.CheckSyntax(capsule);
Assert.NotNull(inner);
Assert.NotEmpty(inner);
Assert.Equal(inner.Length, package.Length);
Assert.Equal(package, inner);
}
</code></pre>
<p>Current unit tests report no error. But i want to make it better. Because in case of encapsulation and de-encapsulation of a byte array for 1000 times it takes ~80ms. What can i improve, or should i change the whole structure and approach to the problem ? </p>
<p>Any idea and feedback helps. Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:24:13.420",
"Id": "436087",
"Score": "2",
"body": "Code behind a link can be useful as additional context. But you should at least include the code you want get reviewed in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:24:58.940",
"Id": "436088",
"Score": "1",
"body": "Understood, thanks for the info. Editing now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:31:03.520",
"Id": "436089",
"Score": "1",
"body": "Thanks for the update. You also mention you have unit tests. It would be most helpful if you would include them, so reviewers get more context to help you out. And try also to include source code of _CapsuleConstant_ :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:50:56.650",
"Id": "436096",
"Score": "2",
"body": "My bad, thought that it might be bloating to include all that code in snippet. Updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T11:16:09.313",
"Id": "436125",
"Score": "2",
"body": "I don't think your post and github readme really explain what your code actually does, but apparently it's prepending and appending some random bytes to a message. How does the receiving end know which bytes to expect? And how does this protect against a MitM attack?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:09:35.627",
"Id": "436139",
"Score": "0",
"body": "You also pass the capsule constant stack to the receiver separately (e.g using in JSON format). That way they can de-serialize the JSON into capsule constant object which is used for CheckSyntax method (de-capsulation). \n\nAbout the MitM, i thought that if there was some let's say prefix and suffixes for the actual package it would be difficult to guess at which index does the actual package start. Little example: \nActual package: {91,54,250,255}\nEncapsulated: {0,92,115,102,91,54,250,255,13,42} \nEncapsulated package is being sent over socket."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T13:11:53.943",
"Id": "436152",
"Score": "0",
"body": "That constants message can also be intercepted, and a '(randomness){json/xml/etc}(randomness)' message shouldn't be too difficult to interpret (and modify). I don't think this adds any actual security, only obscurity. Why not encrypt the message and use a MAC for authentication and tampering protection?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T04:54:52.473",
"Id": "436278",
"Score": "0",
"body": "regardless of using digital signatures and/or encrypting a message, a checksum could be appended that provides fast reliability of a message: https://en.wikipedia.org/wiki/Cyclic_redundancy_check"
}
] |
[
{
"body": "<h2>Specification</h2>\n\n<p>You have 2 requirements stated below. I see <strong>no reason why to <em>re-invent-the-wheel</em></strong> here. Both requirements can be met with using common practices.</p>\n\n<blockquote>\n <p><em>..or a mechanism to drop packages rather fast\n before reading all the package content. (In case somebody sends an\n array with 10k elements, continuously to make denial of service).</em></p>\n</blockquote>\n\n<p>This should be the top layer that uses a fast algorithm to detect message tampering. I would use a <a href=\"https://en.wikipedia.org/wiki/Cyclic_redundancy_check\" rel=\"nofollow noreferrer\">CRC</a> or any other well-known checksum. This layer acts fast and would already filter out a lot of flooding.</p>\n\n<pre><code>[message] = [content][checksum]\n</code></pre>\n\n<blockquote>\n <p><em>I was in need of an extra layer of protection against\n man-in-the-middle attacks..</em></p>\n</blockquote>\n\n<p>An additional layer is needed that does a thorough security check. Here you could verify confidentiality, authentication and addition message tampering. Multiple strategies and algorithms are available; <a href=\"https://crypto.stackexchange.com/questions/5458/should-we-sign-then-encrypt-or-encrypt-then-sign\">This post talks about strategies (sign vs encrypt)</a>.</p>\n\n<pre><code>[content] = [digest][signature][checksum] // one possible strategy\n</code></pre>\n\n<h2>C# Conventions</h2>\n\n<ul>\n<li>Use properties with backing fields: <code>public byte Val { get => val; set => val = value; }</code> -> <code>public byte Value { get; set; }</code></li>\n<li>Don't use abbreviations for member names: <code>Val</code> -> <code>Value</code></li>\n<li>Your <code>int</code> to <code>uint</code> conversion seems convoluted; which range of values would you allow, is unchecked conversion an option for you, why not use <code>uint</code> to begin with?</li>\n<li>Prefer using <code>var</code>: <code>var capsuleConstants = new Stack<CapsuleConstant>();</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T10:32:05.537",
"Id": "436318",
"Score": "0",
"body": "Neat and good points, i like it. I'll certainly do updates according to your evaluations. But i have a concern:\nWhat is the proper way to implement \"calculation of byte array\" ? I looked it up but there is various solutions for that and not sure which is the best to calculate CRC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T10:35:39.527",
"Id": "436321",
"Score": "1",
"body": "For the first layer, that should be fast, I suggest CRC32. For the deeper layer you will find suggestions in the comments to your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T10:40:16.950",
"Id": "436322",
"Score": "1",
"body": "I see. Thanks, appreciated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T05:35:23.097",
"Id": "224858",
"ParentId": "224790",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224858",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:21:48.637",
"Id": "224790",
"Score": "3",
"Tags": [
"c#",
".net",
"security",
"cryptography",
"socket"
],
"Title": "Capsulation solution for byte arrays"
}
|
224790
|
<p>The challenge: </p>
<p>Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.</p>
<p>Example: </p>
<p>If <code>{"2": ["a", "b", "c"], 3: ["d", "e", "f"], …}</code>
then <code>"23"</code> should return <code>["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]</code>.</p>
<p>My iterative solution:</p>
<pre><code>const digitMap = (digiStr) => {
const digitMapping = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z']
}
const length = digiStr.length;
if (length === 1) return digitMapping[digiStr]; // in case of single digit strings
const indexes = []; // index addresses of charsets, in order
for (let i = 0; i < length; i++) {
indexes.push(0);
}
let nextI = length === 2 ? 0 : 1; // current spot of nextI in indexes
const possibleStrs = []; // for final answer of possible permutations
let str = '';
let endCount = 0; // if all addresses in indexes are at their end, then break while loop
while (true) {
console.log(indexes);
for (let i = 0; i < length; i++) {
str += digitMapping[digiStr[i]][indexes[i]];
if (indexes[i] === digitMapping[digiStr[i]].length - 1) {
endCount += 1;
}
}
possibleStrs.push(str);
str = '';
if (endCount === length) {
break;
}
endCount = 0;
// increment last item in indexes as long as it < length of corresponding inner char array
if (indexes[indexes.length - 1] < digitMapping[digiStr[digiStr.length - 1]].length - 1) {
indexes[indexes.length - 1] += 1;
}
else {
indexes[indexes.length - 1] = 0;
// increment nextI as long as < length of corresponding inner array
if (indexes[nextI] < digitMapping[digiStr[nextI]].length - 1) {
indexes[nextI] += 1;
}
else {
// otherwise shift position of nextI in indexes array
// if next position of nextI not end of indexes array
// shift nextI 1 spot forward in indexes
if (nextI + 1 < length - 1) {
nextI += 1;
indexes[nextI] += 1;
}
else {
// else reset all indexes to 0, starting from position 1
for (let i = 1; i < indexes.length; i++) {
indexes[i] = 0;
}
// increment first item in indexes
indexes[0] += 1;
nextI = 1; // place nextI at position 1
}
}
}
}
return possibleStrs;
}
console.log(digitMap("2"));
console.log(digitMap("23"));
console.log(digitMap("234"));
console.log(digitMap("2345"));
console.log(digitMap("23456"));
</code></pre>
<p>Produces the correct output for all test cases. Any alternative approaches--recursive or iterative--to cleaning up the conditional logic would be greatly appreciated.</p>
|
[] |
[
{
"body": "<p>Too long for a comment...</p>\n\n<p>The problem as presented seems to have much in common with the string permutations problem in terms of solution structure.</p>\n\n<p>You should be able to do something similar to: <a href=\"https://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string\">https://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string</a> with slight modification to get a compact recursive formulation.</p>\n\n<p>Pseudo code below:</p>\n\n<pre><code>solution(string digits, string prefix=\"\", array<string> outputs)\n if digits empty then\n add prefix to outputs\n else\n currentDigit := digits.get(0)\n remainingDigits := digits.remove(0);\n for each character in listOfCharsForDigit[currentDigit] do\n solution(remainingDigits, prefix+character, outputs)\n endfor\n endif\n</code></pre>\n\n<p>Hope that helps...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:09:15.303",
"Id": "224807",
"ParentId": "224793",
"Score": "2"
}
},
{
"body": "<p>Interesting question;</p>\n\n<p><strong>High Level Overview</strong></p>\n\n<p>The code is close to good, I definitely would not go for a recursive solution. These challenges often have at least 1 test with a really long string.</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>Some of your naming choices are unfortunate:\n\n<ul>\n<li><code>possibleStrs</code> -> I would go for <code>possibleStrings</code>, or <code>combinations</code>, or <code>out</code></li>\n<li>I prefer <code><verb><thing></code> over <code><thing><verb></code>; so <code>mapDigits</code> over <code>digitMap</code> or even <code>generatePossiblePhoneWordCombinations</code></li>\n</ul></li>\n</ul>\n\n<p><strong>Comments</strong></p>\n\n<ul>\n<li>I like your approach to commenting</li>\n</ul>\n\n<p><strong>JSHint.com</strong></p>\n\n<ul>\n<li>Your code is only missing 2 semicolons, consider using <a href=\"http://jshint.com/\" rel=\"nofollow noreferrer\">http://jshint.com/</a> to perfect your code</li>\n</ul>\n\n<p><strong>Production Code</strong></p>\n\n<ul>\n<li>Remove all references to <code>console.log()</code></li>\n<li>You are mixing variable declarations and logic, I would group the variable declarations up front</li>\n</ul>\n\n<p><strong>Alternatives</strong></p>\n\n<ul>\n<li><p>The below could use a built-in function</p>\n\n<pre><code>const indexes = []; // index addresses of charsets, in order\nfor (let i = 0; i < length; i++) {\n indexes.push(0);\n}\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>const indexes = Array(length).fill(0);\n</code></pre></li>\n</ul>\n\n<p><strong>Counter Proposal</strong></p>\n\n<p>The logic you are using afterwards is a little convoluted, and is hard to read. \nIn essence, you can convert the input string to an array, and use that array to keep track of your state.</p>\n\n<pre><code>// \"23\" should return [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\nfunction mapDigits(s){\n\n const digitMapping = {\n 2: ['a', 'b', 'c'],\n 3: ['d', 'e', 'f'],\n 4: ['g', 'h', 'i'],\n 5: ['j', 'k', 'l'],\n 6: ['m', 'n', 'o'],\n 7: ['p', 'q', 'r', 's'],\n 8: ['t', 'u', 'v'],\n 9: ['w', 'x', 'y', 'z']\n }\n\n //Get the digits, ignore ones and zeroes\n let digits = s.split('').filter(i => i > 1);\n let out = [], tmp = [];\n\n //Some shortcuts\n if(!digits.length){\n return out;\n }\n if(digits.length == 1){\n return digitMapping[digits[0]];\n }\n\n //We're still here, prep out and digits (shift modifies digits)\n out = digitMapping[digits.shift()];\n\n while(digits.length){\n const nextLetters = digitMapping[digits.shift()];\n tmp = out;\n out = [];\n tmp.forEach(s => nextLetters.forEach(c => out.push(s+c))); \n }\n\n return out;\n}\n\n\nconsole.log(mapDigits(\"23\"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T17:33:48.233",
"Id": "436198",
"Score": "1",
"body": "As a comment, the approach from @Zefick is very different and superior to our approaches."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:48:45.840",
"Id": "224825",
"ParentId": "224793",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T07:58:42.160",
"Id": "224793",
"Score": "3",
"Tags": [
"javascript",
"programming-challenge",
"combinatorics",
"iteration"
],
"Title": "Challenge: phone keypad to letters - return all possible strings"
}
|
224793
|
<p>The input graph to the bfs function is in the form of edge list representation.</p>
<pre class="lang-py prettyprint-override"><code>from queue import deque
def neighbour(s,visit,que):
for i in l:
if(i[0]==s and i[1] not in visit):
que.append(i[1])
visit.append(i[1])
return que
def bfs(start=0):
que=deque()
visit=[start]
que.append(start)
while(que):
start=que.popleft()
que=neighbour(start,visit,que)
return visit
l=[(0,1),(0,2),(1,2),(2,0),(2,3),(3,3)]
visit=bfs(start=1)
</code></pre>
<p>This is quite inefficient (when it comes to large no. of edges) since in the neighbour function, it iterates through the entire edge-list every time even when many of the vertices in the edges are already visited in the previous function call.</p>
<p>So, a more efficient way would be to pop out the edges once they entered the if-condition so that in the function-call, there are lesser no. of edges to iterate through.</p>
<p>Like this:</p>
<pre><code>if (i[0]==s and i[1] not in visit):
que.append(i[1])
visit.append(i[1])
l.remove(i)
</code></pre>
<p>But the iterator tends to just skip over to the next item in the list after removing a particular edge. Is there a way to implement an user-defined iterator function to improve the performance since reverse-iterators (i.e., _next__() exists but not _reverse__() ) don't exist?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T22:38:23.293",
"Id": "436257",
"Score": "1",
"body": "Are the edges directed or undirected? The edge list in your code has both (0,2) and (2,0), which implies they are directed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T03:01:44.840",
"Id": "436270",
"Score": "0",
"body": "@RootTwo They are directed"
}
] |
[
{
"body": "<p><code>bfs()</code> doesn't actually do anything with the nodes. It just returns a list of the nodes in the order they were visited.</p>\n\n<h3>Data structures</h3>\n\n<p>Each call to <code>neighbors</code> scans the whole edge list. Which, as you point out, is inefficient. So, preprocess the edge list to create data structure that lets you access the neighbors more efficiently.</p>\n\n<p>If you know how many nodes there are in advance, you can do something like this:</p>\n\n<pre><code>from collections import deque\n\ndef neighbors(edge_list, number_of_nodes):\n \"\"\" Build a list such that the list at index `n`\n is the set of the neighbors of node `n`.\n \"\"\"\n\n neighbors_list = [set() for _ in range(number_of_nodes)]\n\n for start_node, end_node in edge_list:\n neighbors_list[start_node].add(end_node) \n\n # if the edges are not directed, then uncomment the next line\n #neighbors_list[end_node].add(start_node) \n\n return neighbors_list\n</code></pre>\n\n<p>If the nodes have strings for labels, or you don;t know in advance how many there are, <code>neighbors()</code> can be modified like so:</p>\n\n<pre><code>from collections import defauldict, deque\n\ndef neighbors(edge_list, number_of_nodes):\n \"\"\" Build a list such that the list at index `n`\n is the set of the neighbors of node `n`.\n \"\"\"\n\n neighbors_list = defaultdict(set)\n\n for start_node, end_node in edge_list:\n neighbors_list[start_node].add(end_node) \n\n # if the edges are not directed, then uncomment the next line\n #neighbors_list[end_node].add(start_node) \n\n return neighbors_list\n</code></pre>\n\n<p>Then <code>bfs</code> can be done like this (using one of the <code>neighbors()</code> above):</p>\n\n<pre><code>def bfs(edge_list, number_of_nodes, start=0):\n neighbors_of = neighbors(edge_list, number_of_nodes)\n que = deque([start])\n visited = {start:True}\n\n while(que):\n node = que.popleft()\n\n neighbor_nodes = neighbors_of[node] - visited.keys()\n que.extend(neighbor_nodes)\n visited.update((neighbor,True) for neighbor in neighbor_nodes)\n\n return list(visited.keys())\n</code></pre>\n\n<p>The above relies on python 3.7 features: </p>\n\n<ol>\n<li>a dictionary returns keys in the order they were added to the dictionary, so list(visited.keys()) returns the nodes in the order they were visited.</li>\n<li>the view returned by <code>dict.keys()</code> behaves like a set, so <code>neighbors_of[node] - visited.keys()</code> returns a set of nodes that are neighbors or <code>node</code> but are not in <code>visited</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T12:53:15.007",
"Id": "436336",
"Score": "0",
"body": "You don't actually need to call `.keys()` most of the time anymore. Iterating over a dict or converting to list automatically does this. You should still use `.items()` and `.values()` where appropriate, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T14:47:04.837",
"Id": "436355",
"Score": "0",
"body": "@HoboProber, you are correct. For example, `.keys()` isn't needed in `return list(visited.keys())` , but it is needed to get the set-like features of a dict view as in `neighbors_of[node] - visited.keys()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:20:40.167",
"Id": "448495",
"Score": "0",
"body": "@RootTwo This would require converting from edge_list to adjacency list type of format. I know how to do in this way, but as I've mentioned in the last line in my question, popping out the edge after it has been visited is more helpful, but doing that will lead to list pointer skipping over to the next element. How to do it in this way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:59:32.203",
"Id": "448540",
"Score": "0",
"body": "Removing items from a list while iterating over it can cause items to be skipped. The list iterator uses an index internally. The first time through the loop, it is at index 0, so the iterator returns list[0]. When list[0] is removed, the remaining items in the list move up one place: list[1] is now list[0], list[2] is now list[1], and so on. The iterator index goes to 1 and returns list[1]. But that is the old list[2], list[1] got skipped. Solutions are to iterate over the list backward, or is to iterate over a copy of the list. There are a lot of related stackoverflow questions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T02:15:59.223",
"Id": "224852",
"ParentId": "224794",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T08:09:50.127",
"Id": "224794",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"breadth-first-search"
],
"Title": "Optimising the BFS"
}
|
224794
|
<p>I'm using the below Python script to port few table data from a remote server (MySQL database) to my data warehouse server (PostgreSQL DB), The script is working fine (I'm using foreign data wrapper), so I thought of asking your help to make it in a more generalised way and if there is any better option for doing it rather than this way.</p>
<p>In this I have to declare the table structure; perhaps I missed a way to do it dynamically without declaring each table structure specifically?</p>
<p>And any other modifications?</p>
<pre><code>import psycopg2
import os
import time
import MySQLdb
import sys
from pprint import pprint
from datetime import datetime
from psycopg2 import sql
from utils.config import Configuration as Config
from utils.postgres_helper import get_connection
from utils.utils import get_global_config
def psql_Source_fetch_and_DestInsert(cnx_msql,cnx_psql,msql, psql, msql_command, psql_command):
print("Function Call..")
msql.execute(msql_command)
for row in msql:
try:
print("Insertion of rows..")
print(row)
psql.execute(psql_command, row)
except psycopg2.Error as e:
print ("Cannot execute the query!!", e.pgerror)
sys.exit("Problem occured with the query!!!")
cnx_psql.commit()
def dB_Fetch():
# MySQLdb connection
try:
source_host = 'magento'
conf = get_global_config()
cnx_msql = MySQLdb.connect(host=conf.get(source_host, 'host'),
user=conf.get(source_host, 'user'),
passwd=conf.get(source_host, 'password'),
port=int(conf.get(source_host, 'port')),
db=conf.get(source_host, 'db'))
except mysql.connector.Error as e:
print ("MYSQL: Unable to connect!", e.msg)
sys.exit(1)
# Postgresql connection
try:
cnx_psql = get_connection(get_global_config(), 'pg_dwh')
except psycopg2.Error as e:
print('PSQL: Unable to connect!\n{0}').format(e)
sys.exit(1)
# Cursors initializations
cur_msql = cnx_msql.cursor()
cur_psql = cnx_psql.cursor()
try:
print("creating table using cursor")
SQL_create_Staging_schema="""CREATE SCHEMA IF NOT EXISTS staging AUTHORIZATION postgres;"""
SQL_create_sales_flat_quote="""DROP TABLE IF EXISTS staging.sales_flat_quote;CREATE TABLE IF NOT EXISTS staging.sales_flat_quote
(
customer_id BIGINT
, entity_id BIGINT
, store_id BIGINT
, customer_email TEXT
, customer_firstname TEXT
, customer_middlename TEXT
, customer_lastname TEXT
, customer_is_guest BIGINT
, customer_group_id BIGINT
, created_at TIMESTAMP WITHOUT TIME ZONE
, updated_at TIMESTAMP WITHOUT TIME ZONE
, is_active BIGINT
, items_count BIGINT
, items_qty BIGINT
, base_currency_code TEXT
, grand_total NUMERIC(12,4)
, base_to_global_rate NUMERIC(12,4)
, base_subtotal NUMERIC(12,4)
, base_subtotal_with_discount NUMERIC(12,4)
)
;"""
SQL_create_sales_flat_quote_item="""DROP TABLE IF EXISTS staging.sales_flat_quote_item;CREATE TABLE IF NOT EXISTS staging.sales_flat_quote_item
(store_id INTEGER
, row_total NUMERIC
, updated_at TIMESTAMP WITHOUT TIME ZONE
, qty NUMERIC
, sku CHARACTER VARYING
, free_shipping INTEGER
, quote_id INTEGER
, price NUMERIC
, no_discount INTEGER
, item_id INTEGER
, product_type CHARACTER VARYING
, base_tax_amount NUMERIC
, product_id INTEGER
, name CHARACTER VARYING
, created_at TIMESTAMP WITHOUT TIME ZONE
,base_row_total NUMERIC
,base_discount_amount NUMERIC
,applied_rule_ids CHARACTER VARYING
);"""
SQL_create_catalog_product_flat_1="""DROP TABLE IF EXISTS staging.catalog_product_flat_1;CREATE TABLE IF NOT EXISTS staging.catalog_product_flat_1
(name CHARACTER VARYING
, sku CHARACTER VARYING
, type_id CHARACTER VARYING
, created_at TIMESTAMP WITHOUT TIME ZONE
, url_path CHARACTER VARYING
, price NUMERIC
, short_description CHARACTER VARYING
, url_key CHARACTER VARYING
, thumbnail_label CHARACTER VARYING
, small_image CHARACTER VARYING
, thumbnail CHARACTER VARYING
);"""
SQL_create_cataloginventory_stock_item="""DROP TABLE IF EXISTS staging.cataloginventory_stock_item;CREATE TABLE staging.cataloginventory_stock_item
(
qty numeric,
max_sale_qty numeric,
stock_status_changed_auto bigint,
notify_stock_qty numeric,
backorders bigint,
is_in_stock bigint,
item_id bigint NOT NULL,
low_stock_date timestamp without time zone,
min_qty numeric,
manage_stock bigint,
min_sale_qty numeric,
product_id bigint
);"""
print("Creating Schema...")
cur_psql.execute(SQL_create_Staging_schema)
print("Creating tables...")
cur_psql.execute(SQL_create_sales_flat_quote)
cur_psql.execute(SQL_create_sales_flat_quote_item)
cur_psql.execute(SQL_create_cataloginventory_stock_item)
cnx_psql.commit();
print("Fetching data from source server")
#select from Magento & insert into DWH: SELECT & INSERT SQL statements are created as PAIRS for looping.
commands = [
("""SELECT qty,max_sale_qty,stock_status_changed_auto,notify_stock_qty,backorders,is_in_stock,
item_id,low_stock_date,min_qty,manage_stock,min_sale_qty,product_id from cataloginventory_stock_item;""",
"""INSERT INTO staging.cataloginventory_stock_item (qty,max_sale_qty,stock_status_changed_auto,notify_stock_qty,backorders,is_in_stock,
item_id,low_stock_date,min_qty,manage_stock,min_sale_qty,product_id)
SELECT %s, %s, %s,%s,%s,%s,%s,%s,%s, %s, %s, %s;"""),
("""SELECT customer_id, entity_id, store_id, customer_email , customer_firstname, customer_middlename
, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at, is_active
, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal
, base_subtotal_with_discount from sales_flat_quote
where is_active=1
AND items_count != '0'
AND DATE_FORMAT(updated_at, '%Y-%m-%d') >= CURDATE();""",
"""INSERT INTO staging.sales_flat_quote (customer_id, entity_id, store_id, customer_email , customer_firstname
, customer_middlename, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at
, is_active, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal
, base_subtotal_with_discount)
SELECT %s, %s, %s,%s,%s,%s,%s,%s,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s;"""),
("""SELECT store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type
,base_tax_amount,product_id,name,created_at,base_row_total,base_discount_amount,applied_rule_ids from sales_flat_quote_item WHERE DATE_FORMAT(updated_at, '%Y-%m-%d') >= CURDATE();""",
"""INSERT INTO staging.sales_flat_quote_item (store_id,row_total,updated_at,qty,sku,free_shipping,quote_id
,price,no_discount ,item_id,product_type,base_tax_amount,product_id,name
,created_at,base_row_total,base_discount_amount,applied_rule_ids)
SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s;""")
,("""SELECT created_at,url_path,price,short_description,url_key,thumbnail_label,small_image,thumbnail
,name,sku,type_id from catalog_product_flat_1;""",
"""INSERT INTO staging.catalog_product_flat_1 (created_at,url_path,price,short_description,url_key,thumbnail_label
,small_image,thumbnail,name,sku,type_id)
SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s;""")
]
for msql_command, psql_command in commands:
psql_Source_fetch_and_DestInsert(cnx_msql,cnx_psql,cur_msql, cur_psql, msql_command, psql_command)
except (Exception, psycopg2.Error) as error:
print ("Error while fetching data from PostgreSQL", error)
finally:
## Closing cursors
cur_msql.close()
cur_psql.close()
## Committing
cnx_psql.commit()
## Closing database connections
cnx_msql.close()
cnx_psql.close()
if __name__ == '__main__':
dB_Fetch()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:19:33.647",
"Id": "436141",
"Score": "0",
"body": "In my opinion, this question is going a bit beyond asking for a review of the code, in asking how to obtain the schema. That is more of a feature request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T07:49:27.000",
"Id": "436302",
"Score": "0",
"body": "@200_successGetting schema is fine, Can you please review this code and let me know what all changes that need to be made on this to make it better?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T08:18:45.967",
"Id": "224795",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"sql",
"mysql",
"postgresql"
],
"Title": "Python script to import MySQL tables to PostgreSQL"
}
|
224795
|
<p>This is a my first Python program, and whilst I am new to Python I would like to keep in good practice </p>
<p>Below is a short program to work out what type a triangle is and if it makes a valid triangle</p>
<p>I have tried to use as little documention for this as possible to try and get used to how things work in Python so I can only imagine the mistakes I have made. However please do mention anything that should have be done better</p>
<pre><code># Determin if triangle is Scalene. Isosceles or equilateral
# Also works out if lengths can make a triangle
from decimal import *
getcontext().prec = 3
getcontext().rounding = ROUND_HALF_UP
#Needs to be divided to re-set decimal place I think
a = Decimal(input("Length of side a = ")) / 1
b = Decimal(input("Length of side b = ")) / 1
c = Decimal(input("Length of side c = ")) / 1
if a != b and b != c and a != c:
print("This is a a Scalene triangle")
triangle_type = 'Scalene'
elif a == b and c == b:
print("This is an Equilateral triangle")
triangle_type = 'Equilateral'
else:
print("This is an Isosceles triangle")
triangle_type = 'Isosceles'
def is_valid_triangle(a, b, c,triangle_type):
if triangle_type == 'Equilateral':
return True #all same lengths will be a valid triangle
elif triangle_type == 'Isosceles' or triangle_type == 'Scalene':
if a == b:
return a + b > c
elif b == c:
return b + c > a
elif a == c:
return a + c > b
else: #This will be the scalene triangle
return a + b > c
else:
return False #Message is unclear as could be lengths are negitive or correct int type not used
print('Is this a valid triangle?', is_valid_triangle(a,b,c,triangle_type))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T16:55:51.420",
"Id": "436190",
"Score": "1",
"body": "_\"so I can only imagine the mistakes I have made\"_ Does it work for your test cases?"
}
] |
[
{
"body": "<p>Add a <a href=\"//stackoverflow.com/q/419163\"><code>__name__ == "__main__"</code> guard</a>, and move the logic into a function separate from the I/O:</p>\n<pre><code>def triangle_type(a, b, c):\n '''Return a string indicating the type of triangle\n (Equilateral, Isosceles, Scalene, Impossible)\n '''\n # implementation here...\n\ndef main():\n getcontext().prec = 3\n getcontext().rounding = ROUND_HALF_UP\n\n #Needs to be divided to re-set decimal place I think\n a = Decimal(input("Length of side a = ")) / 1\n b = Decimal(input("Length of side b = ")) / 1\n c = Decimal(input("Length of side c = ")) / 1\n\n print(f"This is a {triangle_type(a, b, c)} triangle")\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>In the implementation, we can save a lot of "or" tests by sorting the lengths before we start:</p>\n<pre><code>a, b, c = sorted([a, b, c])\n\nif a + b <= c:\n # N.B. automatically catches a < 0, since b <= c\n return 'Impossible'\nif a != b != c:\n return 'Scalene'\nelif a == c:\n return 'Equilateral'\nelse:\n return 'Isosceles'\n</code></pre>\n<hr />\n<h1>Modified code</h1>\n<pre><code>def triangle_type(a, b, c):\n '''\n Return a string indicating the type of triangle\n (Equilateral, Isosceles, Scalene, Impossible)\n '''\n\n a, b, c = sorted([a, b, c])\n\n if a + b <= c:\n return 'Impossible'\n if a != b != c:\n return 'Scalene'\n if a == c:\n return 'Equilateral'\n return 'Isosceles'\n \ndef main():\n a = input("Length of side a: ")\n b = input("Length of side b: ")\n c = input("Length of side c: ")\n print(f"({a}, {b}, {c}) is a {triangle_type(a, b, c)} triangle")\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<hr />\n<h1>Further improvement</h1>\n<p>Use the <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module to write the tests:</p>\n<pre><code>def triangle_type(a, b, c):\n '''\n Return a string indicating the type of triangle\n (Equilateral, Isosceles, Scalene, Impossible)\n\n >>> triangle_type(1, 1, 2)\n 'Impossible'\n >>> triangle_type(-1, -1, -1)\n 'Impossible'\n >>> triangle_type(1, 1.0, 1)\n 'Equilateral'\n >>> triangle_type(1, 2, 2)\n 'Isosceles'\n >>> triangle_type(2, 3, 2)\n 'Isosceles'\n >>> triangle_type(2, 3, 4)\n 'Scalene'\n '''\n\n a, b, c = sorted([a, b, c])\n\n if a + b <= c:\n return 'Impossible'\n if a != b != c:\n return 'Scalene'\n if a == c:\n return 'Equilateral'\n return 'Isosceles'\n\nif __name__ == "__main__":\n import doctest\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T09:25:36.360",
"Id": "436488",
"Score": "0",
"body": "Thanks for your answers, I have marked this one as accepted as it contains the more useful information, however both answers provide good points that I need to improve upon"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T17:53:37.980",
"Id": "224827",
"ParentId": "224810",
"Score": "3"
}
},
{
"body": "<p>A bug (or poorly-specified behaviour):</p>\n\n<p>If we enter an invalid triangle (e.g. <code>1, 2, 4</code>), the program reports that it's scalene, before telling us that it's not a valid triangle. That's a contradiction - if it's not a triangle, it cannot be a scalene triangle!</p>\n\n<p>I recommend performing the <code>is_valid_triangle()</code> test first, and only continuing to classify the triangle if the test is successful.</p>\n\n<p>And don't forget that valid triangles have three <em>positive</em> sides - any negative values should fail the validity test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T08:36:25.987",
"Id": "436482",
"Score": "0",
"body": "little suggestion to test validity of triangle, valid triangles have three positive sides and sum of two side is greater than 3rd side"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T08:52:40.490",
"Id": "436483",
"Score": "1",
"body": "@prashant, the posted code already covers the second part of that test; I'm just drawing attention to the missing part. I hope that's clear!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T09:06:03.877",
"Id": "436484",
"Score": "0",
"body": "didn't went throuh the whole code, my mistake, thanks for commenting out"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T08:30:50.827",
"Id": "224955",
"ParentId": "224810",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "224827",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T12:59:57.250",
"Id": "224810",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Determine whether three sides form a valid triangle, and classify the triangle"
}
|
224810
|
<p>I am working on a asp.net mvc project. And I wonder if the setup of the project is correct. So just some advice</p>
<p>Because I see this:</p>
<pre class="lang-cs prettyprint-override"><code>public IndicatorController(
IndicatorService indicatorService,
PatientLogService patientLogService,
PatientDbContext dbContext,
AppIdentityDbContext identityDbContext,
MedicalDbContext medicalDbContext,
IMeasurementProcessor measurementProcessor,
IMeasurementRepository measurementRepository,
IEntryRepository entryRepository,
IPersonalFieldBoundaryRepository personalFieldBoundaryRepository,
IEmailSender emailSender,
IndicatorActionService indicatorActionService,
IndicatorBuilderContext indicatorBuilderContext,
IPatientIndicatorService patientIndicatorService,
ViewRender viewRender,
IEmailSender messageSender,
IOptions<AppSettings> appSettings,
ILoggerFactory loggerFactory)
: base(dbContext, identityDbContext, medicalDbContext, loggerFactory)
{
_patientLogService = patientLogService;
_indicatorService = indicatorService;
_measurementProcessor = measurementProcessor;
_measurementRepository = measurementRepository;
_entryRepository = entryRepository;
_personalFieldBoundaryRepository = personalFieldBoundaryRepository;
_emailSender = emailSender;
_indicatorActionService = indicatorActionService;
_indicatorBuilderContext = indicatorBuilderContext;
_patientIndicatorService = patientIndicatorService;
_viewRender = viewRender;
_messageSender = messageSender;
_appSettings = appSettings.Value;
}
</code></pre>
<p>And the base Controller looks like this:</p>
<pre><code>public class BaseController : Controller
{
protected PatientDbContext _patientDbContext;
protected MedicalDbContext _medicalDbContext;
protected readonly AppIdentityDbContext _identityDbContext;
protected readonly ILogger _logger;
public string CurrentUserId => User.FindFirstValue(JwtClaimTypes.Subject);
private Task<Participant> _participant;
private Task<UserIdentity> _userIdentity;
public Task<Participant> Participant => _participant ?? (_participant = LoadParticipant());
public Task<UserIdentity> UserIdentity => _userIdentity ?? (_userIdentity = LoadUserIdentity());
public BaseController(
PatientDbContext patientDbContext,
AppIdentityDbContext identityDbContext,
MedicalDbContext medicalDbContext,
ILoggerFactory loggerFactory)
{
_patientDbContext = patientDbContext;
_medicalDbContext = medicalDbContext;
_identityDbContext = identityDbContext;
_logger = loggerFactory.CreateLogger<BaseController>();
}
private async Task<Participant> LoadParticipant()
{
return !RouteData.Values.ContainsKey("participantId")
|| !Guid.TryParse(RouteData.Values["participantId"].ToString(), out Guid participantId)
? null : await _patientDbContext.Participants.FindAsync(participantId);
}
private async Task<UserIdentity> LoadUserIdentity()
{
var participant = await Participant;
return await _identityDbContext.Users
.Include(i => i.ParticipantIdentity)
.FirstOrDefaultAsync(i => i.Id == participant.UserIdentityId);
}
}
</code></pre>
<p>But so my question is: Is this the correct way to inject the PatientDbContext dbContext directly into the controllers constructor?</p>
<p>Thank you</p>
<p>But for example the AdviseService , there you directly inject the dbcontext:</p>
<pre class="lang-cs prettyprint-override"><code>public class AdviceService
{
private static readonly HtmlSanitizer s_htmlSanitizer = HtmlSanitizerProvider.GetSanitizer();
private readonly PatientDbContext _patientDbContext;
private readonly MedicalDbContext _medicalDbContext;
private readonly AppIdentityDbContext _identityDbContext;
private readonly AdviceLayoutFactory _adviceLayoutFactory;
private readonly PatientLogService _patientLogService;
private readonly ILogger _logger;
private readonly JsonSerializerSettings _jsonSerializerSettings;
private readonly ChatDbContext _chatDbContext;
public AdviceService(
PatientDbContext patientDbContext,
MedicalDbContext medicalDbContext,
ChatDbContext chatDbContext,
AppIdentityDbContext identityDbContext,
AdviceLayoutFactory adviceLayoutFactory,
PatientLogService patientLogService,
ILoggerFactory loggerFactory,
JsonSerializerSettings jsonSerializerSettings)
{
_patientDbContext = patientDbContext;
_medicalDbContext = medicalDbContext;
_identityDbContext = identityDbContext;
_adviceLayoutFactory = adviceLayoutFactory;
_patientLogService = patientLogService;
_jsonSerializerSettings = jsonSerializerSettings;
_logger = loggerFactory.CreateLogger<AdviceService>();
_chatDbContext = chatDbContext;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:58:58.977",
"Id": "436170",
"Score": "7",
"body": "Could you explain a bit what this project is about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:22:57.447",
"Id": "436175",
"Score": "0",
"body": "it is the backend of a Angular project. But What exactly do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T15:24:37.147",
"Id": "436176",
"Score": "7",
"body": "Just a small description of the app you are building would do. But what we are really missing, is how you actually inject these dependencies. Do you use a Depencency Injection framework ?"
}
] |
[
{
"body": "<p>Welcome to CodeReview :-)</p>\n\n<h1>Code to contract (interface) not to implementation</h1>\n\n<p>Your program components should be loosely coupled. It is important for two main reasons:</p>\n\n<ul>\n<li>you can easily swap components of your program. </li>\n<li>change in one place would not force you to alter code independent components</li>\n</ul>\n\n<p>What does this mean in practice?</p>\n\n<p>Start with defining interfaces. For starter, they can be 1:1 copy of your public methods signatures. Then register them in your DI container and pass interfaces into the constructor. (ie. <code>IAdviceLayoutFactory</code>, <code>IPatientLogService</code> instead of <code>AdviceLayoutFactory</code>, <code>PatientLogService</code>)</p>\n\n<h1>Single Responsibility Principle</h1>\n\n<p>In simple terms, classes should be small and have one purpose. When someone asks you - <em>what does class X do?</em> you should be able to answer with a simple sentence, containing one verb.</p>\n\n<p>Another rule of thumb - if a class has more than 6 parameters in a constructor it should be split.</p>\n\n<p>A good example of counter-example would be <code>IndicatorController</code>. It has like 20 parameters. I presume it can't be described with a simple sentence.</p>\n\n<p>Controllers have only one purpose - call application (domain) logic with parameters deserialized from the network request. As simple as it sounds:</p>\n\n<pre><code>public IndicatorController(IIndicatorService service) {\n _service = service;\n}\n\n// Methods matching endpoints related to Indicators\n...\n</code></pre>\n\n<h1>Code has to be testable</h1>\n\n<p>When you follow the rules mentioned above your code is match more testable.</p>\n\n<p>With interfaces, you can easily replace actual implementation with a fake one. Eg. Instead of connecting to a real database you can simply create a fake implementation of class responsible for data manipulation.\nWith dependence on interfaces and some mocking library (like Moq) it is super easy.</p>\n\n<p>Thanks to smaller classes it would be easier to focus on a single feature of your app and unit test it with less moving parts. Just moq all code on which your feature depends. </p>\n\n<p><strong>I would like to give you a change to refactor your code a bit. If you are stuck I would be glad to help - I just don't want to steal all the fun :-)</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T07:22:52.940",
"Id": "436291",
"Score": "0",
"body": "Thank you for your time and effort too show it how it can be better structured."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T23:14:37.257",
"Id": "436443",
"Score": "0",
"body": "You are welcome. Feel free to ask if you have any questions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T23:31:16.657",
"Id": "224845",
"ParentId": "224817",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "224845",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:52:58.567",
"Id": "224817",
"Score": "-1",
"Tags": [
"c#",
"dependency-injection"
],
"Title": "Using Dependency Injection through constructor"
}
|
224817
|
<p>i have this php Script:</p>
<pre><code>function GetFTPFile($iFile) {
echo '<pre>';
$StartTime = microtime(true);
$FTP = [];
$FTP['SMG'] = '';
$FTP['st'] = 0;
$FTP['time'] = 0;
$nuevo_path = $iFile['lfile'];
$remote = $iFile['sfile'];
echo $P_Path = 'ftp://' . FTP_USER . ':' . FTP_PASSWORD . '@' . FTP_HOST . $remote;
echo '<br>';
$FTP['test'] = $P_Path;
$result = file_exists($P_Path);
if ($result == true) {
$resultfile = copy($P_Path, $nuevo_path);
if ($resultfile == true) {
$FTP['SMG'] = 'Copy Successfull';
$FTP['st'] = 1;
} else {
$FTP['SMG'] = 'Copy Fail!!!';
$FTP['st'] = 0;
}
} else {
$FTP['SMG'] = 'Conection Error!!!';
$FTP['st'] = 0;
}
$EndTime = microtime(true);
echo 'Copy time via FTP: <br>';
echo $FTP['time'] = $EndTime - $StartTime;
echo '</pre>';
return $FTP;
}
</code></pre>
<p>and this create a FTP URI Like this</p>
<pre><code>ftp://user:secretpass@xxx.xxx.xxx.xxx/dir1/dir2/repository/test.txt
</code></pre>
<p>And try to copy a txt File around 85 Kb from the FTP Server (UNIX) to local Disk (Linux Ubuntu Server 18.04)</p>
<p>the issues is that this is taken around <strong>20 second</strong> to run the script over the file with the native function <code>copy()</code>.</p>
<p>i try to make the connection over FTP client Filezilla to get the log and get this, i dont know if its relation to this:</p>
<pre><code>11:16:08 Status: Connecting to xxx.xxx.xxx.xxx:21 ...
11:16:08 Status: Connection established, waiting for the welcome message ...
11:16:22 Status: Server not secure, does not support FTP over TLS.
11:16:22 Status: The server does not allow non-ASCII characters.**
11:16:22 Status: Registered at
11:16:22 Status: Retrieving the directory listing ...
11:16:22 Status: Directory "/ usr / intlu" listed correctly
</code></pre>
<p><strong>which is what I am omitting, how can I decrease this delay or how to solve it?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T19:22:04.867",
"Id": "436226",
"Score": "0",
"body": "You're asking why the native function `copy()` takes a long time to copy a file from a FTP server to your local disk. You're not really asking us to review your code. The first thing I would do is to use another FTP client, and check how long it takes to connect, login and download the file with that. The FTP server might just be slow. Alternatively you could use the normal [FTP functions of PHP](https://www.w3schools.com/php/func_ftp_get.asp). Here the steps are not combined into one wrapper and can be timed separately, so you can see what takes so long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T20:43:33.733",
"Id": "436237",
"Score": "0",
"body": "@KIKOSoftware \nI see that you have not read the post, I clearly place the example using Filezilla as an alternative test client and log data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T20:52:58.763",
"Id": "436239",
"Score": "0",
"body": "Yes, I missed the relevance of that. How long does it take with Filezilla? Including the download? I still hope my comment can be useful to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T21:00:42.827",
"Id": "436243",
"Score": "0",
"body": "@KIKOSoftware According to the log i have put in the post, downloading files is immediate, but according to the log, at the time of logging in there is a delay in tls checking."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T17:07:47.993",
"Id": "224826",
"Score": "0",
"Tags": [
"php",
"url",
"ftp"
],
"Title": "use of FTP URI to copy file from FTP server to Local Disk have Delay"
}
|
224826
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.