body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I just wrote a little bash script for rsync push backups of my laptop to my Synology-Diskstation at home.</p>
<p>Since I am a bash beginner and don't have any experience with <code>ssh</code>, <code>rsync</code> and backups I am asking for suggestions how to improve the <em>performance</em>, <em>reliablility</em>, <em>usability</em> and <em>security</em> of my script and for suggestions to improve the <em>coding style</em>. I have listed some problems and notes below. </p>
<p>The hardrive of my laptop is encrypted and the backup should be encrypted as well. </p>
<p>Here is the script: </p>
<pre><code>#!/bin/bash
bold=`tput bold`
normal=`tput sgr0`
dirlist=/home/myuser/bin/dirlist
pass=mypassword
date=`date "+%Y-%m-%dT%H_%M_%S"`
echo "${bold}Mounting encrypted backup volume${normal}"
ssh -n -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "/usr/syno/sbin/synoshare --enc_mount MyuserBackup $pass"
sleep 5
echo "${bold}Checking and eventually creating dirs on backup server${normal}"
## Creating directories
while read dir; do
echo "Create incomplete$dir if not existent"
## http://stackoverflow.com/questions/9393038/ssh-breaks-out-of-while-loop-in-bash
ssh -n -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "mkdir -p /volume1/MyuserBackup/rsync_Backup/incomplete$dir"
done < $dirlist
while read dir; do
echo "${bold}Backing up $dir${normal}"
time sudo rsync -avX -u --compress-level=0 --stats -h --exclude-from=/home/myuser/bin/excludelist --numeric-ids "$@" --link-dest=/volume1/MyuserBackup/rsync_Backup/current$dir --rsh="ssh -i /home/myuser/.ssh/id_rsa" $dir root@192.168.0.70:/volume1/MyuserBackup/rsync_Backup/incomplete$dir
done < $dirlist
echo $date
echo "${bold}Updating Date-Structure${normal}"
echo "mv /volume1/MyuserBackup/rsync_Backup/incomplete /volume1/MyuserBackup/rsync_Backup/back-$date"
ssh -t -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "mv /volume1/MyuserBackup/rsync_Backup/incomplete /volume1/MyuserBackup/rsync_Backup/back-$date"
echo "rm -f /volume1/MyuserBackup/rsync_Backup/current"
ssh -t -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "rm -f /volume1/MyuserBackup/rsync_Backup/current"
echo "ln -s /volume1/MyuserBackup/rsync_Backup/back-$date /volume1/MyuserBackup/rsync_Backup/current"
ssh -t -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "ln -s /volume1/MyuserBackup/rsync_Backup/back-$date /volume1/MyuserBackup/rsync_Backup/current"
echo "Showing the current dir structure:"
ssh -t -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "ls -lhrt /volume1/MyuserBackup/rsync_Backup/"
echo "${bold}Unmounting encrypted volume${normal}"
ssh -t -i /home/myuser/.ssh/id_rsa root@192.168.0.70 "/usr/syno/sbin/synoshare --enc_unmount MyuserBackup"
</code></pre>
<p><code>cat dirlist</code></p>
<pre><code>/home/
/etc/
/var/
</code></pre>
<p><code>cat excludelist</code></p>
<pre><code>## Universal excludes
lost+found
ld.so.cache
# backup text files (e.g. from Emacs)
- *~
- \#*\#
# Commonly distributed Windows cache
- Thumbs.db
# Common package managers (apt, yum)
- *cache/apt/
# sshfs
- box1
- box2
- box3
- box4
# Cache
- .cache/
- **cache
# Temporary files / cache
- .local/share/Trash
- .cache
- .Trash
- **.Trash
- **.macromedia
- **.thumbnails
- .local/share/gvfs-metadata
- .aptitude
- .pulse
- .pulse-cookie
- .xournal
- .sage/temp
- tmp
- .mozilla/firefox/*/Cache
- .mozilla/firefox/*/minidumps # in case Fx crashes dumps will be stored in this
- .mozilla/firefox/*/.parentlock # session-specific
- .mozilla/firefox/*/urlclassifier3.sqlite # phishing database, recreated
- .mozilla/firefox/*/blocklist.xml # blacklisted extensions
- .mozilla/firefox/*/extensions.sqlite # extension database, recreated on startup
- .mozilla/firefox/*/extensions.sqlite-journal
- .mozilla/firefox/*/extensions.rdf
- .mozilla/firefox/*/extensions.ini
- .mozilla/firefox/*/extensions.cache
- .mozilla/firefox/*/XUL.mfasl # cached UI data, recreated
- .mozilla/firefox/*/XPC.mfasl
- .mozilla/firefox/*/xpti.dat
- .mozilla/firefox/*/compreg.dat
- .compiz
- .dbus
# Private directory from ecryptfs
- .Private
# X Windows System
- .xsession-errors*
# Gnome temp stuff
- .compiz*/session
- .gksu.lock
- **.gvfs
# Common Applications
# Adobe Reader
- */.adobe/**/AssetCache/
- */.adobe/**/Cache/
- */.adobe/**/Temp/
- */.adobe/**/UserCache.bin
# Gimp
- /.gimp-*/tmp
- /.gimp-*/swap
# Mozilla Firefox
- .mozilla/firefox/*/Cache/
- .mozilla/firefox/*/lock
- .mozilla/firefox/*/.parentlock
# Mozilla Thunderbird
- .mozilla-thunderbird/*/lock
- .mozilla-thunderbird/*/.parentlock
- *recently-used*
</code></pre>
<h2>Notes and Problems</h2>
<ul>
<li>Usually I execute the script with sudo, but sometimes it asks for the sudo password again when it comes to the next item in dirlist. I guess this is due to the fact that the sudo password is only saved for some time, 5 minutes or so. However this is bad since I don't want to control what the script is doing all the time.</li>
<li><p>Sometimes it gives something like </p>
<pre><code>rsync: send_files failed to open "/home/myuser/.thunderbird/myprofile.default/session-6.json": Input/output error (5)
</code></pre>
<p>This happens only with some "exotic" files like the file above. </p></li>
<li><p>Sometimes it prints errors like</p>
<pre><code>rsync: mkstemp "/volume1/MyuserBackup/rsync_Backup/incomplete/home/" failed: No such file or directory (2)
</code></pre>
<p>However I didn't find any files which were not transferred. </p></li>
<li><p>Is there some better way to handle the password instead of writing it in plaintext into the script?</p></li>
<li><p>The script seems to be really slow even if nothing changed on the disk it takes over 30 min</p></li>
<li><p>Currently I thin out the snapshots manually but I am thinking of writing a program which do this automatically. Something like <a href="http://www.spinellis.gr/sw/unix/fileprune/">this</a>.</p></li>
</ul>
<h2>Versions</h2>
<p>Here are the versions of the used software:</p>
<ul>
<li>bash: 4.2.8(1)</li>
<li>rsync: 3.0.7</li>
<li>synology DSM: 4.2</li>
<li>OpenSSH 5.8p1 Debian-1ubuntu3</li>
</ul>
<h2>Hardware</h2>
<ul>
<li><a href="http://www.synology.com/us/products/DS109/spec.php">Disk-Station</a></li>
<li>Laptop CPU: Dual-Core P8700</li>
</ul>
|
[] |
[
{
"body": "<h2>DRY - Don't Repeat Yourself.</h2>\n\n<p>You repeat certain things a lot. I recommend extracting a function for your ssh commands:</p>\n\n<pre><code>function remotessh {\n echo \"Running ssh : \" + \"$@\"\n ssh -i /home/myuser/.ssh/id_rsa root@192.168.0.70 \"$@\"\n}\n</code></pre>\n\n<p>This function should have some appropriate error handling too.</p>\n\n<p>Then, your code can become simplified like:</p>\n\n<pre><code>echo \"${bold}Mounting encrypted volume${normal}\"\nremotessh -n \"/usr/syno/sbin/synoshare --enc_mount MyuserBackup $pass\" \n\n.....\n\nremotessh -t \"mv /volume1/MyuserBackup/rsync_Backup/incomplete /volume1/MyuserBackup/rsync_Backup/back-$date\"\n\nremotessh -t \"rm -f /volume1/MyuserBackup/rsync_Backup/current\"\n\nremotessh -t \"ln -s /volume1/MyuserBackup/rsync_Backup/back-$date /volume1/MyuserBackup/rsync_Backup/current\"\n\necho \"Showing the current dir structure:\"\nremptessh -t \"ls -lhrt /volume1/MyuserBackup/rsync_Backup/\"\n\necho \"${bold}Unmounting encrypted volume${normal}\"\nremotessh -t \"/usr/syno/sbin/synoshare --enc_unmount MyuserBackup\"\n</code></pre>\n\n<h2>Error Handling</h2>\n\n<p>You should include error handling always in bash scripts.</p>\n\n<h2>RSync issues, etc.</h2>\n\n<p>rsync builds up a list of files to transfer, calculates the smallets dataset that needs to be migrated to accomplish the transfer, then it does the copy. If files change between when the calculation is done, and the transfer is done, it gives different errors/warnings.</p>\n\n<p>This is what is happening with you, I believe.</p>\n\n<h2>Performance</h2>\n\n<p>Depending on the rsync options, it can take a while to both build the copy-list, and do the copy. Even though it may be inconvenient, you probably cannot beat rsync for performance.</p>\n\n<p>Check each of your options to ensure they are the best. Kill those options that you don't need.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:29:17.000",
"Id": "44530",
"ParentId": "29429",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "44530",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:46:17.207",
"Id": "29429",
"Score": "7",
"Tags": [
"beginner",
"bash",
"linux"
],
"Title": "Push backup script"
}
|
29429
|
<p>I am trying to solve the <a href="http://leetcode.com/onlinejudge#question_5" rel="nofollow">Longest Palindromic Substring problem</a> on LeetCode, and I have come up with a DP solution pasted below:</p>
<pre><code>public class Solution {
String string;
boolean[][] visited;
String[][] results;
private boolean isPalindrome(String s){
String test = new StringBuilder(s).reverse().toString();
if(test.equals(s)) return true; else return false;
}
private String maxLengthString(String... args){
String result = new String();
for(String arg:args){
if(arg.length() > result.length()) result = arg;
}
return result;
}
private String findLongestPalindrome(int start,int end){
if(start >= end) return new String();
else if(start >= string.length() || start < 0) return new String();
else if(end <= 0 || end > string.length()) return new String();
else{
if(visited[start][end-1] == true) return results[start][end-1];
String result = new String();
if(this.isPalindrome(string.substring(start,end)))
result = maxLengthString(string.substring(start,end),
findLongestPalindrome(start+1,end),
findLongestPalindrome(start,end-1));
else result = maxLengthString(findLongestPalindrome(start+1,end),
findLongestPalindrome(start,end-1));
visited[start][end-1] = true;
results[start][end-1] = result;
return result;
}
}
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
string = s;
visited = new boolean[s.length()][s.length()];
results = new String[s.length()][s.length()];
return findLongestPalindrome(0,s.length());
}
}
</code></pre>
<p>The algorithm is quite straightforward, but the online judge complains about it not being efficient enough. I am just wondering if this algorithm is slow by nature (in which case I have to find another algorithm) or if it's something about my implementation.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:12:39.493",
"Id": "46529",
"Score": "0",
"body": "Also, it's probably slow because of the recursion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:13:22.700",
"Id": "46530",
"Score": "0",
"body": "I see you are using a recursive approach. Have you tried to create an iterative solution and compare the results?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:16:38.513",
"Id": "46531",
"Score": "0",
"body": "@bblincoe I will try later"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T14:53:03.907",
"Id": "46532",
"Score": "1",
"body": "@Bohemian I'd imagine, to become efficient enough, it would require a fundamentally different approach, i.e. basically a complete rewrite. Wouldn't this be beyond the scope of [codereview.se]? UPDATE - Well, the question doesn't actually seem to be asking about a different approach, just why it's slow, so it may be fine for there, I'm not sure."
}
] |
[
{
"body": "<h2>Why is it slow?</h2>\n\n<p>The input string <code>S</code> can be up to 1000 characters.</p>\n\n<p>Your DP solution considers all \\$\\mathcal{O}(|S|^2)\\$ substrings of <code>S</code> and you're checking for each of these substrings, if it is a palindrome, in linear time in terms of the length of this substring.</p>\n\n<h2>Faster solutions</h2>\n\n<p>You can do it easily in \\$\\mathcal{O}(|S|^2)\\$ using a polynomial hashing technique.</p>\n\n<p>There are of course more sophisticated and linear solutions based on the famous <a href=\"http://en.wikipedia.org/wiki/Longest_palindromic_substring\" rel=\"nofollow\">Manacher algorithm</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:16:58.903",
"Id": "29436",
"ParentId": "29434",
"Score": "3"
}
},
{
"body": "<p>The proper way to solve it is to use a profiler to determine where the bottlenecks are, but by inspection, your search tree is at least twice the size it has to be <em>and</em> you will always expand the entire tree rather than terminating when you can.</p>\n\n<pre><code>if(this.isPalindrome(string.substring(start,end)))\n result = maxLengthString(string.substring(start,end),\n findLongestPalindrome(start+1,end),\n findLongestPalindrome(start,end-1));\n else result = maxLengthString(findLongestPalindrome(start+1,end),\n findLongestPalindrome(start,end-1));\n</code></pre>\n\n<p>if this.isPalindrome is true, then there is no way that findLongestPalindrome(start+1,end) or (start,end-1) could be longer. Rewriting this gives:</p>\n\n<pre><code>if(this.isPalindrome(sting.substring(start,end)))\n result = string.substring(start,end)\nelse\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:21:50.147",
"Id": "46534",
"Score": "0",
"body": "In the worst case it doesn't help at all"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:19:55.467",
"Id": "29437",
"ParentId": "29434",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:09:51.357",
"Id": "29434",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"programming-challenge",
"palindrome"
],
"Title": "\"Longest Palindromic Substring\" challenge solution is inefficient"
}
|
29434
|
<p>I've noticed that there are several ways of sending data through a TCP stream. I want to do it the fastest way in terms of latency.</p>
<p>One method I became aware of is with a binary writer:</p>
<pre><code>using (MemoryStream ms = PrintWindow(process))
{
writer.Write((int)ms.Length);
writer.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
</code></pre>
<p>And to receive it:</p>
<pre><code>Image.FromStream(new MemoryStream(reader.ReadBytes(reader.ReadInt32())));
</code></pre>
<p>It writes the size for reference, then takes the data.</p>
<p>For the other method, which is a bit sensitive, it seems that it can easily fail if the image changes for some reason:</p>
<pre><code>using (MemoryStream ms = PrintWindow(process))
{
tcp.GetStream().Write(ms.GetBuffer(), 0, tcp.SendBufferSize);
}
</code></pre>
<p>And to receive it:</p>
<pre><code>byte[] b = new byte[tt1.ReceiveBufferSize];
tt1.GetStream().Read(b, 0, tt1.ReceiveBufferSize);
Image.FromStream(new MemoryStream(b));
</code></pre>
<p>I've found this with trial and error. But, as I've said, it's very sensitive and can cause an error if the image changes in a certain way. I'm not absolutely sure why, though.</p>
<p>Which of these is the fastest? In my view, writing with just the stream should be faster than with some special writer.</p>
<p>The error I get when using the second method seems to occur when the data is very low. For example: a black or near-black picture. If anyone knows how to solve this, please let me know.</p>
<p>It seems that I need to have the TCP Send and Receive buffer at least as big as the largest file for it to work, so I've increased it by x128. I'm not sure if that's a good idea or not, but from my understanding, the only thing it does is allocate more RAM. Then again, I think it's probably because I set the byte size to the buffer size.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:30:28.627",
"Id": "46577",
"Score": "0",
"body": "there are various ways of checking the incoming data. And of reading and writing.. eg readline, readexisting, read.. which all have their advantages etc.. You have not indicated how you are formating start and stop bits, and how you are listening for data. how you manage the flow of reading data, the way you read it and the way you format loops in your code will make a difference to performance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-08T20:10:11.487",
"Id": "54750",
"Score": "0",
"body": "I remember something about my PDF application where you set the Buffer size...let me get back to you"
}
] |
[
{
"body": "<p>If you are looking for ways to optimize your application - you are clearly looking at the wrong place, at least in my opinion. <code>BinaryWriter</code> is a simple wrapper around actual stream. All it does is it converts simple types to byte arrays and writes those to stream. Ofc it is slower, as any other wrapper, but not <em>that much</em> slower. In real life this difference can be ignored.</p>\n\n<p>If writing to <code>NetworkStream</code> is your main performance issue, then consider wrapping it with <code>BufferedStream</code>. </p>\n\n<p>If it isnt, and you are simply curious... then you can always use disassembler to see whats inside <code>BinaryWriter.Write</code> method for yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T13:37:17.130",
"Id": "46542",
"Score": "0",
"body": "Hmm, thought it was good to write stuff like this, as many ask stuff like this. But guess it´s wrong then, sorry. \nBut from what you wrote, i get that as close to the stream you are, the faster it get´s. Meaning writing directly is faster than going around to write to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:14:50.317",
"Id": "46548",
"Score": "1",
"body": "@Zerowalker, nah, there is nothing wrong with curiosity. And your logic is correct. However if you are going to blindly follow it - you will end up having one mega-object with one mega-method containing all of your application's logic implemented using API calls. I would not say \"worth it\" looking at such code, and neither would you, im sure. Even though it will indeed run faster then the same code refactored using common OOP practices and patterns (_wrapper_ being one of such patterns.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:25:53.707",
"Id": "46566",
"Score": "0",
"body": "Well that´s good. And well at this application, i really need to get the most out of it, especially latency, 1ms here and there is important. Normally i wouldn´t care that much as long as it works well. But that being said. Binarywriter/reader is faster in my tests weird enough;S"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T05:50:48.313",
"Id": "46642",
"Score": "0",
"body": "That's probably because you are working with streams in some wierd way :) Yet another reason to use dedicated writers :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T07:25:58.367",
"Id": "46646",
"Score": "0",
"body": "Probably, but would like to get it to work. It´s weird that there isn´t a direct way to write a file, and when it´s done, send a \"Cancel\". I found something in WriteAsync, CancellationToken, but it seems it´s something else though."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T13:15:15.420",
"Id": "29445",
"ParentId": "29440",
"Score": "5"
}
},
{
"body": "<pre><code>using (MemoryStream ms = PrintWindow(process))\n{ \n tcp.GetStream().Write(ms.GetBuffer(), 0, tcp.SendBufferSize); \n}\n</code></pre>\n\n<p>This is very very bad. Do NOT do this. It is going to try and write <code>tcp.SendBufferSize</code> bytes across the stream. But you've made no attempt to be sure that's correct. You could be sending too many bytes, or too few bytes. You've already noted that it fail randomly, but you've papered over the real problem. </p>\n\n<p>Performance wise, its not going to give you an advantage. When it works, you are sending a large amount of bytes across the network you aren't using. That's going to be a serious performance problem. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:27:34.237",
"Id": "46575",
"Score": "0",
"body": "Yeah notices how stupid this was. I am trying to do something like the first, but without using a \"3rd\" party writer. But i don´t know how to tell the other client that the data has ended."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:34:58.657",
"Id": "46578",
"Score": "0",
"body": "@Zerowalker, the person who wrote the 3rd party writer was probably way more experienced then you. You've got no reason to assume that you could do a better job then him."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:41:06.460",
"Id": "46580",
"Score": "0",
"body": "probably, but the performance between the different ways to do this task of just sending an image is quite large. So that´s why i want to do it the simplest way, without any special stuff going on. That being sad, i am not thinking i could write a writer that´s better than probably any that exist with my skills."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T16:34:42.643",
"Id": "29461",
"ParentId": "29440",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T12:16:49.390",
"Id": "29440",
"Score": "5",
"Tags": [
"c#",
"comparative-review",
"stream",
"tcp"
],
"Title": "Sending data through a TCP stream"
}
|
29440
|
<hr>
<h2>here is the puzzle description</h2>
<p>Your task is to decode messages that were encoded with substitution ciphers. In a substitution cipher, all occurrences of a character
are replaced by a different character. For example, in a cipher that replaces "a" with "d" and "b" with "e", the message "abb" is encoded
as "dee".</p>
<p>The exact character mappings that are used in the substitution ciphers will not be known to you. However, the dictionary of words
that were used will be given. You will be given multiple encoded messages to decode (one per line) and they may use different
substitution ciphers. The same substitution cipher is used on all of the words in a particular message .</p>
<p>For each scrambled message in the input, your program should output a line with the input line, followed by the string " = " (without
the quotes), followed by the decoded message.</p>
<p>NOTE: All inputs are from stdin and output to stdout. The input will be exactly like how it's given in the problem and
your output should exactly match the given example output</p>
<pre><code>Example:
input file :
//dict
hello
there
yello
thorns
//secret
12334 51272
12334 514678
output:
12334 51272 = hello there
12334 514678 = hello thorns
</code></pre>
<p>after some thought, I came up with the following algorithm to solve. </p>
<p>Question: what are the other possible ways to solve this. can we optimize the current solution i have?</p>
<p>thanks </p>
<pre><code>class Program
{
static void Main(string[] args)
{
var dict = new List<string> { "hello", "there", "yello", "thorns" };
var listEncryptedSentences = new List<string> { "12334 51272", "12334 514678" };
var listListWords = new List<List<string>>();
foreach (var encryptedSentence in listEncryptedSentences)
{
listListWords.Add(encryptedSentence.Split(' ').ToList());
}
foreach (var listWords in listListWords)
{
SolveAndPrint(dict, listWords);
}
Console.ReadKey();
}
private static void SolveAndPrint(List<string> dict, List<string> encodedWords)
{
var previousSolutions = new List<string>();
var currentSolutions = new List<string>();
var totalSolutions = new List<string>();
string totalWordTillNow = "";
foreach (var encodedWord in encodedWords)
{
currentSolutions = GetMatchingStrings(dict, encodedWord);
totalWordTillNow += encodedWord;
totalSolutions = GetMatchingStrings(CrossJoin(previousSolutions, currentSolutions), totalWordTillNow);
previousSolutions = totalSolutions;
}
string encodedString = "";
var decodedStrings = new List<string>();
foreach (var solution in totalSolutions)
decodedStrings.Add("");
foreach (var encodedWord in encodedWords)
{
encodedString += encodedWord + " ";
for (int i = 0; i < totalSolutions.Count; i++)
{
decodedStrings[i] += " " + totalSolutions[i].Substring(0, encodedWord.Length);
totalSolutions[i] = totalSolutions[i].Substring(encodedWord.Length, totalSolutions[i].Length - encodedWord.Length);
}
}
foreach (var decodedString in decodedStrings)
{
Console.WriteLine(encodedString + "=" + decodedString);
}
}
private static List<string> GetMatchingStrings(List<string> possibleWords, string word)
{
var result = new List<string>();
var wordPattern = GetWordLettersPattern(word);
foreach (var possibleWord in possibleWords)
{
if (CompareCounts(wordPattern, GetWordLettersPattern(possibleWord)))
result.Add(possibleWord);
}
return result;
}
private static List<List<int>> GetWordLettersPattern(string word)
{
var distinctletters = word.ToCharArray().Distinct();
var letterPattern = new List<List<int>>();
foreach (var letter in distinctletters)
{
letterPattern.Add(GetPositions(word, letter.ToString()));
}
return letterPattern;
}
public static List<int> GetPositions(string source, string searchString)
{
List<int> ret = new List<int>();
int len = searchString.Length;
int start = -len;
while (true)
{
start = source.IndexOf(searchString, start + len);
if (start == -1)
{
break;
}
else
{
ret.Add(start);
}
}
return ret;
}
public static bool CompareCounts(List<List<int>> left, List<List<int>> right)
{
bool returnVal = true;
returnVal &= left.Count == right.Count;
if (returnVal)
{
for (int i = 0; i < left.Count; i++)
{
returnVal &= left[i].Count == right[i].Count;
if (!returnVal) break;
}
}
return returnVal;
}
public static List<string> CrossJoin(List<string> left, List<string> right)
{
var returnVal = new List<string>();
if (left.Count == 0)
returnVal.AddRange(right);
else if (right.Count == 0)
returnVal.AddRange(left);
else foreach (var leftItem in left)
{
foreach (var rightItem in right)
{
returnVal.Add(leftItem + rightItem);
}
}
return returnVal;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A tad tighter, but the same solution overall:</p>\n\n<pre><code>static class Program\n{\n static void Main()\n {\n var dict = new List<string> { \"hello\", \"there\", \"yello\", \"thorns\" };\n var listEncryptedSentences = new List<string> { \"12334 51272\", \"12334 514678\" };\n var listListWords = listEncryptedSentences.Select(encryptedSentence => encryptedSentence.Split(' '));\n\n foreach (var listWords in listListWords)\n {\n SolveAndPrint(dict, listWords);\n }\n\n Console.ReadKey();\n }\n\n private static void SolveAndPrint(IEnumerable<string> dict, IEnumerable<string> encodedWords)\n {\n IEnumerable<string> previousSolutions = new List<string>();\n IList<string> totalSolutions = null;\n var totalWordTillNow = string.Empty;\n\n foreach (var encodedWord in encodedWords)\n {\n var currentSolutions = GetMatchingStrings(dict, encodedWord);\n\n totalWordTillNow += encodedWord;\n totalSolutions = GetMatchingStrings(CrossJoin(previousSolutions, currentSolutions), totalWordTillNow);\n previousSolutions = totalSolutions;\n }\n\n if (totalSolutions == null)\n {\n totalSolutions = new List<string>();\n }\n\n var encodedString = string.Empty;\n var decodedStrings = totalSolutions.Select(solution => string.Empty).ToList();\n\n foreach (var encodedWord in encodedWords)\n {\n encodedString += encodedWord + \" \";\n for (var i = 0; i < totalSolutions.Count; i++)\n {\n decodedStrings[i] += \" \" + totalSolutions[i].Substring(0, encodedWord.Length);\n totalSolutions[i] = totalSolutions[i].Substring(encodedWord.Length, totalSolutions[i].Length - encodedWord.Length);\n }\n }\n\n foreach (var decodedString in decodedStrings)\n {\n Console.WriteLine(encodedString + \"=\" + decodedString);\n }\n }\n\n private static IList<string> GetMatchingStrings(IEnumerable<string> possibleWords, string word)\n {\n var wordPattern = GetWordLettersPattern(word);\n\n return possibleWords\n .Where(possibleWord => CompareCounts(wordPattern, GetWordLettersPattern(possibleWord)))\n .ToList();\n }\n\n private static IList<IEnumerable<int>> GetWordLettersPattern(string word)\n {\n return word\n .ToCharArray()\n .Distinct()\n .Select(letter => GetPositions(word, letter.ToString(CultureInfo.InvariantCulture)))\n .ToList();\n }\n\n public static IEnumerable<int> GetPositions(string source, string searchString)\n {\n var ret = new List<int>();\n var len = searchString.Length;\n var start = -len;\n\n while (true)\n {\n start = source.IndexOf(searchString, start + len, StringComparison.InvariantCulture);\n if (start == -1)\n {\n return ret;\n }\n\n ret.Add(start);\n }\n }\n\n public static bool CompareCounts(IList<IEnumerable<int>> left, IList<IEnumerable<int>> right)\n {\n var returnVal = true;\n\n returnVal &= left.Count() == right.Count();\n if (returnVal)\n {\n for (var i = 0; i < left.Count(); i++)\n {\n returnVal &= left[i].Count() == right[i].Count();\n if (!returnVal)\n {\n return false;\n }\n }\n }\n\n return returnVal;\n }\n\n public static List<string> CrossJoin(IEnumerable<string> left, IEnumerable<string> right)\n {\n var returnVal = new List<string>();\n\n if (!left.Any())\n {\n returnVal.AddRange(right);\n }\n else if (!right.Any())\n {\n returnVal.AddRange(left);\n }\n else\n {\n foreach (var leftItem in left)\n {\n var item = leftItem;\n\n returnVal.AddRange(right.Select(rightItem => item + rightItem));\n }\n }\n\n return returnVal;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T13:58:56.230",
"Id": "46543",
"Score": "0",
"body": "LINQ all over nice :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T13:46:08.330",
"Id": "29446",
"ParentId": "29443",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T12:46:11.037",
"Id": "29443",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"cryptography"
],
"Title": "Better ways of solving the substitution cipher puzzle"
}
|
29443
|
<p>In the book <code>Clean Code</code> from Robert C. Martin are given many recommendations. Two of them are </p>
<ul>
<li>to keep functions small and </li>
<li>within a function to only have one level of abstraction. </li>
</ul>
<p>I already cleaned the following method up a bit by extracting a few methods (<code>RemoveFontColor()</code>, <code>RemoveTextHighlight()</code>). But i am not sure if the few-liners (font-style, font-weight, etc.) should be extracted into a method as well. The advise from the author is to not mix different-levels of abstraction within a function because this could lead to other details creeping in. This would mean that even the two liners will be extracted into their own methods.</p>
<h3>The partly refactored code example</h3>
<pre><code>private string Fix(FixPreferences preferences,string value)
{
if (preferences.IsRemoveBold) {
value = value.Replace("font-weight:bold", "font-weight:normal");
value = value.Replace("font-weight: bold", "font-weight:normal");
}
if (preferences.IsRemoveItalics) {
value = value.Replace("font-style:italic;", "font-style:normal;");
value = value.Replace("font-style: italic;", "font-style:normal;");
}
if (preferences.IsRemoveFontColor) {
value = RemoveFontColor(value);
}
if (preferences.IsRemoveTextHighlight) {
value = RemoveTextHighlight(value);
}
if (preferences.IsRemoveStrikethrough){
value =
value.Replace("text-decoration: line-through;", "text-decoration:none;");
value =
value.Replace("text-decoration:line-through;", "text-decoration:none;");
}
if (preferences.IsRemoveUnderline)
{
value =
value.Replace("text-decoration: underline;", "text-decoration:none;");
value =
value.Replace("text-decoration:underline;", "text-decoration:none;");
}
return value;
}
</code></pre>
<h2>Update</h2>
<p>I changed to extract even the few lines - but it still looks not pretty. </p>
<pre><code> private string Fix(ChangeLogFixOperationPreferences preferences,string value)
{
if (preferences.IsRemoveBold)
value = RemoveBold(value);
if (preferences.IsRemoveItalics)
value = RemoveItalics(value);
if (preferences.IsRemoveFontColor)
value = RemoveFontColor(value);
if (preferences.IsRemoveTextHighlight)
value = RemoveTextHighlight(value);
if (preferences.IsRemoveStrikethrough)
value = RemoveStrikethrough(value);
if (preferences.IsRemoveUnderline)
value = RemoveUnderline(value);
if (preferences.IsResetFontSize)
value = ResetFontSize(value);
return value;
}
</code></pre>
<p>Is there a better way - for example to put the preferences and the methods into a dictionary and for each preference that is set to true the function from the dictionary is called within a loop?</p>
<h3>My question</h3>
<ul>
<li>How would you refactor the code above? </li>
<li>Are there any ways to group the different <code>font-*</code> or <code>text-decoration:*</code> togehter in one function? Would that be wise since it violates the single responsibility pattern (SRI)?</li>
<li>Update: Would you recommend calling a function from a dictionary
<ul>
<li><a href="https://stackoverflow.com/questions/4233536/c-sharp-store-functions-in-a-dictionary">store functions in a dictionary</a> or may be </li>
<li><a href="https://stackoverflow.com/questions/8251951/call-a-method-dynamically-based-on-some-other-variable">call method dynamically</a> or </li>
<li>from Jon Skeet <a href="https://stackoverflow.com/questions/5125717/how-to-store-functions-in-dictionary-with-uint-as-key-c">storing functions in a dictionary by using Action</a></li>
</ul></li>
</ul>
|
[] |
[
{
"body": "<p>First of all, each condition and formatting will be moved to your own class. Let's create a common interface:</p>\n\n<pre><code>interface FormattingRemover\n{\n bool Match(string value);\n string RemoveFormat(string value);\n}\n</code></pre>\n\n<p>Now we can use it to abstract the formatting:</p>\n\n<pre><code>public class RemoveBold : FormattingRemover\n{\n public bool Match(string value) {\n // your condition here\n return true;\n }\n\n public string RemoveFormat(string value) {\n return RemoveBold(value);\n }\n}\n</code></pre>\n\n<p>In your class you'll need a list with all implementantions of FormattingRemover, iterate over it and when the value matches, you can remove its formatting.</p>\n\n<pre><code>private removers = AllRemovers();\n\nprivate string Fix(ChangeLogFixOperationPreferences preferences,string value)\n{\n foreach (var remover in removers)\n {\n if (remover.Match(value))\n {\n value = remover.RemoveFormat(value);\n }\n }\n\n return value;\n}\n</code></pre>\n\n<p>For now on, you just need to add new implementations to provide it with AllRemovers. A good idea is inject it with some DI container, like Ninject.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:13:10.287",
"Id": "46547",
"Score": "0",
"body": "What would be in `private removers = AllRemovers();` ? Would it contain a List of all `preferences` (IsRemoveBold, IsRemoveUnderline, ...) which formating should be removed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:47:39.803",
"Id": "46561",
"Score": "1",
"body": "`AllRemovers()` is a method which populate and returns a List of all implementantions of `FormattingRemover`. The class `RemoveBold` is an example of how this should be done."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T13:53:45.897",
"Id": "29447",
"ParentId": "29444",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T12:46:22.490",
"Id": "29444",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Small function and level of abstraction - clean code - refactor further"
}
|
29444
|
<p>It simply searches for an empty row in a given destination. If it is empty, it performs certain actions (copying, pasting, etc.). If it is not empty, it goes to another row. I managed to do it with dozens of <code>If</code> formulas, but doing it in such a way seems really ineffective. Moreover, doing it in such a way puts a severe limitation on the number of <code>If</code>s I can put in my code. </p>
<p>My code is too long and cannot be executed. Is there a way to ameliorate my code somehow?</p>
<pre><code>Sub My_Macro
Application.ScreenUpdating = False
Dim Worksheet As Worksheets
startrow = Worksheets("GUTS").Cells(10, 1) 'Here I denote value 1
endrow = Worksheets("GUTS").Cells(11, 1) 'Here I denote value 1000
For x = startrow To endrow
If Cells(x, "O").Value = "P" Or Cells(x, "O").Value = "R" Then
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "C") = "" Then
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "C") = "Pur"""
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "C") = "Pur"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "H" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "E").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "C") = "Pur"
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Else
If Cells(x, "O").Value = "S" Then
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "C") = "" Then
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 2, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 3, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 4, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 1, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 5, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 6, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 7, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 8, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 9, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 10, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 11, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 12, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 13, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 14, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 15, "C") = "Sale"
Else
If Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "C") = "" Then
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "A").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F" & x, "G" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "E").PasteSpecial xlPasteAll
Range("I" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "H").PasteSpecial xlPasteAll
Range("J" & x).Copy
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "J").PasteSpecial xlPasteAll
Worksheets(Cells(x, "P").Value).Cells(Cells(x, "Q").Value + 16, "C") = "Sale"
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Else
If Cells(x, "O").Value = "C" Or Cells(x, "O").Value = "N" Then
Sheets("Manual processing").Rows("3:3").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("P" & x).Copy
Sheets("Manual processing").Range("A3").PasteSpecial Paste:=xlPasteValues
Range("C" & x, "O" & x).Copy
Sheets("Manual processing").Range("B3").PasteSpecial Paste:=xlPasteValues
Range("Q" & x).Copy
Sheets("Manual processing").Range("O3").PasteSpecial Paste:=xlPasteValues
End If
End If
End If
Next
Application.ScreenUpdating = True
End Sub
</code></pre>
|
[] |
[
{
"body": "<pre><code> If Worksheets(Cells(x, \"P\").Value).Cells(Cells(x, \"Q\").Value + 4, \"C\") = \"\" Then\n Worksheets(Cells(x, \"P\").Value).Cells(Cells(x, \"Q\").Value + 4, \"A\").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove\n Range(\"F\" & x, \"H\" & x).Copy\n Worksheets(Cells(x, \"P\").Value).Cells(Cells(x, \"Q\").Value + 4, \"E\").PasteSpecial xlPasteAll\n Range(\"J\" & x).Copy\n Worksheets(Cells(x, \"P\").Value).Cells(Cells(x, \"Q\").Value + 4, \"J\").PasteSpecial xlPasteAll\n Worksheets(Cells(x, \"P\").Value).Cells(Cells(x, \"Q\").Value + 4, \"C\") = \"Pur\"\n</code></pre>\n\n<p>Copy-pasting a snippet over and over again is a hint that you need a loop or a function.</p>\n\n<p>The only difference between each snippet being that the 4 was replaced with different numbers. You could replace this code repetition with a loop (instead of 4, use the loop index). Alternatively, you could replace this code snippet with a function which takes a number, then call this function over and over again, passing it that number (which will replace the 4). You could even do both.</p>\n\n<p>Either way, the first step in making this code readable is probably to avoid repeating the same code over and over again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:12:04.333",
"Id": "29455",
"ParentId": "29450",
"Score": "12"
}
},
{
"body": "<p>As suggested by Brian, you should try a <code>for..next</code></p>\n\n<p>Something like</p>\n\n<pre><code>Dim i As Integer\nFor i = 1 To 16\n If Worksheets(Cells(x, \"P\").Value).Cells(Cells(x, \"Q\").Value + i, \"C\") = \"\" Then\n With Worksheets(Cells(x, \"P\").Value)\n .Cells(Cells(x, \"Q\").Value + i, \"A\").Resize(, 10).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove\n Range(\"F\" & x, \"H\" & x).Copy\n .Cells(Cells(x, \"Q\").Value + i, \"E\").PasteSpecial xlPasteAll\n Range(\"J\" & x).Copy\n .Cells(Cells(x, \"Q\").Value + i, \"J\").PasteSpecial xlPasteAll\n .Cells(Cells(x, \"Q\").Value + i, \"C\") = \"Pur\"\n End With\n End If\nNext i\n</code></pre>\n\n<p>And yet, several suggestions :</p>\n\n<ul>\n<li>use <code>With</code> statement when dealing with the same object on several lines</li>\n<li>be careful with your <code>Range</code> and <code>Cells</code> statements because you don't seem to know where you are working on. You'd better double-check by <em>almost always</em> using <code>Worksheets(\"Sheet1\").Range(\"A1\")</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T09:36:06.410",
"Id": "29488",
"ParentId": "29450",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "29488",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:10:02.143",
"Id": "29450",
"Score": "7",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Searching for an empty row in a given destination"
}
|
29450
|
<p>The following code works but is slow and I know can be better, just don't understand how to make it work. The end result is displaying the actual driving distance from the users current location to multiple locations (I'm only including two end locations here to try and save space). This way they can see which location is actually closer to where they currently are. Right now I'm making multiple calls when I know I should be able to pass in everything at once.</p>
<p>In <code>Locations.java</code>, in <code>getLastLocation()</code> I'm calling both <code>FirstDownloadTask</code> and <code>SecondDownloadTask</code> in order to set the text to the correct <code>TextView</code> for the destination location being passed in. How can I change this so I only have one <code>DownloadTask</code> and <code>ParserTask</code> and when I call <code>DownloadTask</code> be able to pass in more than one URL? (ex: <code>firstDownloadTask.execute(url1, url2)</code>) Since <code>ParserTask</code> processes one JSON string, how can I modify this so that it tells <code>ParserTask</code> the correct <code>TextView</code> to set based on the <code>String url</code> being processed?</p>
<p>When I try to pass in multiple parameters, it sets the text of each <code>TextView</code> to the distance of the end location that was passed in last. I can't figure out how to tell it to process the first distance and set the first <code>TextView</code> and move on to the next and so on. Like I said, it does currently work, just not as good as it could.</p>
<p><strong>Update</strong></p>
<p>Still trying to get it working, following along with the short example seen <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="nofollow">on the Android Developers site</a>.</p>
<p><strong>Update 2</strong></p>
<p>I merged the two <code>AsyncTask</code> classes (<code>FirstDownloadTask</code> and <code>SecondDownloadTask</code> merged to <code>DownloadTask</code>) and am passing in both destination URLs. I also moved declaring the <code>TextViews</code> into <code>onPostExecute</code>, trying to pass them in individually along with the URL. I updated the <code>Locations.java</code> below, commenting out what I removed and adding the new class.</p>
<p>Now when I run it but get the LogCat error:</p>
<blockquote>
<p>Cannot execute task: the task is already running</p>
</blockquote>
<p><strong>LogCat</strong></p>
<pre><code>08-07 08:56:29.378: E/AndroidRuntime(13918): FATAL EXCEPTION: main
08-07 08:56:29.378: E/AndroidRuntime(13918): java.lang.IllegalStateException: Cannot execute task: the task is already running.
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.AsyncTask.execute(AsyncTask.java:534)
08-07 08:56:29.378: E/AndroidRuntime(13918): at com.android.project.Locations$DownloadTask.onPostExecute(Locations.java:270)
08-07 08:56:29.378: E/AndroidRuntime(13918): at com.android.project.Locations$DownloadTask.onPostExecute(Locations.java:1)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.Handler.dispatchMessage(Handler.java:99)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.os.Looper.loop(Looper.java:137)
08-07 08:56:29.378: E/AndroidRuntime(13918): at android.app.ActivityThread.main(ActivityThread.java:5059)
08-07 08:56:29.378: E/AndroidRuntime(13918): at java.lang.reflect.Method.invokeNative(Native Method)
08-07 08:56:29.378: E/AndroidRuntime(13918): at java.lang.reflect.Method.invoke(Method.java:511)
08-07 08:56:29.378: E/AndroidRuntime(13918): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
08-07 08:56:29.378: E/AndroidRuntime(13918): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
08-07 08:56:29.378: E/AndroidRuntime(13918): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p><strong>Locations.java</strong></p>
<pre><code>private Location currentLocation = null;
private LocationManager locationManager;
private GeoPoint currentPoint;
ArrayList<LatLng> markerPoints;
public class Locations extends Fragment {
// onCreate, onActivityCreated
public void getLastLocation() {
String provider = getBestProvider();
currentLocation = locationManager.getLastKnownLocation(provider);
if (currentLocation != null) { setCurrentLocation(currentLocation); }
this.markerPoints = new ArrayList<LatLng>();
// Get current position
LatLng fromLocation = new LatLng(currentLocation.getLatitude(),
currentLocation.getLongitude());
// Set destination locations
LatLng dest1 = new LatLng(35.5158335, -82.7046222);
LatLng dest2 = new LatLng(35.4533462, -82.3823722);
Locations.this.markerPoints.add(fromLocation);
Locations.this.markerPoints.add(dest1);
Locations.this.markerPoints.add(dest2);
String url1 = Locations.this.getDirectionsUrl(fromLocation, dest1);
String url2 = Locations.this.getDirectionsUrl(fromLocation, dest2);
new DownloadTask().execute(url1, url2); // Passing in both url1 and url2 now
/* FirstDownloadTask firstDownloadTask = new FirstDownloadTask();
SecondDownloadTask secondDownloadTask = new SecondDownloadTask();
// Start downloading json data from Google Directions API
firstDownloadTask.execute(url1);
secondDownloadTask.execute(url2); */
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) { sb.append(line); }
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Changed FirstDownloadTask and SecondDownloadTask to:
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urlList) {
try {
ArrayList<String> returnList = new ArrayList<String>();
for (String url : urlList) {
String data = Locations.this.downloadUrl(url);
returnList.add(data);
if (isCancelled()) break;
}
return returnList;
} catch (Exception e) {
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(ArrayList<String> results) {
super.onPostExecute(results);
TextView tv1 = (TextView) getActivity().findViewById(R.id.textView1);
TextView tv2 = (TextView) getActivity().findViewById(R.id.textView2);
TextView[] views = { tv1, tv2 };
ParserTask parserTask = new ParserTask();
int i = 0;
for (String url : results) { // Trying to execute url1 and set tv1 first then execute url2 and set tv2 second
parserTask.execute(url); // Trying to execute correct url
parserTask.setTextView(views[i]); // Trying to set text to correct TextView
i++;
}
}
}
private class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
private TextView mTextView;
protected ParserTask() {
super();
mTextView = null;
}
// Set the TextView to display
public void setTextView(TextView textView) {
mTextView = textView;
}
@Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
try {
ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
for (int i = 0; i < jsonData.length; i++) {
JSONObject jObject = new JSONObject(jsonData[i]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
if (isCancelled()) break;
}
return routes;
} catch (Exception e) {
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {
if (result.size() < 1) {
Toast.makeText(getActivity(), "No Points", Toast.LENGTH_LONG).show();
return;
}
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
}
}
mTextView.setText("(" + distance + " away)");
}
}
}
/* private class FirstDownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urlList) {
try {
ArrayList<String> returnList = new ArrayList<String>();
for (String url : urlList) {
// Fetching the data from web service
String data = Locations.this.downloadUrl(url);
returnList.add(data);
}
return returnList;
} catch (Exception e) {
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(ArrayList<String> results) {
super.onPostExecute(results);
TextView tv1 = (TextView) getActivity().findViewById(R.id.textView1);
FirstParserTask parserTask = new FirstParserTask();
for (String url : results) {
parserTask.execute(url);
parserTask.setFirstTextView(tv1);
}
}
}
private class FirstParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
private TextView mTextView;
protected FirstParserTask() {
super();
mTextView = null;
}
public void setFirstTextView(TextView textView) { mTextView = textView; }
@Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
try {
ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
for (int i = 0; i < jsonData.length; i++) {
JSONObject jObject = new JSONObject(jsonData[i]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
}
return routes;
} catch (Exception e) {
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(
ArrayList<List<HashMap<String, String>>> result) {
if (result.size() < 1) {
return;
}
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
}
}
mTextView.setText("Location 1 is (" + distance + " away)");
}
}
}
private class SecondDownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urlList) {
try {
ArrayList<String> returnList = new ArrayList<String>();
for (String url : urlList) {
// Fetching the data from web service
String data = Locations.this.downloadUrl(url);
returnList.add(data);
}
return returnList;
} catch (Exception e) {
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(ArrayList<String> results) {
super.onPostExecute(results);
TextView tv2 = (TextView) getActivity().findViewById(R.id.textView2);
SecondParserTask parserTask = new SecondParserTask();
for (String url : results) {
parserTask.execute(url);
parserTask.setSecondTextView(tv2);
}
}
}
private class SecondParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
private TextView mTextView;
protected SecondParserTask() {
super();
mTextView = null;
}
public void setSecondTextView(TextView textView) { mTextView = textView; }
// Parsing the data in non-ui thread
@Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
try {
ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
for (int i = 0; i < jsonData.length; i++) {
JSONObject jObject = new JSONObject(jsonData[i]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
}
return routes;
} catch (Exception e) {
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(
ArrayList<List<HashMap<String, String>>> result) {
if (result.size() < 1) { return; }
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
}
}
mTextView.setText("Location 2 (" + distance + " away)");
}
}
} */
}
</code></pre>
<p><strong>DirectionsJSONParser.java</strong></p>
<pre><code>public class DirectionsJSONParser {
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j))
.getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j))
.getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps
.get(k)).get("polyline")).get("points");
List<LatLng> list = this.decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat",
Double.toString((list.get(l)).latitude));
hm.put("lng",
Double.toString((list.get(l)).longitude));
path.add(hm);
}
}
}
routes.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng(((lat / 1E5)), ((lng / 1E5)));
poly.add(p);
}
return poly;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Finally figured it out! By doing this, in my application code, I was able to reduce the number of AsyncTask class lines from nearly 400 to 100.</p>\n\n<p>Here's the adjusted code for anyone interested. I'm only including the relevant parts for the sake of saving space.</p>\n\n<p><strong>No changes were made to DirectionsJSONParser.java</strong></p>\n\n<p><strong>Locations.java</strong></p>\n\n<pre><code>public void getLastLocation() {\n // Nothing changed above this...\n // Get current position\n LatLng fromLocation = new LatLng(currentLocation.getLatitude(), \n currentLocation.getLongitude());\n // Set destination locations\n LatLng dest1 = new LatLng(35.5158335, -82.7046222);\n LatLng dest2 = new LatLng(35.4533462, -82.3823722); // btw these are completely random\n LatLng dest3 = new LatLng(35.1234567, -82.1234567); // Just for fun, add a 3rd\n LatLng dest4 = new LatLng(35.7654321, -82.7654321); // and a 4th\n\n Locations.this.markerPoints.add(fromLocation);\n Locations.this.markerPoints.add(dest1);\n Locations.this.markerPoints.add(dest2);\n Locations.this.markerPoints.add(dest3);\n Locations.this.markerPoints.add(dest4);\n\n String url1 = Locations.this.getDirectionsUrl(fromLocation, dest1);\n String url2 = Locations.this.getDirectionsUrl(fromLocation, dest2);\n String url3 = Locations.this.getDirectionsUrl(fromLocation, dest3);\n String url4 = Locations.this.getDirectionsUrl(fromLocation, dest4);\n\n new DownloadTask().execute(url1, url2, url3, url4);\n}\n\nprivate class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {\n @Override\n protected ArrayList<String> doInBackground(String... urlList) {\n try {\n ArrayList<String> returnList = new ArrayList<String>();\n for (String url : urlList) {\n // Fetching the data from web service\n String data = Locations.this.downloadUrl(url);\n returnList.add(data);\n }\n return returnList;\n } catch (Exception e) {\n Log.d(\"Background Task\", e.toString());\n return null; // Failed, return null\n }\n }\n\n // Executes in UI thread, after the execution of doInBackground()\n @Override\n protected void onPostExecute(ArrayList<String> results) {\n super.onPostExecute(results);\n TextView tv1 = (TextView) getActivity().findViewById(R.id.textView1);\n TextView tv2 = (TextView) getActivity().findViewById(R.id.textView2);\n TextView tv3 = (TextView) getActivity().findViewById(R.id.textView3);\n TextView tv4 = (TextView) getActivity().findViewById(R.id.textView4);\n\n String s1 = \"Location 1 \";\n String s2 = \"Location 2 \";\n String s3 = \"Location 3 \";\n String s4 = \"Location 4 \";\n\n TextView[] views = { tv1, tv2, tv3, tv4 };\n String[] strings = { s1, s2, s3, s4 };\n\n int i = 0;\n for (String url : results) {\n ParserTask parserTask = new ParserTask(views[i], strings[i]);\n parserTask.execute(url);\n i++;\n }\n }\n}\n\n/** A class to parse the Google Places in JSON format */\nprivate class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {\n\n private TextView mTextView;\n private String sString;\n\n public ParserTask(TextView views, String strings) {\n this.mTextView = views;\n this.sString = strings;\n }\n\n @Override\n protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {\n try {\n ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();\n for (int i = 0; i < jsonData.length; i++) {\n JSONObject jObject = new JSONObject(jsonData[i]);\n DirectionsJSONParser parser = new DirectionsJSONParser();\n // Starts parsing data\n routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);\n }\n return routes;\n } catch (Exception e) {\n Log.d(\"Background task\", e.toString());\n return null; // Failed, return null\n }\n }\n\n // Executes in UI thread, after the parsing process\n @Override\n protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {\n if (result.size() < 1) {\n Toast.makeText(getActivity(), \"No Points\", Toast.LENGTH_LONG).show();\n return;\n }\n\n // Traversing through all the routes\n for (int i = 0; i < result.size(); i++) {\n // Fetching i-th route\n List<HashMap<String, String>> path = result.get(i);\n String distance = \"No distance\";\n // Fetching all the points in i-th route\n for (int j = 0; j < path.size(); j++) {\n HashMap<String, String> point = path.get(j);\n if (j == 0) {\n distance = point.get(\"distance\");\n continue;\n }\n }\n // Set TextViews\n for (int t = 0; t < 4; t++) {\n mTextView.setText(sString + \"(\" + distance + \" away)\");\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T16:01:35.397",
"Id": "29559",
"ParentId": "29453",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29559",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:32:27.703",
"Id": "29453",
"Score": "1",
"Tags": [
"java",
"android",
"asynchronous"
],
"Title": "Can these async tasks be merged together?"
}
|
29453
|
<p>I am working on a C#.Net application that will generate an Excel report from a template. Although the code's not in the app yet, it will pull data from a SQL Server database to populate the report.</p>
<p>I am asking for help in reviewing my class design. My code is below, with some details of the functions removed for simplicity (if someone feels like they need to see them in order to help, I can add them).</p>
<pre><code>using System;
namespace RGBBProgramSummary
{
class Program
{
static void Main()
{
ReportSheet ProgramSummary = new ReportSheet("Program Summary");
ProgramSummary.CleanUp();
}
}
}
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace RGBBProgramSummary
{
class ReportBook
{
public bool Error;
public DateTime RunDate;
private string FileName;
static Application ExcelApp = new Application();
public Workbooks reportWBs = ExcelApp.Workbooks;
public Workbook ReportWB;
public ReportBook()
{
RunDate = GetRunDate();
FileName = GetFileName(RunDate);
File.Copy(Properties.Settings.Default.Template, FileName);
ReportWB = reportWBs.Open(FileName);
//ExcelApp.Visible = true;
}
private DateTime GetRunDate()
{
...
return DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek - 2);
}
private String GetFileName(DateTime RunDate)
{
string FileName;
...
return Properties.Settings.Default.ReportPath + FileName;
}
}
}
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace RGBBProgramSummary
{
class ReportSheet : ReportBook
{
private Worksheet reportWS;
public ReportSheet(string SheetName)
{
reportWS = ReportWB.Worksheets[SheetName];
BuildHeader(reportWS);
}
public void CleanUp()
{
ReportWB.Save();
ReportWB.Close();
Marshal.ReleaseComObject(reportWS);
Marshal.ReleaseComObject(reportWBs);
Marshal.ReleaseComObject(ReportWB);
}
private void BuildHeader(Worksheet WS)
{
int WeekColumn = 0;
int MonthColumn = 0;
...
int j = CountOfWeeks();
...
List<string> MonthList = GetMonthList();
...
}
private int CountOfWeeks()
{
int RunDateWeek
int FirstDateWeek
...
return RunDateWeek - FirstDateWeek + 1;
}
private List<string> GetMonthList()
{
List<string> MonthList = new List<string>();
...
return MonthList;
}
}
}
</code></pre>
<p>As you can see, I really only have 2 classes. <code>ReportBook</code> represents the Workbook itself, and <code>ReportSheet</code> represents the Worksheet (<code>ReportSheet</code> inherits from <code>ReportBook</code>). I'm wondering if that's overkill, and really if they should be consolidated into one class. At the least, I would need to make changes if I ever wanted to add an additional worksheet (for one, I wouldn't want to open the workbook in the constructor of the base class then).</p>
<p>Also, I was going create a function in the <code>ReportSheet</code> class to read from the aforementioned SQL DB. But, after reading answers to another question, I'm thinking that the read from the DB should be in it's own class.</p>
|
[] |
[
{
"body": "<p>Although arguably a Pandora's box of other complications, have you considered ditching the Interop libraries and driving this through Ace/Jet drivers via OleDB? Too often do I see well-intentioned applications fall over because Excel gets upgraded. Best-case scenario you'll have to manage multiple releases, whereas oftentimes you're stuck redeveloping because of core changes that break existing methods.</p>\n\n<p>Even when I need specific functions available only to the Interop libraries, I try to avoid using an actual reference in my project. You can dynamically marshal your Excel.Application object if you're building this in .NET 4.0, and it gives you some flexibility depending on what you're trying to achieve.</p>\n\n<p>If you're just interested about data transfer, I'd consider making a move to OleDB if you're comfortable with SQL-based database querying.</p>\n\n<p>I think by omitting your specific methods of how the data gets into the sheet, you're leaving out one of the most important parts of the application in terms of performance. Are you dumping the data cell by cell? I'm assuming coming from SQL the data will be in DataSet/DataTable format, so you could dump to an array, and then point to an address in the sheet.</p>\n\n<p>I do like that you've avoided the dreaded double-dot, and are taking the proper Marshalling release methods to make sure Excel goes away when it's supposed to.</p>\n\n<p>/$.02</p>\n\n<p>-- Locke</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:24:36.577",
"Id": "47262",
"Score": "0",
"body": "Thanks for the feedback. I have never actually heard of Ace or Jet (as bad as that might be), but went and checked them out. I'm not sure if they'll work or not, because I do really need to dump the data cell by cell. The template I'm populating is highly-formatted, with rows of data heavily mixed with rows of hard-coded values. Maybe I'm underestimating the ACE and Jet technologies though. Lastly, do you have a link that would help me find out more information with regards to your second paragraph? I'm intrigued. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T04:02:26.837",
"Id": "29774",
"ParentId": "29454",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:03:01.383",
"Id": "29454",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"excel"
],
"Title": "Class design - Excel report"
}
|
29454
|
<p>I am looking for feedback on a solution to the following problem posed from a book that I'm working through (<em>Java: How To Program</em> 9th Edition):</p>
<blockquote>
<p>Continuing the discussion in Exercise 16.20, we reiterate the
importance of designing check-writing systems to prevent alteration of
check amounts. One common security method requires that the amount be
written in numbers and spelled out in words as well. Even if someone
is able to alter the numerical amount of the check, it’s extremely
difficult to change the amount in words. Write an application that
inputs a numeric check amount that’s less than £1000 and writes the
word equivalent of the amount. For example, the amount 112.43 should
be written as</p>
<p>ONE hundred TWELVE and 43 pence</p>
</blockquote>
<p>I'm interested in solutions which cover the areas I have studied so far, those being:</p>
<blockquote>
<ol>
<li>Introduction to Computers and Java</li>
<li>Introduction to Java Applications</li>
<li>Introduction to Classes, Objects, Methods and Strings</li>
<li>Control Statements: Part 1</li>
<li>Control Statements: Part 2</li>
<li>Methods: A Deeper Look</li>
<li>Arrays and ArrayLists</li>
<li>Classes and Objects: A Deeper Look</li>
<li>Object-Oriented Programming: Inheritance</li>
<li>Object-Oriented Programming: Polymorphism</li>
<li>Exception Handling: A Deeper Look</li>
<li>GUI Components: Part 1 (Swing)</li>
<li>Strings, Characters and Regular Expressions</li>
</ol>
</blockquote>
<p>I have been a bit naughty by jumping ahead of the text to use a little recursion within the <code>readMe()</code> method. I figured from the description of recursion that the line of code in question would behave this way and I was right.</p>
<p>I can't help feeling that the way I have implemented the <code>readMe()</code> method is somewhat messy and I can see that it would not scale very well beyond £1000 or four digits. Is there a simpler way of doing this? All forms of feedback are welcome.</p>
<pre><code>import java.util.Scanner;
public class WordCheckAmount {
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
String userInput;
boolean correctInput = false;
do
{
System.out.println( "Please enter an amount below 1000" );
userInput = sc.nextLine();
System.out.println();
if( userInput.indexOf( '.' ) < 0 && validateAmount( userInput ) ) // no decimal point
{
correctInput = true;
readMe( userInput );
}
if( userInput.indexOf( '.' ) > 0 && validatePointAmount( userInput ) ) // decimal point
{
correctInput = true;
String[] tokens = userInput.split( "\\." );
readMe( tokens[ 0 ] );
System.out.printf( "and " );
readMe( tokens[ 1 ] );
System.out.println( "pence" );
}
}while( !correctInput );
}
public static boolean validatePointAmount( String amount )
{
return amount.matches( "\\d{0,3}.?\\d{0,2}" );
}
public static boolean validateAmount( String amount )
{
return amount.matches( "\\d{0,3}" );
}
public static void readMe( String amount )
{
String[] oneThruNineteen = { "NULL", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX",
"SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE",
"THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN", "NINETEEN" };
String[] theDecades = { "NULL", "NULL", "TWENTY", "THIRTY", "FOURTY", "FIFTY",
"SIXTY", "SEVENTY", "EIGHTY", "NINETY" };
int theLength = amount.length();
switch( theLength )
{
case 3: // 3 digits
System.out.printf( "%s ", oneThruNineteen[ Character.getNumericValue( amount.charAt( 0 ) ) ] );
System.out.printf( "hundred " );
int testMe = Character.getNumericValue( amount.charAt( 1 ) );
if( testMe < 2 ) // if tens unit in the teens
System.out.printf( "%s ", oneThruNineteen[ Integer.parseInt( amount.substring( 1, 3 ) ) ] );
else // if tens unit twenty or higher
{
String feedMe = amount.substring( 1 , 3 );
readMe( feedMe ); // recursion I presume? feedback for 2 digits
}
break;
case 2: // 2 digits
int testMe2 = Character.getNumericValue( amount.charAt( 0 ) );
if( testMe2 < 2 ) // if tens unit in the teens
System.out.printf( "%s ", oneThruNineteen[ Integer.parseInt( amount ) ] );
else // if tens unit twenty or higher
{
System.out.printf( "%s ", theDecades[ Character.getNumericValue( amount.charAt( 0 ) ) ] );
int testMe3 = Character.getNumericValue( amount.charAt( 1 ) );
if( testMe3 > 0 ) // if next digit is higher than 0, otherwise you get TWENTY NULL for 20 etc
System.out.printf( "%s ", oneThruNineteen[ Character.getNumericValue( amount.charAt( 1 ) ) ] );
}
break;
case 1: // just the 1 digit
System.out.printf( "%s ", oneThruNineteen[ Integer.parseInt( amount ) ] );
break;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:58:10.613",
"Id": "46569",
"Score": "0",
"body": "Check out this Stack Overflow answer: http://stackoverflow.com/a/3911982/300257"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T08:13:45.333",
"Id": "59551",
"Score": "0",
"body": "Also see http://codereview.stackexchange.com/q/6780/9357 and http://codereview.stackexchange.com/q/30525/9357."
}
] |
[
{
"body": "<p>Yes! Your code is more complicated than it needs to be.</p>\n\n<ul>\n<li>You treat the String as a String instead of first parsing it as a number and treating it as a number. It is more complicated to treat chars than numbers when you want to use them as numbers.</li>\n<li>You have some code duplication near the logic of <code>if (testMe < 2) ...</code></li>\n<li>Instead of printing directly, it is better to return a String and let the caller print</li>\n</ul>\n\n<p>Here is a method I came up with, that returns a string:</p>\n\n<pre><code>static String[] oneThruNineteen = { \"NULL\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\",\n \"SEVEN\", \"EIGHT\", \"NINE\", \"TEN\", \"ELEVEN\", \"TWELVE\",\n \"THIRTEEN\", \"FOURTEEN\", \"FIFTEEN\", \"SIXTEEN\", \"SEVENTEEN\",\n \"EIGHTEEN\", \"NINETEEN\" };\n\nstatic String[] theDecades = { \"NULL\", \"NULL\", \"TWENTY\", \"THIRTY\", \"FOURTY\", \"FIFTY\",\n \"SIXTY\", \"SEVENTY\", \"EIGHTY\", \"NINETY\" };\npublic static String numToStr(int amount) {\n String str = \"\";\n if (amount >= 100) {\n str += oneThruNineteen[ amount / 100] + \" hundred \";\n str += numToStr(amount % 100);\n }\n else if (amount >= 20) {\n str += theDecades[ amount / 10 ];\n str += numToStr(amount % 10);\n }\n else {\n str += oneThruNineteen[ amount ];\n }\n return str;\n}\n</code></pre>\n\n<p>It is possible to improve even further to add thousands, millions, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T23:37:51.217",
"Id": "36315",
"ParentId": "29457",
"Score": "7"
}
},
{
"body": "<p>The main body of could is really easy to be written as a recursive program:</p>\n\n<pre><code>final private static String[] units = {\"Zero\",\"One\",\"Two\",\"Three\",\"Four\",\n \"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\n \"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\",\"Fifteen\",\n \"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"};\nfinal private static String[] tens = {\"\",\"\",\"Twenty\",\"Thirty\",\"Forty\",\"Fifty\",\n \"Sixty\",\"Seventy\",\"Eighty\",\"Ninety\"};\n\npublic static String convert(Integer i) {\n if( i < 20) return units[i];\n if( i < 100) return tens[i/10] + ((i % 10 > 0)? \" \" + convert(i % 10):\"\");\n if( i < 1000) return units[i/100] + \" Hundred\" + ((i % 100 > 0)?\" and \" + convert(i % 100):\"\");\n if( i < 1000000) return convert(i / 1000) + \" Thousand \" + ((i % 1000 > 0)? \" \" + convert(i % 1000):\"\") ;\n return convert(i / 1000000) + \" Million \" + ((i % 1000000 > 0)? \" \" + convert(i % 1000000):\"\") ;\n}\n</code></pre>\n\n<p>Now just cover pence aswell:</p>\n\n<pre><code>public static String convert(Double i) {\n double pence = (int)((i-((int)i))*100);\n string result = convert((int)i);\n return pence.Equals(0d) ? result : result + \" and \" + pence \" pence\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-27T15:46:16.200",
"Id": "68088",
"ParentId": "29457",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:24:17.587",
"Id": "29457",
"Score": "6",
"Tags": [
"java",
"beginner",
"recursion",
"converting",
"numbers-to-words"
],
"Title": "Writing the word equivalent of a check (cheque) amount"
}
|
29457
|
<p>Please criticize the <code>MatrixNotThreadSafe</code> class and other classes. How can I improve the design of the Matrix interface? How can I make the classes and tests clearer?</p>
<p><a href="https://github.com/Leonideveloper/Matrix/tree/master/Matrix/src/com/gmail/leonidandand/matrix" rel="nofollow">Code on GitHub</a></p>
<p><strong>Position.java</strong></p>
<pre><code>public class Position {
public final int row;
public final int column;
public Position(int row, int column) {
if (row < 0 || column < 0) {
throw new IllegalArgumentException();
}
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || !(obj instanceof Position)) {
return false;
}
Position other = (Position) obj;
return (this.row == other.row) && (this.column == other.column);
}
}
</code></pre>
<p><strong>TestPosition.java</strong></p>
<pre><code>public class TestPosition {
@Test
public void testCreation() {
Position pos = new Position(1, 2);
assertEquals(1, pos.row);
assertEquals(2, pos.column);
}
@Test
public void testRowsIsZero() {
new Position(0, 2);
}
@Test
public void testColumnsZero() {
new Position(2, 0);
}
@Test(expected=IllegalArgumentException.class)
public void testIllegalRows() {
new Position(-1, 2);
}
@Test(expected=IllegalArgumentException.class)
public void testIllegalColumns() {
new Position(1, -2);
}
@Test
public void testEquals() {
assertTrue(new Position(1, 2).equals(new Position(1, 2)));
assertFalse(new Position(1, 2).equals(new Position(0, 0)));
assertFalse(new Position(1, 2).equals(null));
}
}
</code></pre>
<p><strong>Dimension.java</strong></p>
<pre><code>public class Dimension {
public final int rows;
public final int columns;
public Dimension(int rows, int columns) {
if (rows <= 0 || columns <= 0) {
throw new IllegalArgumentException(
"Dimension constructor: rows and columns must be positive");
}
this.rows = rows;
this.columns = columns;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Dimension) {
Dimension other = (Dimension) obj;
return rows == other.rows && columns == other.columns;
}
return false;
}
@Override
public int hashCode() {
return rows * columns;
}
}
</code></pre>
<p><strong>TestDimension.java</strong></p>
<pre><code>public class TestDimension {
@Test
public void testCreation() {
Dimension dim = new Dimension(1, 2);
assertEquals(1, dim.rows);
assertEquals(2, dim.columns);
}
@Test(expected=IllegalArgumentException.class)
public void testRowsIsZero() {
new Dimension(0, 1);
}
@Test(expected=IllegalArgumentException.class)
public void testRowsIsNegative() {
new Dimension(-1, 1);
}
@Test(expected=IllegalArgumentException.class)
public void testColumnsIsZero() {
new Dimension(1, 0);
}
@Test(expected=IllegalArgumentException.class)
public void testColumnsIsNegative() {
new Dimension(1, -2);
}
public void testEquals() {
assertTrue(new Dimension(33, 22).equals(new Dimension(33, 22)));
assertFalse(new Dimension(1, 2).equals(new Dimension(3, 1)));
assertFalse(new Dimension(2, 4).equals(null));
}
public void testHashCode_NotThrowsExceptions() {
new Dimension(2, 3).hashCode();
}
}
</code></pre>
<p><strong>Matrix.java</strong></p>
<pre><code>public interface Matrix<T> {
boolean contains(T elem);
Dimension getDimension();
int rows();
int columns();
T get(Position pos);
T get(int row, int column);
void set(Position pos, T value);
void set(int row, int column, T value);
void fill(T value);
void forEach(OnEachHandler<T> onEachHandler);
void swap(Position pos1, Position pos2);
}
</code></pre>
<p><strong>OnEachHandler.java</strong></p>
<pre><code>public interface OnEachHandler<T> {
void handle(Position pos, T elem);
}
</code></pre>
<p><strong>MatrixNotThreadSafe.java</strong></p>
<pre><code>public class MatrixNotThreadSafe<T> implements Matrix<T> {
private final int rows;
private final int columns;
private final T[][] values;
public MatrixNotThreadSafe(Dimension dim) {
this(dim.rows, dim.columns);
}
@SuppressWarnings("unchecked")
public MatrixNotThreadSafe(int rows, int columns) {
if (rows <= 0 || columns <= 0) {
throw new IllegalArgumentException();
}
this.rows = rows;
this.columns = columns;
this.values = (T[][]) new Object[rows][columns];
}
public MatrixNotThreadSafe(Matrix<T> other) {
this(other.rows(), other.columns());
other.forEach(new OnEachHandler<T>() {
@Override
public void handle(Position pos, T elem) {
set(pos, elem);
}
});
}
@Override
public boolean contains(T elem) {
for (int row = 0; row < rows(); ++row) {
for (int column = 0; column < columns(); ++column) {
if (elementsAreEqual(elem, get(row, column))) {
return true;
}
}
}
return false;
}
private boolean elementsAreEqual(Object e1, Object e2) {
return (e1 == e2) ||
((e1 != null) && (e1.equals(e2))) ||
((e2 != null) && (e2.equals(e1)));
}
@Override
public Dimension getDimension() {
return new Dimension(rows(), columns());
}
@Override
public int rows() {
return rows;
}
@Override
public int columns() {
return columns;
}
@Override
public T get(Position pos) {
return get(pos.row, pos.column);
}
@Override
public T get(int row, int column) {
checkIndexes(row, column);
return values[row][column];
}
private void checkIndexes(int row, int column) {
if (row < 0 || column < 0) {
throw new IllegalArgumentException(stringByRowColumn(row, column));
}
if (row >= rows() || column >= columns()) {
throw new IndexOutOfBoundsException(stringByRowColumn(row, column));
}
}
private String stringByRowColumn(int row, int column) {
return "[" + row + ", " + column + "]";
}
@Override
public void set(Position pos, T value) {
set(pos.row, pos.column, value);
}
@Override
public void set(int row, int column, T value) {
checkIndexes(row, column);
values[row][column] = value;
}
@Override
public void fill(final T value) {
forEach(new OnEachHandler<T>() {
@Override
public void handle(Position pos, T elem) {
set(pos, value);
}
});
}
@Override
public void forEach(OnEachHandler<T> onEachHandler) {
for (int row = 0; row < rows(); ++row) {
for (int column = 0; column < columns(); ++column) {
Position pos = new Position(row, column);
T elem = get(row, column);
onEachHandler.handle(pos, elem);
}
}
}
@Override
public void swap(Position pos1, Position pos2) {
T temp = get(pos1);
set(pos1, get(pos2));
set(pos2, temp);
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || !(obj instanceof Matrix<?>)) {
return false;
}
Matrix<?> other = (Matrix<?>) obj;
if (this.rows() != other.rows() || this.columns() != other.columns()) {
return false;
}
for (int row = 0; row < rows(); ++row) {
for (int column = 0; column < columns(); ++column) {
if (!elementsAreEqual(get(row, column), other.get(row, column))) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int totalHashCode = 0;
for (int row = 0; row < rows(); ++row) {
for (int column = 0; column < columns(); ++column) {
totalHashCode += hashCodeOfElement(row, column);
}
}
return totalHashCode * (rows() + columns());
}
private int hashCodeOfElement(int row, int column) {
T element = get(row, column);
return element != null ? element.hashCode() : 0;
}
}
</code></pre>
<p><strong>TestMatrixNotThreadSafe.java</strong></p>
<pre><code>public class TestMatrixNotThreadSafe {
private static final Integer VALUE = 5;
private static final int ROWS = 10;
private static final int COLUMNS = 20;
private Matrix<Integer> matrix;
@Before
public void setUp() {
this.matrix = new MatrixNotThreadSafe<Integer>(ROWS, COLUMNS);
}
@Test
public void testMatrixCopyConstructor() {
fillMatrix(matrix);
Matrix<Integer> copy = new MatrixNotThreadSafe<Integer>(matrix);
assertEquals(matrix.rows(), copy.rows());
assertEquals(matrix.columns(), copy.columns());
for (int row = 0; row < copy.rows(); ++row) {
for (int column = 0; column < copy.columns(); ++column) {
assertEquals(matrix.get(row, column), copy.get(row, column));
}
}
}
private void fillMatrix(final Matrix<Integer> matrixToFill) {
for (int row = 0; row < matrixToFill.rows(); ++row) {
for (int column = 0; column < matrixToFill.columns(); ++column) {
matrixToFill.set(row, column, elementForPosition(row, column));
}
}
}
private Integer elementForPosition(int row, int column) {
return row * column;
}
@Test
public void testInitValueIsNull() {
assertNull(matrix.get(0, 0));
}
@Test(expected=IllegalArgumentException.class)
public void testConstructorNegativeDimension() {
new MatrixNotThreadSafe<Integer>(1, -1);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructorDimensionIsZero() {
new MatrixNotThreadSafe<Integer>(0, 1);
}
@Test
public void testContains() {
assertFalse(matrix.contains(2));
matrix.set(new Position(0, 0), 2);
assertTrue(matrix.contains(2));
matrix.set(new Position(0, 0), 1);
assertFalse(matrix.contains(2));
}
@Test
public void testJustCreatedMatrixContainsNull() {
assertTrue(matrix.contains(null));
}
@Test
public void testGetDimension() {
assertEquals(new Dimension(ROWS, COLUMNS), matrix.getDimension());
}
@Test
public void testDimensionOfMatrix() {
assertEquals(ROWS, matrix.rows());
assertEquals(COLUMNS, matrix.columns());
}
@Test(expected=IllegalArgumentException.class)
public void testGetByNegativePosition() {
matrix.get(1, -1);
}
@Test(expected=IndexOutOfBoundsException.class)
public void testGetByOutOfBoundsPosition() {
matrix.get(ROWS + 1, 0);
}
@Test(expected=IllegalArgumentException.class)
public void testSetByNegativePosition() {
matrix.set(-1, 0, VALUE);
}
@Test(expected=IndexOutOfBoundsException.class)
public void testSetByOutOfBoundsPosition() {
matrix.set(0, COLUMNS + 1, VALUE);
}
@Test
public void testGetSet() {
fillMatrix(matrix);
for (int row = 0; row < ROWS; ++row) {
for (int column = 0; column < COLUMNS; ++column) {
assertEquals(elementForPosition(row, column), matrix.get(row, column));
}
}
}
@Test
public void testFill() {
final Integer one = 1;
matrix.fill(one);
for (int row = 0; row < ROWS; ++row) {
for (int column = 0; column < COLUMNS; ++column) {
assertTrue(one.equals(matrix.get(row, column)));
}
}
}
@Test
public void testFillByNullValues() {
matrix.fill(null);
for (int row = 0; row < ROWS; ++row) {
for (int column = 0; column < COLUMNS; ++column) {
assertNull(matrix.get(row, column));
}
}
}
@Test
public void testSwap() {
Matrix<Integer> matrix = new MatrixNotThreadSafe<Integer>(2, 2);
Position pos1 = new Position(0, 0);
Position pos2 = new Position(1, 1);
Integer val1 = 1;
Integer val2 = 2;
matrix.set(pos1, val2);
matrix.set(pos2, val1);
matrix.swap(pos1, pos2);
assertEquals(val2, matrix.get(pos2));
assertEquals(val1, matrix.get(pos1));
}
@Test(expected=IllegalArgumentException.class)
public void testSwapIllegalArguments() {
Position pos1 = new Position(0, 0);
Position pos2 = new Position(0, -1);
matrix.swap(pos1, pos2);
}
@Test(expected=IndexOutOfBoundsException.class)
public void testSwapPositionOutOfBounds() {
Position pos1 = new Position(0, COLUMNS + 1);
Position pos2 = new Position(0, 0);
matrix.swap(pos1, pos2);
}
@Test
public void testForEach_AllElementsAreProcessedExactlyOnce() {
final Matrix<Boolean> flags = getMatrixInitializedByFalse(ROWS, COLUMNS);
flags.forEach(new OnEachHandler<Boolean>() {
@Override
public void handle(Position pos, Boolean elem) {
assertFalse(flags.get(pos));
assertFalse(elem);
flags.set(pos, true);
}
});
for (int row = 0; row < flags.rows(); ++row) {
for (int column = 0; column < flags.columns(); ++column) {
assertTrue(flags.get(row, column));
}
}
}
private Matrix<Boolean> getMatrixInitializedByFalse(int rows, int columns) {
final Matrix<Boolean> flags = new MatrixNotThreadSafe<Boolean>(rows, columns);
for (int row = 0; row < flags.rows(); ++row) {
for (int column = 0; column < flags.columns(); ++column) {
flags.set(row, column, false);
}
}
return flags;
}
@Test
public void testForEach_Order_LeftToRight_UpToDown() {
final Matrix<Boolean> flags = getMatrixInitializedByFalse(ROWS, COLUMNS);
flags.forEach(new OnEachHandler<Boolean>() {
@Override
public void handle(Position pos, Boolean elem) {
if (!pos.equals(new Position(0, 0))) {
assertPreviousElementWasProcessed(flags, pos);
}
flags.set(pos, true);
}
});
}
private void assertPreviousElementWasProcessed(Matrix<Boolean> matrix, Position pos) {
Position positionBefore = positionBefore(matrix.rows(), matrix.columns(), pos);
assertTrue(matrix.get(positionBefore));
}
private Position positionBefore(int rows, int columns, Position pos) {
if (pos.column - 1 < 0) {
return new Position(pos.row - 1, columns - 1);
} else {
return new Position(pos.row, pos.column - 1);
}
}
@Test
public void testEquals() {
Matrix<Integer> matrix1 = new MatrixNotThreadSafe<Integer>(1, 2);
matrix1.set(0, 0, VALUE);
matrix1.set(0, 1, VALUE);
Matrix<Integer> matrix2 = new MatrixNotThreadSafe<Integer>(1, 2);
matrix2.set(0, 0, VALUE);
matrix2.set(0, 1, VALUE);
assertTrue(matrix1.equals(matrix2));
matrix2.set(0, 0, VALUE + 1);
assertFalse(matrix1.equals(matrix2));
}
@Test
public void testEquals_WithNull() {
assertFalse(matrix.equals(null));
}
@Test
public void testEquals_DifferentClass() {
assertFalse(matrix.equals(Integer.valueOf(1)));
}
@Test
public void testEquals_NullElements_DifferentTemplateParameters() {
Matrix<Integer> integerMatrix = new MatrixNotThreadSafe<Integer>(2, 2);
Matrix<Boolean> booleanMatrix = new MatrixNotThreadSafe<Boolean>(2, 2);
assertTrue(integerMatrix.equals(booleanMatrix));
}
@Test
public void testEquals_NotNullElements_DifferentTemplateParameters() {
Matrix<Integer> integerMatrix = new MatrixNotThreadSafe<Integer>(1, 1);
Matrix<Boolean> booleanMatrix = new MatrixNotThreadSafe<Boolean>(1, 1);
integerMatrix.set(0, 0, Integer.valueOf(0));
booleanMatrix.set(0, 0, Boolean.valueOf(false));
assertFalse(integerMatrix.equals(booleanMatrix));
}
@Test
public void testEquals_NullElements_SameTemplateParameters() {
assertEquals(matrix, new MatrixNotThreadSafe<Integer>(ROWS, COLUMNS));
}
@Test
public void testEquals_DifferentDimensions_NullElements() {
Matrix<Integer> matrix1 = new MatrixNotThreadSafe<Integer>(2, 2);
Matrix<Integer> matrix2 = new MatrixNotThreadSafe<Integer>(2, 1);
assertFalse(matrix1.equals(matrix2));
}
@Test
public void testEquals_NotNullElements_With_NullElements() {
Matrix<Boolean> falseElements = getMatrixInitializedByFalse(ROWS, COLUMNS);
Matrix<Boolean> nullElements = new MatrixNotThreadSafe<Boolean>(ROWS, COLUMNS);
assertFalse(falseElements.equals(nullElements));
}
@Test
public void testHashCode_NotThrowsExceptions() {
matrix.hashCode();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:57:04.527",
"Id": "46585",
"Score": "1",
"body": "My biggest issue is that it does not do anything useful yet. The proof is in the pudding. You cannot add or multiply two of them. You cannot invert one. I know some people advocate test-driven development, which is cool, but if your code does not do anything, then it is by definition useless. Once you continue implementing your class, consider how stable your inversion operation is. It can be a big deal, this is why real matrix libraries can be messy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:47:06.093",
"Id": "46605",
"Score": "0",
"body": "Is not it better to place \"useful\" operations with the matrix in separate classes? (Sorry for my bad English. Maybe I understood you incorrectly.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T19:34:58.930",
"Id": "46685",
"Score": "1",
"body": "Well, your architecture is already leading to a slow implementation. Usually the consumers of the matrix libraries expect it to run very fast. With your approach you may end up with jumping across different memory pages while performing any Matrix operation. I really do think that some sort of array could be better, given that your matrix can be represented by a 2D array easily. Most real matrix libs try to use hardware and graphics card to get stuff done fast. Anyhow, suppose you are not constrained by speed. Still, it helps to know what the consumers of the matrix class want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T19:40:36.737",
"Id": "46686",
"Score": "1",
"body": "Continued. You might want to make matrices immutable - makes code simpler to debug, is bad for performance. I would not delegate work to an outside handler; that would smell like http://c2.com/cgi/wiki?AbuseOfUtilityClasses Also, if you look at what a matrix multiplication or inversion, etc. involves, you have to look at the entire matrix, cannot really work with just one cell at a time. So, I strongly believe that inside of the Matrix class is the best place to perform matrix operations. Doing so would keep things simple and keep the scope local. I think you started polishing smth unfinished."
}
] |
[
{
"body": "<p><strong>Position</strong></p>\n\n<ul>\n<li>While it implements <code>equals()</code> it doesn't implement <code>hashCode()</code>. It should.</li>\n<li>The <code>equals()</code> method could start with a test : <code>if (this == obj) { return true; }</code> While this isn't strictly necessary it can avoid a more costly <code>instanceof</code> check.</li>\n<li>I would advise to make this class <code>final</code>, and if not, then its <code>equals()</code> and <code>hashCode()</code> method, so subclasses cannot violate <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow\">LSP</a>.</li>\n<li>You can probably get away with allowing direct field access here, but getter/setter would be better encapsulation.</li>\n</ul>\n\n<p><strong>Dimension</strong></p>\n\n<ul>\n<li>Some of the remarks for <code>Position</code> apply to <code>Dimension</code> as well.</li>\n<li><code>hashCode()</code> can be improved so that <code>new Dimension(4, 5)</code> does not map to the same hash as <code>new Dimension(5, 4)</code></li>\n</ul>\n\n<p><strong>Matrix</strong></p>\n\n<ul>\n<li>minimize the interface by getting rid of the convenience methods that take <code>int</code> params for <code>row</code> and <code>column</code>. They make the interface harder to maintain, and harder to understand.Same for the <code>rows()</code> and <code>columns()</code> method. Convenience methods seem so great, but they have to be kept in sync with the actual methods when implementations change. People looking at the interface must look at documentation to see if the methods really do the same, or not. It also makes things harder to test.</li>\n</ul>\n\n<p><strong>MatrixNotThreadSafe</strong></p>\n\n<ul>\n<li>if you switch to a single dimension array to represent Matrix content, all the double loops be gone, improving cyclomatic complexity.</li>\n<li>I would use a <code>Dimension</code> field instead of the rows and columns fields. Both <code>equals()</code> and <code>hashCode()</code> implementations will benefit.</li>\n<li>I would suggest renaming this to <code>ArrayMatrix</code>. A thread safe implementation can be named <code>ConcurrentMatrix</code> (analogous with Collections from JDK)</li>\n</ul>\n\n<p><strong>Tests</strong> </p>\n\n<ul>\n<li>Strive to have one assert per test :</li>\n</ul>\n\n<p>so change</p>\n\n<pre><code> @Test\n public void testEquals() {\n assertTrue(new Position(1, 2).equals(new Position(1, 2)));\n assertFalse(new Position(1, 2).equals(new Position(0, 0)));\n assertFalse(new Position(1, 2).equals(null));\n }\n</code></pre>\n\n<p>into :</p>\n\n<pre><code>@Test\npublic void testEqualsIdentityTrue() {\n Position position = new Position(1, 2);\n assertTrue(position.equals(position));\n}\n\n@Test\npublic void testValueEqualsTrue() {\n assertTrue(new Position(1, 2).equals(new Position(1, 2)));\n}\n\n@Test\npublic void testValueEqualsFalseIfColumnDiffers() {\n assertFalse(new Position(1, 2).equals(new Position(1, 3)));\n}\n\n@Test\npublic void testValueEqualsFalseIfRowDiffers() {\n assertFalse(new Position(1, 2).equals(new Position(3, 2)));\n}\n@Test\npublic void testEqualsFalseForNull() {\n assertFalse(new Position(1, 2).equals(null));\n}\n</code></pre>\n\n<p>(ok, I added a few too)</p>\n\n<p>You can also test whether hashCode() is in sync with equals().</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T19:48:53.863",
"Id": "29466",
"ParentId": "29458",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29466",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:28:22.473",
"Id": "29458",
"Score": "2",
"Tags": [
"java",
"thread-safety",
"matrix"
],
"Title": "Thread-safety of Matrix class"
}
|
29458
|
<p><a href="https://en.wikipedia.org/wiki/Grading_%28education%29" rel="nofollow">For anyone who's unfamiliar with this grading system</a>.</p>
<p>I'd like a general review of my code, and I have a few questions:</p>
<ol>
<li>Are plain types okay for the letter grades and credit hours, or could they be <code>public</code> <code>typedef</code>s?</li>
<li>Should <code>operator<<</code> need to call <code>calculateGPA()</code>, or should I create a <code>private</code> accessor and have that called? In order to maintain encapsulation, I'll need to keep <code>operator<<</code> as a <code>friend</code>.</li>
<li>Is the <code>for</code>-loop in <code>calculateGPA()</code> ideal for this purpose, or are there one or more STL functions that can do the same thing but more cleanly?</li>
</ol>
<p><strong>GPA.h</strong></p>
<pre><code>#ifndef GPA_H
#define GPA_H
#include <iosfwd>
#include <vector>
#include <utility>
class GPA
{
private:
std::vector<std::pair<unsigned, unsigned> > grades;
double calculateGPA() const;
public:
void add(char, unsigned);
friend std::ostream& operator<<(std::ostream&, GPA const&);
};
unsigned convertLetterGrade(char);
#endif
</code></pre>
<p><strong>GPA.cpp</strong></p>
<pre><code>#include "GPA.h"
#include <ostream>
#include <stdexcept>
void GPA::add(char letterGrade, unsigned creditHours)
{
unsigned numericalGrade = convertLetterGrade(letterGrade);
grades.push_back(std::make_pair(numericalGrade, creditHours));
}
double GPA::calculateGPA() const
{
unsigned sumGradePoints = 0;
unsigned sumCreditHours = 0;
for (auto iter = grades.cbegin(); iter != grades.cend(); ++iter)
{
sumGradePoints += iter->first * iter->second;
sumCreditHours += iter->second;
}
double totalGPA = static_cast<double>(totalGradePoints) / sumCreditHours;
return totalGPA;
}
unsigned convertLetterGrade(char letterGrade)
{
switch (letterGrade)
{
case 'a':
case 'A': return 4;
case 'b':
case 'B': return 3;
case 'c':
case 'C': return 2;
case 'd':
case 'D': return 1;
case 'f':
case 'F': return 0;
default: throw std::logic_error("Invalid Letter Grade");
}
}
std::ostream& operator<<(std::ostream& out, GPA const& obj)
{
return out << obj.calculateGPA();
}
</code></pre>
<p><strong>Main.cpp</strong></p>
<pre><code>#include "GPA.h"
#include <cstddef>
#include <iostream>
int main()
{
std::cout << "# Classes: ";
std::size_t numClasses;
std::cin >> numClasses;
GPA gpa;
for (std::size_t i = 0; i < numClasses; ++i)
{
std::cout << "\n(" << i+1 << ") Letter Grade: ";
char letterGrade;
std::cin >> letterGrade;
std::cout << " Credit Hours: ";
unsigned creditHours;
std::cin >> creditHours;
gpa.add(letterGrade, creditHours);
}
std::cout << "\n*** Total GPA: " << gpa;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:48:29.800",
"Id": "46583",
"Score": "0",
"body": "with deciding to make letter grades and credit hours public, I would ask, what advantage is there to making them public? But what are the disadvantages, weighed against the limitations of having them private.. I would be inclined to keep them private.. if this doesn't make sense let me know cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:54:03.460",
"Id": "46584",
"Score": "0",
"body": "@Skippy: With `typedef`s, this is entirely different. They generally rename a type, but doesn't have much to do with encapsulation. They could help personalize my class a bit, plus the user obviously already knows about those two variables. They just don't know about the `std::vector` inside the class (and even if I were to `typedef` that, it would obviously be `private`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:57:16.603",
"Id": "46586",
"Score": "0",
"body": "hey thnx for that, I wasn't sure if I understood yr point properly, I appreciate yr patience (I am here to learn you see :))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:01:01.157",
"Id": "46589",
"Score": "1",
"body": "@Skippy: That's why we're here. :-)"
}
] |
[
{
"body": "<p>Note that I am completely unfamiliar with the american(?) grade system and GPAs -- I am reviewing the coding style and approach, not whether or not the solution is correct.</p>\n\n<h3>General notes:</h3>\n\n<ul>\n<li><p><strong>Your</strong> <code>GPA</code> <strong>class is not really a class.</strong> It's actually just a function. It could just as well be implemented as <code>double calculateGPA(std::vector<std::pair<char, unsigned>>)</code>. Beware of the golden hammer, especially when it comes to classes.</p></li>\n<li><p>You can use <code>std::tolower()</code> to halve the size of your <code>switch</code>.</p></li>\n<li><p><code>v</code>ector comes after <code>u</code>tility in the alphabet :-)</p></li>\n<li><p>C++11 allows writing <code>>></code> in nested templates.</p></li>\n<li><p>Your program won't compile: <code>totalGradePoints</code> is called <code>sumGradePoints</code>.</p></li>\n<li><p>You can probably use <code>float</code> instead of <code>double</code>.</p></li>\n<li><p>Make the local variables in <code>calculateGPA()</code> floating point numbers from the start, and drop the cast.</p></li>\n<li><p><code>obj</code> should be called <code>gpa</code> or something like that.</p></li>\n<li><p>Write unit tests.</p></li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>Are plain types okay for the letter grades and credit hours, or could they be <code>public</code> <code>typedef</code>s?</p>\n</blockquote>\n\n<p>Either is fine. Using a <code>typedef</code> makes the <em>intent</em> of a variable a bit clearer. This added distinction between types could help the developer realizing he or she is making a mistake. However, a typedef is sadly just a type <em>alias</em> and <em>does not create a new type!</em> In other words, you do not get any type-safety benefits of doing so.</p>\n\n<p>To get full type safety, you would need to create a (templated) wrapper class around the types in question. Doing so would be a nice exercise when you start to learn about templates.</p>\n\n<hr>\n\n<blockquote>\n <p>Should <code>operator<<</code> need to call <code>calculateGPA()</code>, or should I create a <code>private</code> accessor and have that called? In order to maintain encapsulation, I'll need to keep <code>operator<<</code> as a <code>friend</code>.</p>\n</blockquote>\n\n<p>I would cache the result of <code>calculateGPA</code> and provide an accessor to it. Have <code>operator<<</code> call that accessor. This means that your class would need to invalidate the cached value whenever <code>grades</code> is modified.</p>\n\n<hr>\n\n<blockquote>\n <p>Is the for-loop in <code>calculateGPA()</code> ideal for this purpose, or are there one or more STL functions that can do the same thing but more cleanly?</p>\n</blockquote>\n\n<p>The <code>for</code> loop is sufficiently short and sweet, and makes just a single pass (unlike most other solutions I can think of). You could always use <code>std::accumulate</code> and a lambda, but you would have to do so for both <code>sumCreditPoints</code> and <code>sumGradeHours</code>.</p>\n\n<p>Am I guilty of converting you to the <code>const&</code> style? :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:09:48.933",
"Id": "46592",
"Score": "0",
"body": "Yeah, the `typedef`s are more for aesthetics anyway. I have barely covered templates, but it doesn't seem to quite fit my intent here (I think). If I were to go with the first point, would there be no GPA class at all? I suppose that means everything would be in one file, then. Yes, I did eventually catch the includes, and I now prefer `const&` now (it reads more as \"const-reference\"). :-) Finally: I still cannot use a range-based for-loop for `calculateGPA()`. :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:13:39.340",
"Id": "46593",
"Score": "0",
"body": "[Is this what you mean by the \"golden hammer\"?](https://en.wikipedia.org/wiki/Law_of_the_instrument)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:16:35.107",
"Id": "46594",
"Score": "0",
"body": "With a templated wrapper class you could do `typedef unique_type_wrapper<unsigned> HourCount`, and then HourCount would be a distinct type. | You would have no GPA class, but you could still put the function in a separate file (and make helper functions in that file `static`). | Yes, and classes are a typical golden hammer. Just look at Java :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:19:39.033",
"Id": "46595",
"Score": "0",
"body": "`unique_type_wrapper`? Never heard of that before. Just when I thought my code was \"C++-enough,\" there's even more C++ I could use. Would further discussion on this in chat be okay, even if it may involved writing code (off-topic)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:21:05.490",
"Id": "46596",
"Score": "0",
"body": "`unique_type_wrapper` is the class you write when you learn about templates to allow type-safe type aliases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:22:28.560",
"Id": "46597",
"Score": "0",
"body": "Ah. Even then, I would need a hard lesson on templates (not asking it from you specifically)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:27:00.733",
"Id": "46598",
"Score": "0",
"body": "I've also added clarification for the GPA. Thanks for bring it to my attention!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:02:48.880",
"Id": "46600",
"Score": "0",
"body": "I've now added the data member, accessor, and called `calculateGPA()` in `add()` (for updating the cache). Is that okay to do, also considering it may impact efficiency?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:23:25.010",
"Id": "46601",
"Score": "0",
"body": "I'd do lazy evaluation, i.e. I wouldn't calculate the GPA until someone asks to see it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:26:54.183",
"Id": "46602",
"Score": "0",
"body": "I was trying to do that instead, but then I would probably need to go back to calling the calculating function when outputting. Is there a better way to do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T21:07:10.433",
"Id": "46607",
"Score": "0",
"body": "Something like this: http://ideone.com/HUg5Xr (The comments are intended for you and do not represent a normal commenting level.) I also added a few points to my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T21:09:34.057",
"Id": "46608",
"Score": "0",
"body": "Alright, I'll take a look at this. If I have more questions, I'll post them on chat."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:00:47.560",
"Id": "29465",
"ParentId": "29462",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29465",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T16:59:24.750",
"Id": "29462",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Grade point average (GPA) calculator"
}
|
29462
|
<p>I am trying to learn some basic Python and am trying to find tricks to write speedy code:</p>
<pre><code>import sys
if len(sys.argv) < 3:
print("You left out the arguments")
sys.exit()
gcf = 0
numbers = []
collections = []
unique = False
for i in range(1,len(sys.argv)):
numbers.append(int(sys.argv[i]))
for x in range(0,len(numbers)):
collections.append([])
for s in range(1,numbers[x] + 1):
if numbers[x] % s == 0:
collections[x].append(s)
print str(numbers[x]) + ": ",
print ','.join(map(str,collections[x]))
for i in collections[0]:
for x in collections:
if i in x:
unique = True
else:
unique = False
if unique:
gcf = i
print "gcf is: "+str(gcf)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:59:28.127",
"Id": "46587",
"Score": "0",
"body": "does this code work? I don't understand what yr trying to acheive here for i in collections[0]:\n for x in collections:\n if i in x:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:00:53.087",
"Id": "46588",
"Score": "0",
"body": "yes it works perfectly fine with python 2.7.3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:05:24.390",
"Id": "46590",
"Score": "0",
"body": "this will accept an infinite amount of arguments so i am comparing the factors of any random collection of factors (collections[0]) because the gcf has to be the greatest factor of all args given so any one will work for example if i have [1,3,5],[1,3,5,7],[1,3,5,7,9] i can use any one to compare to the other 2 and still get the right answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T18:07:34.010",
"Id": "46591",
"Score": "0",
"body": "thnx I was looking o see if you can get rid of the third for loop with s, but I can't figure it out,.. someone else will.. be good to see hey :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:33:20.583",
"Id": "46603",
"Score": "0",
"body": "If you're only interested in finding the overall gcf/gcd, you should look at the function [`fractions.gcd`](http://docs.python.org/2/library/fractions.html?#fractions.gcd) and this [gcd question](http://stackoverflow.com/questions/16628088) on stackoverflow. If you also want to find the factors of the input numbers, check out [this answer](http://stackoverflow.com/a/6800586). And you can always come back and edit the code in this question when you've implemented some changes. :)"
}
] |
[
{
"body": "<p>You have written that you want to know tricks for writing speedy code. So I'll leave the algorithm as it is.</p>\n\n<p>You should know that <a href=\"https://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function\">Python code runs faster in local scope than global scope</a>. So putting all of it inside a function should be faster.</p>\n\n<p>From your code it is clear that you don't know about List comprehension. It is faster than creating a list and then appending items to it. So thi</p>\n\n<pre><code>numbers = []\nfor i in range(1,len(sys.argv)):\n numbers.append(int(sys.argv[i]))\n</code></pre>\n\n<p>can be this</p>\n\n<pre><code>numbers = [int(sys.argv[i]) for i in range(1,len(sys.argv))]\n</code></pre>\n\n<p>and it would be faster and easier to read. Same goes for your <code>collections</code> list.</p>\n\n<p>Do you need the <code>unique</code> for something else? I think no. So this</p>\n\n<pre><code>for i in collections[0]:\n for x in collections:\n if i in x:\n unique = True\n else:\n unique = False\n if unique:\n gcf = i\n</code></pre>\n\n<p>can be made this</p>\n\n<pre><code>for i in collections[0]:\n for x in collections:\n if i in x:\n gcf = i\n</code></pre>\n\n<p>Notice less spaces. Makes it easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T20:38:16.887",
"Id": "46689",
"Score": "0",
"body": "thanks but for the last part i am looping through all of the collections and returning true only if it is the gcf in all of the collections so removing unique will not work. The var name unique makes no sense though so sorry for the confusion"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:41:04.887",
"Id": "29498",
"ParentId": "29464",
"Score": "1"
}
},
{
"body": "<p>I agree with Aseem above, a list comprehension is a good move in Python. In addition, I think you can dramatically reduce the number of loops you are doing. </p>\n\n<p>If I understand it right, <code>numbers</code> is an integer representation of <code>sys.argv</code> -> I suggest using <code>sys.argv</code> itself, which reduces your memory overhead. Also, you can iterate over the values in <code>sys.argv</code> directly, you don't need to iterate over indexes. With this in mind, you reduce the number of loops you need to do:</p>\n\n<p>-- Current code:</p>\n\n<pre><code>numbers, collections = [], []\nfor i in range(1,len(sys.argv)):\n numbers.append(int(sys.argv[i]))\nfor x in range(0,len(numbers)):\n collections.append([]) \n for s in range(1,numbers[x] + 1):\n if numbers[x] % s == 0:\n collections[x].append(s)\n</code></pre>\n\n<p>-- Revision, with less loops:</p>\n\n<pre><code>revised = []\nfor n in sys.argv[1:]:\n revised.append([i for i in range(1, int(n) + 1) if not int(n) % i])\n</code></pre>\n\n<p>-- Test that these are in fact equivalent:</p>\n\n<pre><code>collections == revised => True\n</code></pre>\n\n<p>You could go further to reduce the memory consumption, by consuming <code>sys.argv</code> as you went:</p>\n\n<pre><code>revised_2 = []\nsys.argv.pop(0)\nwhile sys.argv:\n n = int(sys.argv.pop(0))\n revised_2.append([i for i in range(1, n + 1) if not n % i])\n</code></pre>\n\n<p>You might want to do this if the lists are really large (but in this case, I imagine you would be reading in the values from a file and wouldn't be using <code>sys.argv</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T21:11:00.680",
"Id": "29508",
"ParentId": "29464",
"Score": "1"
}
},
{
"body": "<p>You can use sets to whittle down the possible GCFs.</p>\n\n<pre><code>for i, argument in enumerate(sys.argv[1:]):\n factors = set(n for n in range(2, int(argument) + 1) if int(argument) & n is 0)\n print argument, factors\n if i is 0:\n possible_gcfs = factors\n else:\n possible_gcfs &= factors\nprint \"gcf is:\", max(possible_gcfs | {1})\n</code></pre>\n\n<p>Better, use <code>reduce</code>:</p>\n\n<pre><code>def get_factors(x):\n factors = set(n for n in range(2, int(x) + 1) if int(x) % n is 0)\n print x, ':', factors\n return factors\n\npossible_gcfs = reduce(set.intersection, map(get_factors, sys.argv[1:]))\nprint \"gcf is:\", max(possible_gcfs | {1})\n</code></pre>\n\n<p>Or if you don't need it to print out the factors of each number you can make it a bit more efficient by noting that the GCF must be no larger than the lowest of the arguments entered. </p>\n\n<pre><code>arguments = map(int, sys.argv[1:])\npossible_gcfs = range(2, min(arguments) + 1)\nfor argument in arguments:\n possible_gcfs = [n for n in possible_gcfs if argument % n is 0]\nprint \"gcf is: \", max(possible_gcfs + [1])\n</code></pre>\n\n<p>... but this can again be simplified using <code>reduce</code> and noting that the <a href=\"https://stackoverflow.com/a/16628379/567595\">gcf is associative</a></p>\n\n<pre><code>def gcf(a, b):\n a, b = int(a), int(b)\n return max(n for n in range(1, min(a, b) + 1) if a % n is 0 and b % n is 0)\n\nprint \"gcf is:\", reduce(gcf, sys.argv[1:])\n</code></pre>\n\n<p>(And as a comment pointed out there are plenty of other solutions posted to earlier questions and you could use <code>fractions.gcd</code>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T22:44:13.110",
"Id": "29510",
"ParentId": "29464",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29498",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T17:42:27.883",
"Id": "29464",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Simple GCF calculator app"
}
|
29464
|
<p>I'm working on a general <code>Requestmethod</code> class which sanitizes and recasts the input of users in an automatic fashion. I've also tried to do array-access in cookies.</p>
<p>My biggest question are:</p>
<ol>
<li>Is this too much for one class alone?</li>
<li>Is the readability/thinking right on this?</li>
</ol>
<p>Code:</p>
<pre><code> Example: (<input type="checkbox" name="checkboxes[]" />)
$a = new Request('POST');
$b = $a->getArray('checkboxes');
$b->get(0);
$b->get(1);
$b->get(2);
class REQUESTCONF {
const XSS = false;
const SALT = 'anysalt';
const c_expire = 24;
const c_path = '/';
const c_domain = '';
const c_secure = false;
const c_httponly = false;
}
/**
* Class to get Secure Request Data
*
* XSS Levels:
* 0 / false = off
* 1 = htmlentities
* 2 = strip tags
*
* @package Request
*/
class Request {
private $DATA;
private $CURSOR = false;
private $XSS = false;
private $METHOD;
/**
* Constructor
*
* @package Request
* @param string $METHOD POST GET SESSION or COOKIE
* @param boolean $XSS XSS Prevent Level
* @uses sanitize(
);
* @return object Request
* @access public
*/
function __construct($METHOD,$XSS=false) {
$this->METHOD = strtoupper($METHOD);
$this->XSS = $XSS;
switch ($this->METHOD) {
case 'FILE':
$this->DATA = $_FILES;
break;
case 'GET':
$this->DATA = $_GET;
break;
case 'POST':
$this->DATA = $_POST;
break;
case 'COOKIE':
foreach($_COOKIE as $k => $v) {
// hiding Notice - but no other way :'(
$array = @unserialize($v);
if ($array && is_array($array)) {
$this->DATA[$k] = $array;
} else {
$this->DATA[$k] = $v;
}
}
break;
case 'SESSION':
$this->DATA = $_SESSION;
break;
default:
trigger_error('Parameter must be a valid Request Method (GET, POST, FILE, SESSION or COOKIE)',E_USER_ERROR);
die();
break;
}
$this->DATA = $this->sanitize($this->DATA);
return $this;
}
/**
* Destruct - clean up
*
* @package Request
* @access public
*/
function __destruct() {
$this->save();
if ( $this->METHOD == 'SESSION' )
session_regenerate_id();
unset($this->XSS);
unset($this->DATA);
unset($this->CURSOR);
unset($this->METHOD);
}
/**
* Removes a Value with $key of $this->DATA
*
* @package Request
* @param string $key Arraykey of Element in $DATA
* @access public
*/
public function remove($key){
if ( $this->CURSOR != false && isset($this->DATA[$this->CURSOR]) && is_array($this->DATA[$this->CURSOR]) ) {
unset($this->DATA[$this->CURSOR][$key]);
} elseif (isset($this->DATA[$key])) {
unset($this->DATA[$key]);
} else {
return false;
}
}
/**
* Dumps whole $DATA
*
* @package Request
* @access public
*/
public function dump(){
var_dump($this->DATA);
}
/**
* Set Value in $DATA
*
* @package Request
* @param string $key Arraykey of Element in $DATA
* @param mixed $value String Integer Float or Bool want to set in $DATA
* @return boolean
* @access public
*/
public function set($key,$value){
if ( $this->CURSOR != false && isset($this->DATA[$this->CURSOR]) && is_array($this->DATA[$this->CURSOR]) ) {
$this->DATA[$this->CURSOR][$key] = $value;
return 1;
}
if (is_array($value))
return false;
$this->DATA[$key] = $value;
$this->setToken();
return $this;
}
/**
* Get a Value from $DATA with validation
*
* @package Request
* @uses object validateString
* @param string $key Arraykey of Element in $DATA
* @param mixed $validate Regex Rule for validation or false
* @return mixed $this->DATA[$var] Contents of the Arraykey
* @access public
*/
public function validGet($key,$validateRegex){
if (!$this->checkToken())
return false;
if ( $string = $this->get($key) ) {
if (preg_match($validateRegex,$string))
return $string;
}
return false;
}
/**
* Get Filesize when Cursor is on a FILE Request
*
* @package Request
* @return int Filesize in Bytes of File
* @access public
*/
public function getFilesize(){
if ($this->METHOD != 'FILE' || !$this->CURSOR)
return false;
return $this->DATA[$this->CURSOR]['size'];
}
/**
* Get Filename when Cursor is on a FILE Request
*
* @package Request
* @return string Name of File
* @access public
*/
public function getFilename(){
if ($this->METHOD != 'FILE' || !$this->CURSOR)
return false;
return $this->DATA[$this->CURSOR]['name'];
}
/**
* Get MIME when Cursor is on a FILE Request
*
* @package Request
* @return string MIME-Type of File
* @access public
*/
public function getFileType(){
if ($this->METHOD != 'FILE' || !$this->CURSOR)
return false;
// When File is a Picture getimagesize() mime is more secure and can handle PSDs - exif not
if ($img = getimagesize($this->DATA[$this->CURSOR]['tmp_name'])) {
return $img['mime'];
} elseif (isset($this->DATA[$this->CURSOR]['type'])) {
return $this->DATA[$this->CURSOR]['type'];
} else {
return false;
}
}
/**
* Saves the File to a given destination
*
* @package Request
* @param string $dest Save Destination
* @return boolean
* @access public
*/
public function saveFile($dest){
if ($this->METHOD != 'FILE' || !$this->CURSOR)
return false;
if (move_uploaded_file($this->DATA[$this->CURSOR]['tmp_name'],$dest)) {
return true;
} else {
return false;
}
}
/**
* Sets the Cursor to a FILE Request
*
* @package Request
* @param string $key Arraykey of Element in $DATA
* @access public
*/
public function getFile($key){
if ($this->METHOD != 'FILE')
return false;
//sanitize filename => no leading dot
return $this->getArray($key);
}
/**
* Get a Value from $DATA
*
* @package Request
* @param string $key Arraykey of Element in $DATA
* @return mixed $this->DATA[$var] Contents of the Arraykey
* @access public
*/
public function get($key){
if (!$this->checkToken())
return false;
if ( $this->CURSOR != false && isset($this->DATA[$this->CURSOR][$key]))
return $this->DATA[$this->CURSOR][$key];
if (!isset($this->DATA[$key]))
return false;
return $this->DATA[$key];
}
/**
* Set a Array in $DATA
*
* @package Request
* @param array $array Array you want to Store in $DATA
* @return boolean true
* @access public
*/
public function setArray($key,$array){
if (!is_array($array) OR $this->METHOD == 'FILE')
return false;
$this->DATA[$key] = $array;
$this->setToken();
return $this;
}
/**
* Sets the Cursor to an existing arraykey from Data when its an Array
* Otherwise set it to false and return false
*
* @package Request
* @param string $key Key of an Array in $DATA
* @return object Request
* @access public
*/
public function getArray($key){
if (!isset($this->DATA[$key]) || !is_array($this->DATA[$key])) {
$this->CURSOR = false;
return false;
}
$this->CURSOR = $key;
return $this;
}
/* Sanitizer
*
*
* @package Request
* @return array sanitized and pseudotyped Array (since POST and GET is String only)
* @access private
*/
private function sanitize($array){
foreach ($array as $k => $v) {
if (is_numeric($v)) {
$array[$k] = $v + 0;
if ( is_int($v) ) {
$array[$k] = (int) $v;
} elseif ( is_float($v) ) {
$array[$k] = (float) $v;
}
} elseif (is_bool($v)) {
$array[$k] = (bool) $v;
} elseif (is_array($v)) {
$array[$k] = $this->sanitize($array[$k]);
} else {
if ($this->XSS > 0) {
switch ($this->XSS) {
case 1:
$array[$k] = htmlentities(trim($v));
break;
case 2:
$array[$k] = strip_tags(trim($v));
break;
}
} else {
$array[$k] = (string) trim($v);
}
}
}
return $array;
}
/**
* refill the original REQUEST
*
* @package Request
* @access public
*/
public function save() {
switch($this->METHOD) {
case "GET" :
$_GET = $this->DATA;
break;
case "POST" :
$_POST = $this->DATA;
break;
case "SESSION" :
$_SESSION = $this->DATA;
break;
case "COOKIE" :
$expire = time()+3600*REQUESTCONF::c_expire;
foreach ($this->DATA as $K => $V) {
if ( is_array($V)) {
setcookie($K,serialize($V),
$expire,
REQUESTCONF::c_path,
REQUESTCONF::c_domain,
REQUESTCONF::c_secure,
REQUESTCONF::c_httponly
);
} else {
setcookie($K,$V,
$expire,
REQUESTCONF::c_path,
REQUESTCONF::c_domain,
REQUESTCONF::c_secure,
REQUESTCONF::c_httponly
);
}
}
break;
}
return 1;
}
/**
* Generates a Token with data serializing and a given salt from Config
* saves it in the first level of Session or Cookie
*
* @package Request
* @access private
*/
private function setToken() {
if ($this->METHOD == 'SESSION' || $this->METHOD == 'COOKIE') {
if ( isset($this->DATA['TOKEN']))
unset($this->DATA['TOKEN']);
$this->DATA['TOKEN'] = crc32(serialize($this->DATA).REQUESTCONF::SALT);
}
}
/**
* checks the inserted Tokenhash with actual Data in Session or Cookie
*
* @package Request
* @return boolean true on success false on fail
* @access private
*/
private function checkToken() {
if ($this->METHOD != 'SESSION' && $this->METHOD != 'COOKIE' )
return 1;
if ( isset($this->DATA['TOKEN'])) {
$proof = $this->DATA['TOKEN'];
unset($this->DATA['TOKEN']);
if ( $proof != crc32(serialize($this->DATA).REQUESTCONF::SALT) ) {
return false;
} else {
$this->DATA['TOKEN'] = crc32(serialize($this->DATA).REQUESTCONF::SALT);
return 1;
}
} else {
return false;
}
}
}
function Request($method,$xss=false) {
if (!$xss)
$xss = REQUESTCONF::XSS;
return new Request($method,$xss);
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Right, let me be clear, I mean this in the nicest of ways, but I don't like this code one bit. Let me start off a couple of simple things:</p>\n\n<p>Please, follow the coding standards as described by <a href=\"http://www.php-fig.org/psr/1/\">PHP-FIG</a></p>\n\n<p>I've noticed you're (ab)using the error supressing operator (eg <code>@unserialize</code>). Don't. Errors and Warnings are there to help you improve on your code. If there's a warning issued, don't cover it up, <em>fix it</em>. Even more worrying is <em>where</em> I saw this being used:</p>\n\n<pre><code>foreach($_COOKIE as $k => $v)\n{\n $array = @unserialize($v);\n if ($array && is_array($array))\n {\n $this->DATA[$k] = $array;\n }\n else\n {\n $this->DATA[$k] = $v;\n }\n}\n</code></pre>\n\n<p>Now this implies you're actually setting cookies to hold serialized objects or arrays. First off, it gives me a solid clue on what your stack looks like (I know for a fact you're using PHP). Serialized arrays are easily changed client side, so there's no guarantee on data integrity. If they're serialized objects, you're in trouble... big time. That would mean you're actually sending an object to the client, containing its state, and possibly all sorts of information on your server. If I were to be a 16 year old would-be hacker, I'd feel like I just struck gold. With some trial and error, I could easily manipulate that objects state, to gain access to those parts of your app you probably rather I didn't know about.<br/>\nCookies should cosist of little slivers of, on its own, meaningless data, Sessions are where you <em>could</em> store serialized objects, but still: I wouldn't.</p>\n\n<p>Your <code>Request</code> class has a <code>public function __construct</code> function defined. Why then, do you also define a <code>function Request</code>? It looks as though you're trying to catch errors if somebody omitted the <code>new</code> keyword, or you're trying to mimic the factory pattern. Either implement a factory, or drop the function. If it's there to catch code that doesn't construct its instances using <code>new</code>, then that code contains bugs: <em>fix them, don't work around them</em>.</p>\n\n<p>Next: The <code>REQUESTCONF</code> class, which only contains constants (ignoring the naming issues here). These constants <em>obviously</em> belong to the <code>Request</code> object: the <code>Request</code> object's state is defined by it. Drop that class, which is used as a constant array anyway, and define the constants as <code>Request</code> constants.</p>\n\n<p>You don't need to call all those <code>unset</code>'s in the destructor. Dealing with the session is fine, anything else is just overhead (the values will be unset when the object goes out of scope anyway), which is right after the destructor returns.</p>\n\n<p>Moving on to some actual code:</p>\n\n<pre><code>public function getArray($key)\n{\n if (!isset($this->DATA[$key]) || !is_array($this->DATA[$key])) {\n $this->CURSOR = false;\n return false;\n }\n $this->CURSOR = $key;\n return $this;\n}\n</code></pre>\n\n<p>This doesn't make sense, to me at least. I'd expect the return type of <code>getArray</code> to be <em>either</em> an array or <code>null</code>, you're returning false, or the object itself. I see what you're doing here, but the name is just begging for accidents to happen.<br/>\neither implement a child of the <code>Traversable</code> interface (which is what you're trying to do anyway) or change the method-name.</p>\n\n<p>Your first question: <em>Is this too much for one class?</em><Br/>\nYes, it is. You might want to take a look at existing frameworks and how they manage the Request, what objects they use and how they're tied in.</p>\n\n<p>Your <code>Request</code> object deals with everything, from the basic GET params to sessions. They're not the same thing, and should be treated as seperate entities. You're using a class as a module, which violates the single responsability principle.<br/>\nI'd suggest you write a class for each request that requires its own treatment. Take, for example, a <code>Session</code> class. That class should indeed implement a destructor, but a <code>Get</code> object shouldn't. Their constructors should be different, too, but they can both implement the same basic getter and setter.</p>\n\n<p>Start off by writing an abstract <code>RequestType</code> class, that holds the shared methods/properties, and extend it with the various request-type classes:</p>\n\n<pre><code>abstract class RequestType\n{\n protected $data = null;\n protected $writeable = true;\n abstract public function __construct();//ensure all children implement their own constructor\n public function __get($name)\n {\n if (!is_array($this->data) || !isset($this->data[$name]))\n {//or throw exception\n return null;\n }\n return $this->data[$name];\n }\n public function __set($name, $val)\n {\n if ($this->writeable === false)\n {\n throw new RuntimeException(sprintf('%s instance is Read-Only', get_class($this)));\n }\n $this->data[$name] = $value;\n return $this;\n }\n}\n//then\nclass Session extends RequestType\n{\n public function __construct($id = null, $readOnly = false)\n {\n $this->writeable = !!$readOnly;\n //start session, assign to $this->data\n }\n}\n</code></pre>\n\n<p>You get the idea... You can use the abstract class for type-hinting, and implement the <code>Traversable</code> interface there, too.</p>\n\n<p>Your main <code>Request</code> object then sort of becomes a service, then:</p>\n\n<pre><code>class Request\n{\n private $session = null;\n private $cookie = null;\n private $post = null;\n private $get = null;\n private $xhr = false;//isAjax()\n private $uri = null;\n //type constants\n const TYPE_COOKIE = 1; //000001\n const TYPE_SESSION = 2;//000010\n const TYPE_POST = 4; //000100\n const TYPE_GET = 8; //001000\n const TYPE_URI = 16; //010000\n const TYPE_AJAX = 32; //100000\n const TYPE_ALL = 63; //111111\n //config constants\n const CONF_XSS = 0; //use PDO-style: array(Request::CONF_XSS => XSS_ON)\n const XSS_ON = 1;\n const XSS_OFF = 0;\n\n private static $objects = array(\n 1 => 'Cookie',\n 2 => 'Session',\n 4 => 'Post',\n 8 => 'Get',\n 16 => 'Uri',\n 32 => 'Ajax'\n );\n private $options = array(\n self::CONF_XSS => XSS_OFF,\n 'default' => 'config here'\n );\n public function __construct($type = self::TYPE_ALL, array $options = null)\n {\n if (is_array($options))\n {\n foreach($options as $conf => $value)\n {\n $this->options[$conf] = $value;\n }\n }\n if ($type === self::TYPE_ALL)\n {\n foreach(self::$objects as $type)\n {//assume setPost, setSession, ..\n $this->{'set'.$type}($this->options);\n }\n return $this;\n }\n if (($type & ($type - 1)) === 0 && ($type & self::TYPE_ALL) === $type)\n {//^^ $type is power of 2 , and it's value < 63 ===> constant exists\n $this->{'set'.self::$objects[$type]}($this->options);\n }\n return $this;\n }\n}\n</code></pre>\n\n<p>You implement, as the constructor shows, your <code>set<Type></code> methods, and some lazy-loading <code>get<Type></code> methods, too, and you're good to go.<Br/>\nIn case you're not sure what I mean by lazy-loading getters:</p>\n\n<pre><code>public function getSession()\n{\n if ($this->session === null)\n {\n $this->session = new Session($this->options);//session_start is the responsability of the Session class!\n }\n return $this->session;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T09:22:42.163",
"Id": "46649",
"Score": "0",
"body": "Thank you for your insights and efforts to explain me this. I didnt think of that lazyload Method you are using there - thats really handy.\nAnd i have no problems at all when you say my code smells - the reason why i post this here is good critique - which you gave me.\n\nBut yeah my REQUESTCONF i use it as \"Pseudo-Enum\" for my Config File because its the easiest way for me to do global Configurations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T09:25:29.097",
"Id": "46650",
"Score": "0",
"body": "@wandregal: You're welcome. Though that `REQUESTCONF` did remind me of `enum`. Still, declaring those constants in your `Request` class does the same thing: `Request::XSS_ON` is available without there being an instance of the class, too, so why bother creating 2 classes, and 9/10 having to call the autoloader twice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T09:36:17.940",
"Id": "46651",
"Score": "0",
"body": "Simply because i didnt know PHP can handle that and i see now ive overcomplicated my whole Problem here. Thats also \"just\" a new learning experience for me because OOP PHP is pretty new for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T09:40:39.723",
"Id": "46652",
"Score": "0",
"body": "@wandregal: As always, there's only one place to look: [php.net: on importing](http://www.php.net/manual/en/language.namespaces.importing.php), and [docs on namespaces in general](http://php.net/manual/en/language.namespaces.php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T07:01:40.663",
"Id": "46737",
"Score": "1",
"body": "@wandregal: I've added some more _\"critique\"_ on your using the `@` operator and _where_ you're using that operator. I must stress that there are some rather important things to fix for you there, too."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T08:09:47.063",
"Id": "29485",
"ParentId": "29469",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "29485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:10:10.167",
"Id": "29469",
"Score": "9",
"Tags": [
"php",
"object-oriented",
"classes"
],
"Title": "Critique Request: PHP Request-Method Class"
}
|
29469
|
<p>I've written a small code snippet that generates checkboard texture using cl-opengl.</p>
<pre><code>(defun init-texture (tex)
(gl:bind-texture :texture-2d tex)
(gl:tex-parameter :texture-2d :texture-min-filter :nearest)
(gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
(print *test-texture*)
(let* ((tex-w 16) (tex-h 16) (pixel-size 4)
(pixel-data (make-array (* (* tex-w tex-h) pixel-size) :element-type '(unsiged-byte 8) :adjustable nil :initial-element 0)))
(loop for y from 0 to (- tex-h 1) do
(let ((line-offset (* (* tex-w pixel-size) y)))
(loop for x from 0 to (- tex-w 1) do
(let ((x-offset (+ line-offset (* x pixel-size))) (c (if (oddp (+ x y)) 255 0)))
(setf (aref pixel-data x-offset) 255)
(setf (aref pixel-data (+ x-offset 1)) c)
(setf (aref pixel-data (+ x-offset 2)) c)
(setf (aref pixel-data (+ x-offset 3)) 255)))))
(gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))
</code></pre>
<p>Problem:
it looks ugly and is unnecessarily verbose, especially <code>(- tex-h 1)</code> and 4 <code>setf</code> in a row.</p>
<p>How can I "beautify"/simplify this?</p>
<p>Program logic:</p>
<ol>
<li>generate 1d array of (unsigned-byte 8). Array size is tex-w*tex-h*pixel-size, where tex-w is 16, tex-h is 16, pixel-size is 4. 1 pixels. That's 16x16 texture data in rgba format where every pixel takes 4 elements.</li>
<li>Fill array. If <code>(oddp (+ x y))</code>, put white pixel, otherwise put blue pixel.</li>
</ol>
|
[] |
[
{
"body": "<p>Not much better:</p>\n\n<pre><code>(defun init-texture (tex &aux (tex-w 16) (tex-h 16) (pixel-size 4))\n (gl:bind-texture :texture-2d tex)\n (gl:tex-parameter :texture-2d :texture-min-filter :nearest)\n (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)\n (print *test-texture*)\n (let ((pixel-data (make-array (* tex-w tex-h pixel-size)\n :element-type '(unsiged-byte 8)\n :adjustable nil\n :initial-element 0)))\n (loop for y below tex-h\n for line-offset = (* tex-w pixel-size y)\n do (loop for x below tex-w\n for x-offset = (+ line-offset (* x pixel-size))\n for c = (if (oddp (+ x y)) 255 0)\n do (setf (aref pixel-data (+ x-offset 0)) 255\n (aref pixel-data (+ x-offset 1)) c\n (aref pixel-data (+ x-offset 2)) c\n (aref pixel-data (+ x-offset 3)) 255)))\n (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))\n</code></pre>\n\n<p>To get rid of the <code>aref</code>s is not really possible. One way would be to use the function <code>REPLACE</code>:</p>\n\n<pre><code>(replace pixel-data (vector 255 c c 255) :start1 x-offset)\n</code></pre>\n\n<p>But now it allocates a vector for that. Then one might want to wish that the vector would be allocated on the stack:</p>\n\n<pre><code>(let ((new-data (vector 255 c c 255)))\n (declare (dynamic-extent new-data))\n (replace pixel-data (vector 255 c c 255) :start1 x-offset))\n</code></pre>\n\n<p>Another way is not to write the <code>aref</code>s, but to hide it behind a macro:</p>\n\n<pre><code>(defmacro vector-put-at ((vector start) &rest data)\n `(progn\n ,@(loop for d in data and i from 0\n collect `(setf (aref ,vector (+ ,start ,i)) ,d))))\n</code></pre>\n\n<p>The you can write above as:</p>\n\n<pre><code>(defun init-texture (tex &aux (tex-w 16) (tex-h 16) (pixel-size 4))\n (gl:bind-texture :texture-2d tex)\n (gl:tex-parameter :texture-2d :texture-min-filter :nearest)\n (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)\n (print *test-texture*)\n (let ((pixel-data (make-array (* tex-w tex-h pixel-size)\n :element-type '(unsiged-byte 8)\n :adjustable nil\n :initial-element 0)))\n (loop for y below tex-h\n for line-offset = (* tex-w pixel-size y)\n do (loop for x below tex-w\n for x-offset = (+ line-offset (* x pixel-size))\n for c = (if (oddp (+ x y)) 255 0)\n do (vector-put-at (pixel-data x-offset)\n 255 c c 255)\n (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T02:26:28.057",
"Id": "46613",
"Score": "0",
"body": "Interesting, thanks. However, thinking about it, is there some kind of way to set 4 (consequent) array elements at once? that would eliminate multiple arefs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T06:48:51.550",
"Id": "46644",
"Score": "0",
"body": "@SigTerm: see my edit above"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T23:12:14.420",
"Id": "29472",
"ParentId": "29470",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29472",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:11:12.513",
"Id": "29470",
"Score": "1",
"Tags": [
"common-lisp",
"opengl"
],
"Title": "common lisp: nested loop beautification (checkboard texture generator)"
}
|
29470
|
<p>The following code takes a string and converts it to it's number equivalent.
A=1 ... Z=26, while keeping all other characters intact.
It formats the string using two delimiters. One for between characters and one for between words. I want to optimize it, and have fixed a lot of redundancy, and slow parts. However, I can't seem to make it any faster. The longest amount of time is taken for decrypting an encrypted string. I would like to optimize both parts. </p>
<p>Suggestions on techniques or code with explanation would be most helpful. This is mostly for me to understand the bottlenecks in Lua logic.</p>
<pre><code>function parseString(str,del1,del2)
local delim1 = del1 or ' '
local delim2 = del2 or '-'
local tab = {}
local sub = ''
local index = 1
local c = ''
local i = 1
while (i > #str and sub == '') == false do
c = str:sub(i,i)
if c == delim2 or c == delim1 or c == '' then
if string.match(sub,'%d') == nil then
tab[index] = sub
index = index + 1
else
tab[index] = string.char(tonumber(sub) + 96)
index = index + 1
end
if c == delim1 then
tab[index] = ' '
index = index + 1
end
sub = ''
else
sub = sub .. c
end
i = i + 1
end
return table.concat(tab)
end
function strToNums(str)
local t = {string.byte(str,1,#str)}
for i,v in ipairs(t) do
if v < 97 and v >= 65then
t[i] = v - 64
else
if v <= 172 and v >= 97then
t[i] = v - 96
else
t[i] = v
end
end
end
return t
end
function formater(del1,del2,arg)
local out = {}
local index = 1
local nDel1 = string.byte(del1)
local nDel2 = string.byte(del2)
for i,v in ipairs(arg) do
if v <= 26 and v >= 1 then
out[index] = tostring(v)
index = index + 1
if i < #arg and arg[i+1] ~= nDel1 then
out[index] = del2
index = index + 1
end
else
if v == 32 then
out[index] = del1
index = index + 1
else
out[index] = string.char(v)
index = index + 1
if i < #arg and arg[i+1] ~= nDel1 then
out[index] = del2
index = index + 1
end
end
end
end
return table.concat(out)
end
function main()
local line = ''
local del1 = ' '
local del2 = '-'
local x = os.clock()
local line2 = ''
local str =''
for i=1,1000 do
str = strToNums("This string'll test my system!")
line = formater(del1,del2,str)
line2 = parseString(line,del1,del2)
end
print(line,line2)
print(string.format("elapsed time: %.10f\n", os.clock() - x))
-- while true do
-- line = io.read()
-- if string.match(line,'%a+') == nil then break end
-- line = formater(del1,del2,strToNums(line))
-- print(line)
-- print(parseString(line,del1,del2))
-- end
end
main()
</code></pre>
<p>This is the output that I would expect for the given input:</p>
<pre><code>20-8-9-19 19-20-18-9-14-7-'-12-12 20-5-19-20 13-25 19-25-19-20-5-13-! this string'll test my system!
elapsed time: 0.0880000000
</code></pre>
<p>strToNum takes a string and converts it to a table of char values.</p>
<p>Formatter takes two types of delimiters: one for between characters and one for between words. It also takes the table of values generated by strToNum. It takes these values and creates a string with each character separated by one delimiter and each word separated by another.</p>
<p>parseString takes a string and two delimiters. The delimiters are to be checked against.
The string is iterated over, and between iterators another sub string is created and added to as long as there is not a delimiter. Each time it runs into a delimiter it adds it to a table. Which is then concatenated at the end.
This function takes the most amount of time to run. I think it is because of the using substring, string.char and tonumber.</p>
<p>edit:
It certainly became faster. Not quite twice as fast though. I see a lot of the redundancies in my code now.
Mine with just encoding</p>
<pre><code>> lua numandstring.lua
20-8-9-19 19-20-18-9-14-7-'-12-12 20-5-19-20 13-25 19-25-19-20-5-13-!
elapsed time: 0.0330000000
new one with just encoding
> lua numandstring.lua
20-8-9-19 19-20-18-9-14-7-'-12-12 20-5-19-20 13-25 19-25-19-20-5-13-!
elapsed time: 0.0280000000
</code></pre>
<p>I squeezed out a little more speed with</p>
<pre><code>function encode3(input, wordDelimiter, characterSeparator)
local out = {}
input = input:upper()
local index = 1
local c = input:sub(1,1)
local inputLength = #input
for i=1,inputLength do
local nextc = input:sub(i+1,i+1)
if c == wordDelimiter then
out[index] = c
index = index + 1
else
out[index] = lookup[c] or c
index = index + 1
if i < inputLength and nextc ~= wordDelimiter then
out[index] = characterSeparator
index = index + 1
end
end
c = nextc
end
return table.concat(out)
end
</code></pre>
<p>I eliminated calling the table length method repeatedly, because it has to iterate over the whole table. C habits die hard.</p>
<pre><code>> lua numandstring.lua
20-8-9-19 19-20-18-9-14-7-'-12-12 20-5-19-20 13-25 19-25-19-20-5-13-!
elapsed time: 0.0250000000
</code></pre>
<p>Also the calls to the first sub make no difference. Sub is called the same amount of times either way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T05:19:45.690",
"Id": "46639",
"Score": "0",
"body": "\"Sub is called the same amount of times either way\". Um, no. Try removing the call outside the loop. BTW, the table length call in the for loop is evaluated only once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T05:31:20.567",
"Id": "46641",
"Score": "0",
"body": "I did try both and got the same amount of time. The length is evaluated every time. I even get a performance boost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:19:10.203",
"Id": "46665",
"Score": "0",
"body": "\"The length is evaluated every time.\" [All three control expressions are evaluated only once, before the loop starts.](http://www.lua.org/manual/5.1/manual.html#2.4.5) This is Lua 101. \"I even get a performance boost.\" Because your benchmarking sucks. This stuff trivial to prove. Run this: `function x() print('x') return 10 end for i=1,x() do end` Note how many times `x` is called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:22:54.987",
"Id": "46666",
"Score": "0",
"body": "You completely missed what I was saying. When you use the length of a table as an index for the table it has to iterate through the table to find the new table length. i.e. this: \"out[#out +1] = c\". I know for a loop it is only called once btw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:34:56.897",
"Id": "46667",
"Score": "0",
"body": "I said \"The table length call **IN THE FOR LOOP** is evaluated only once.\" You *responded* \"The length is evaluated every time.\" Can you see why I would \"miss what you're saying\"? You responded to a comment *about* the for loop. If you were talking about something else entirely, there's no possible way I could know that. My point is that your code removes the length check *from the for loop*, when there's no reason to do that. That length call happens only once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:44:08.607",
"Id": "46668",
"Score": "0",
"body": "I must have missed what you were saying as well. I thought that you were talking about things in the loop. You said table length call, while you were talking about a string length call, you can see how I might think you were talking about the table. It removes it also when it is checked against the length: \"if i < inputLength and nextc ~= wordDelimiter then\". This prevents it from having to iterate over the string every time it checks. The initial one is useless, and I know that, I put it there for consistency. Oh well, thanks again for the help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T16:12:44.773",
"Id": "46669",
"Score": "0",
"body": "Ahh... I see the second usage. Side note: in production code, I'd use `encode2`. Why? It most clearly expresses intent, it's the most *readable*, which is by far the most important metric almost all the time. It's why high level languages exist. `encode3` is premature optimization, buying us a few microseconds at the cost of code size and complexity which translates into more time and energy spent on maintenance. Of course, in this case, optimization was the point of the exercise, but I thought it's worth pointing out that writing code like that in a dynamic language is non-idiomatic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T16:20:30.070",
"Id": "46670",
"Score": "0",
"body": "Yeah, I understand that. I usually break it up that way. Even when I wrote in plain C. I was just trying to see how much I could squeeze out of Lua. Milliseconds maybe small, but this code scales linearly which is nice. Side note: I wrote a version of this in C and it was like 25 times faster. Is it supposed to be that way? I don't have the C code atm :/, should've emailed it to myself. Thanks for pointing it out though, I sometimes slip into C mode."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T16:36:51.433",
"Id": "46671",
"Score": "0",
"body": "\"in C it was like 25 times faster. Is it supposed to be that way?\" For something like this? Probably. Lua's strings are immutable and just to look at a single character you're creating an new, garbage string object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T16:42:38.413",
"Id": "46672",
"Score": "0",
"body": "Yeah, that's would I thought. I didn't think it would be that bad though."
}
] |
[
{
"body": "<p>Your code is a bit is overcomplicated. There are a million ways to skin this cat, but I'll show a few. They're all about twice as fast as your code on my machine:</p>\n\n<p>The most concise would be to let Lua do most of the parsing for us. We'll first chop the string into words, then chop each word into characters, convert the characters, concat the characters back into a word with the character delimiter, then concat the words back into a string with the word delimiter:</p>\n\n<pre><code>function encode1(input, wordDelimiter, characterSeparator) \n local ascii_offset = ('A'):byte() - 1\n local words = {}\n\n for word in input:upper():gmatch('[^'..wordDelimiter..']+') do\n local encodedWord = {}\n for c in word:gmatch('.') do\n encodedWord[#encodedWord + 1] = c:match('%w') and c:byte() - ascii_offset or c\n end\n words[#words + 1] = table.concat(encodedWord, characterSeparator)\n end\n\n return table.concat(words, wordDelimiter)\nend\n</code></pre>\n\n<p>Usage and output:</p>\n\n<pre><code>print(encode(\"This string'll test my system!\", ' ', '-'))\n\n20-8-9-19 19-20-18-9-14-7-'-12-12 20-5-19-20 13-25 19-25-19-20-5-13-!\n</code></pre>\n\n<p>To make it a bit faster, we can use a lookup table to find the value for a character.</p>\n\n<pre><code>local lookup = {\n A= 1, B= 2, C= 3, D= 4, E= 5, F= 6, G= 7, H= 8, I= 9, J=10, K=11, L=12, M=13,\n N=14, O=15, P=16, Q=17, R=18, S=19, T=20, U=21, V=22, W=23, X=24, Y=25, Z=26,\n}\n\nfunction encode2(input, wordDelimiter, characterSeparator) \n local words = {}\n\n for word in input:upper():gmatch('[^'..wordDelimiter..']+') do\n local encodedWord = {}\n for c in word:gmatch('.') do\n encodedWord[#encodedWord + 1] = lookup[c] or c\n end\n words[#words + 1] = table.concat(encodedWord, characterSeparator)\n end\n\n return table.concat(words, wordDelimiter)\nend\n</code></pre>\n\n<p>Something a bit closer to your approach (manually parsing the input) is a bit more complicated but is measurably faster:</p>\n\n<pre><code>function encode3(input, wordDelimiter, characterSeparator) \n input = input:upper()\n local out = {}\n local c = input:sub(1,1)\n for i=1,#input do\n local nextc = input:sub(i+1,i+1)\n if c == wordDelimiter then\n out[#out + 1] = c\n else\n out[#out + 1] = lookup[c] or c\n if i < #input and nextc ~= wordDelimiter then\n out[#out + 1] = characterSeparator\n end\n end\n c = nextc\n end\n\n return table.concat(out)\nend\n</code></pre>\n\n<p>Notice that I make the first call to <code>sub</code> outside of the loop so that I only need one <code>sub</code> call in the loop. Not doing this makes a measurable speed difference.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T00:51:41.297",
"Id": "29473",
"ParentId": "29471",
"Score": "4"
}
},
{
"body": "<p>You can use a translation table with <code>gsub</code>, as in the code below:</p>\n\n<pre><code>local t={}\nfor c in (\"abcdefghijklmnopqrstuvwxyz\"):gmatch(\".\") do\n local k=c:upper()\n local v=(k:byte()-(\"A\"):byte()+1)..\"-\"\n t[c]=v\n t[k]=v\nend\n\ns=\"This string'll test my system!\"\ns=s:gsub(\"%A+\",\"/\")\nprint(s:gsub(\"%a\",t))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:47:13.023",
"Id": "29683",
"ParentId": "29471",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29473",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:57:20.057",
"Id": "29471",
"Score": "6",
"Tags": [
"parsing",
"lua"
],
"Title": "Lua string parsing"
}
|
29471
|
<p>I have implemented the following code which will be used to read in what are essentially key-value pairs from a file.</p>
<p>an example input file may look like</p>
<pre><code>max_search_depth 10
enable_recursion false
job_name Khalessi
</code></pre>
<p><strong>my main issue with this code</strong> is that I wish to return variables of different types based on the text in the file. <em>max search depth</em> is best suited as an int, while <em>job name</em> is a string, and <em>enable recursion</em> is a bool</p>
<p>currently I solve this issue by sub classing the declaration struct, but i wonder if there are other options for achieving this which put less onus on the calling function to know what variable type it will be receiving with any given key.</p>
<p>I am hoping to purpose this code for a few different areas in my application, so I would like to keep it as generic as possible.</p>
<p><strong>my secondary concern</strong> is with the section involving if(key == a_particular_key) { //do whatever }
There are potentially 100's of possibilities of what a key could be, so I am sure there must be a more elegant way of finding the key and directing program flow accordingly, but as of yet I have not learned a more elegant solution</p>
<p><strong>tertiary concern</strong> of minor importance: do i really need void v() in the parent class to use polymorphism?</p>
<p>Thanks a ton for looking at my code! </p>
<pre><code>#include <algorithm>
#include <iostream>
#include <string>
struct declaration {
std::string key;
// need at least one virtual method to enable polymorphism?
// compiler errors will result if v() is not present.
virtual void v(){}
};
// Specializations of the declaration struct for their respective types
struct declaration_int : public declaration { int value; };
struct declaration_string : public declaration { std::string value; };
struct declaration_bool : public declaration { bool value; };
declaration* readLine(){
std::string key, value;
// Irrelevent code. Simulates reading in a line from a file. It's only
// here to keep the code consise and relevent.
static unsigned int count = 0;
count++;
if( count % 3 == 0){
key = "max_search_depth";
value = "10";
}
else if( count % 3 == 1){
key = "enable_recursion";
value = "false";
}
else {
key = "job_name";
value = "Khaleesi";
}
// key and value have now been set
// based on what was parsed in from the file
// check if value is numeric
char *numeric_check;
int numeric_value = static_cast<int>(strtod( value.c_str(), &numeric_check ));
// value is a boolean
if( value == "true" || value == "false") {
//initalize object and return it
declaration_bool *d_bool = new declaration_bool;
d_bool->key = key;
d_bool->value = (value == "true");
return dynamic_cast<declaration*>(d_bool);
}
// value is a number
else if( *numeric_check == '\0' ) {
declaration_int *d_int = new declaration_int;
d_int->key = key;
d_int->value = numeric_value;
return dynamic_cast<declaration*>(d_int);
}
// value is a string
else {
declaration_string *d_string = new declaration_string;
d_string->key = key;
d_string->value = value;
return dynamic_cast<declaration*>(d_string);
}
// side note: I am aware of this memory leak. For sake of simplicity
// I have not worried about deleting the declaration structs. In acctual
// code this would be properly handled.
}
// irrelevent and used only for illustrative purposes
void setRecursion( bool enabled ){}
void setDepth( int levels ){}
void statusReport( std::string job_name ){}
int main (){
/*shhhh*/int lines_remaining = 3;/* Again, only to keep it simple. Not real code*/
// while file still has lines to read in
while( lines_remaining-- ){
declaration *line = readLine();
if(line->key == "enable_recursion" ){
// I know I can expect a bool value next due to the "enable_recursion" key,
// so I can check to ensure it is indeed a bool and be safe, but the general
// idea now is to just:
declaration_bool *db = dynamic_cast<declaration_bool*>(line);
// and just do whatever I wanted to do with that value;
setRecursion( db->value );
}
else if(line->key == "max_search_depth" ){
declaration_int *di = dynamic_cast<declaration_int*>(line);
setDepth( di->value );
}
else if(line->key == "job_name" ){
declaration_string *ds = dynamic_cast<declaration_string*>(line);
statusReport( ds->value );
}
else {
// unknown/bad key found. deal with it.
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There's quite a bit to comment on here, however, it's late, so I'm going to post a solution to your problem, and then try and quickly explain it. Hopefully I can edit this post with more details soon.</p>\n\n<p>Crux of the solution: there are two major problems here. Firstly, the keys are not stored in any kind of way that makes their associated values easy to access. The second, and more difficult problem, is that the caller must know <strong>in advance</strong> what type a given key maps to.</p>\n\n<p>We'll solve the first problem with a <code>std::map</code>. The second problem requires more sophisticated machinery. In this case, we'll use a <code>boost::variant</code>, which is a <em>discriminated union</em> type: it can store any one of a number of types (which are specified via template):</p>\n\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <map>\n#include <string>\n#include <utility>\n\n#include \"boost/variant.hpp\"\n\nenum contains_type\n{\n BOOL_T, \n INT_T, \n STRING_T, \n NONE_TYPE \n};\n\nstruct type \n{\nprivate:\n\n typedef boost::variant<bool, int, std::string> variant_t;\n typedef std::pair<variant_t, contains_type> value;\n std::map<std::string, value> map_;\n\npublic:\n\n typedef std::map<std::string, value>::const_iterator const_iterator;\n\n void add_value(const std::string& key, const std::string& value)\n {\n variant_t var;\n contains_type c;\n\n if(value == \"true\") {\n var = true;\n c = BOOL_T;\n }\n else if(value == \"false\") {\n var = false;\n c = BOOL_T;\n }\n else if(std::all_of(value.begin(), value.end(),\n [](char c) { return std::isdigit(c); })) {\n var = std::atoi(value.c_str());\n c = INT_T;\n } else {\n var = value;\n c = STRING_T;\n }\n\n map_.insert(std::make_pair(key, std::make_pair(std::move(var), c)));\n }\n\n const_iterator get_value(const std::string& key) const\n {\n return map_.find(key);\n }\n\n bool get_value_bool(const std::string& key) const {\n auto it = map_.find(key);\n return boost::get<bool>(it->second.first);\n }\n\n int get_value_int(const std::string& key) const {\n auto it = map_.find(key);\n return boost::get<int>(it->second.first);\n }\n\n std::string get_value_string(const std::string& key) const\n {\n auto it = map_.find(key);\n return boost::get<std::string>(it->second.first);\n }\n\n contains_type get_type(const std::string& key) const\n {\n auto it = map_.find(key);\n if(it == map_.end()) return NONE_TYPE;\n return it->second.second;\n }\n\n const_iterator begin() const\n {\n return map_.begin();\n }\n\n const_iterator end() const\n {\n return map_.end();\n }\n};\n\nint main()\n{\n type t;\n t.add_value(\"enable_recursion\", \"true\");\n t.add_value(\"max_search_depth\", \"10\");\n t.add_value(\"job_name\", \"foobar\");\n contains_type c = t.get_type(\"enable_recursion\");\n if(c == BOOL_T) {\n bool b = t.get_value_bool(\"enable_recursion\");\n std::cout << \"enable_recursion: \" << b << \"\\n\";\n }\n}\n</code></pre>\n\n<p>A quick rundown of how this works: we have a <code>boost::variant<bool, int, std::string></code>. This\ncan have any one of those types assigned to it. We also have an <code>enum</code> which will be stored\nwith it that will keep track of what type it is assigned. We store both of these, along with the <code>std::string</code> key in a <code>std::map</code>. That's basically all of the top stuff taken care of.</p>\n\n<p><code>add_value</code> simply inserts the <code>key</code> into the map, converts the <code>value</code> string into the correct type, and stores the value/type pair under that key in the <code>map</code>.</p>\n\n<p>The other functions are mainly for convenience.</p>\n\n<p>This may be too advanced for you currently, but it does solve both problems. As I said, I'll try and update this post with more information (and some actual feedback on your code) when I get a chance.</p>\n\n<p>Edit: Ok, now for an actual code review.</p>\n\n<p>Your design utilises <code>dynamic_cast</code> in a number of places. You can actually replace all of these in the <code>readLine</code> function with <code>static_cast<declaration></code> since we know that it will not fail here. This will also not incur the performance penalty of having to do the type check. </p>\n\n<p>The memory leak you talk about shouldn't really be something that is an afterthought. In this situation, if you have access to C++11, you should be using RAII to stop memory leaks and to solidify ownership:</p>\n\n<pre><code>#include <memory>\n\nstd:unique_ptr<declaration> readLine()\n{\n //...\n}\n</code></pre>\n\n<p>The main difficulty with this design is, as I've said previously, that the user of this has to know in advance what type you're getting back is. Unfortunately, this is the opposite of the problem that polymorphism is trying to solve. With polymorphism, the idea is that you get back an instance of some class that conforms to an interface, but that you should not care what the underlying type is. In this case, you're returning a base class, but you are required to know what its underlying subclass is. Because of the nature of the problem, and the fact that C++ cannot overload functions by return type, this isn't really the correct way to go: classic OOP won't work here. What is really required is more akin to <code>union</code>, which has its own problems. Thus the choice of using <code>boost::variant</code> in the solution above: it can be used in similar situations, but is generally easier and less error prone to work with.</p>\n\n<p>As a final word, this solution itself still isn't perfect. It is still relatively easy for a someone using the above code to forget to do the proper checks to make sure they're casting things to the correct type. Due to the nature of the way the data is stored, this isn't really something that can be worked around in the code that reads it in. The better option would be to modify the data itself: this could be as simple as adding an extra field with the value type or prefacing the value with its type, for example:</p>\n\n<pre><code>max_search_depth integer:10\nenable_recursion boolean:false\njob_name string:Khalessi\n</code></pre>\n\n<p>Then, while parsing the file, the type information would be there along with the value. If you are able to modify the file format, this may be the simplest solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:12:39.933",
"Id": "29499",
"ParentId": "29474",
"Score": "2"
}
},
{
"body": "<p>Your main issues is that on input you have different types for each key. So you spend time building a generic class hierarchy to hold each of the types. But the main code we see that each specific key expects a specific type of value and thus you try and decode the generic type based on the key value. Personally I would reverse this pattern.</p>\n<p>As you read the input. When each key is found extract the type you want and call the appropriate handler method.</p>\n<p>Your second problem is the number of keys that you will eventually have. Yes you should re-write the code to be data driven. That means you to store the mappings of key to action in data not the code. Thus making the driver code short east to read and the same in every case. The only interesting part of the code becomes the data.</p>\n<p>Below I have mapped keys to actions in the data structure <code>actionMap</code>.</p>\n<pre><code>#include <map>\n#include <algorithm>\n#include <string>\n#include <memory>\n#include <functional>\n#include <iostream>\n\nvoid setRecursion( bool enabled ){} \nvoid setDepth( int levels ){} \nvoid statusReport( std::string job_name ){}\n\ntemplate<typename R> R readA(std::istream& stream)\n{\n R value;\n stream >> value;\n return value;\n}\n\nint main()\n{\n std::map<std::string, std::function<void(std::istream&)> > const action\n {\n {"enable_recursion", [](std::istream& value){setRecursion(readA<bool>(value));}},\n {"max_search_depth", [](std::istream& value){setDepth(readA<int>(value));}},\n {"job_name", [](std::istream& value){statusReport(readA<std::string>(value));}}\n };\n\n std::string key;\n while(std::cin >> key)\n {\n auto find = action.find(key);\n if (find != action.end())\n {\n // If we find an action in the action map\n // then call it.\n find->second(std::cin);\n }\n else\n { \n // Unknown action deal with it.\n }\n // Ignore any unused values on the line\n // Thus each iteration of the loop starts at\n // the beginning of a new line.\n std::string ignoreLine;\n std::getline(std::cin, ignoreLine);\n }\n}\n</code></pre>\n<p>The above is C++11. But it is easy to re-write for C++03. The main features of C++ here are syntactic sugar over well known easy to use C++03 ways of doing things (that take slightly more typing).</p>\n<h3>Comments on your code:</h3>\n<pre><code>while( lines_remaining-- ){\n\n declaration *line = readLine();\n</code></pre>\n<p>This is usually an anti-pattern. What happens if the readLine() fails? You should check for that.</p>\n<p>The normal pattern would be:</p>\n<pre><code>declaration* line\nwhile(lines_remaining-- && ((line = readLine()) != NULL)){\n // The loop is only enetered\n // if the loop succeded.\n</code></pre>\n<p>You will see this pattern in most languages. The read is always part of the test to see if it we do something next (do work/enter a loop).</p>\n<p>You mention you know it is a resource problem</p>\n<pre><code>declaration *line = readLine();\n</code></pre>\n<p>but even for a simple example this leak can easily be solve.</p>\n<pre><code>std::unique_ptr<declaration> readLine();\n\n// STUFF\nstd::unique_ptr<declaration> line = readLine();\n</code></pre>\n<p>The use of smart pointers to indicate ownership symantics so should be automatic. The use of smart pointers to make sure that you don't leak resources should be automatic.</p>\n<p>If you have to force polymorphsm on the code use the virtual destructor. You need one anyway. As a calling the destructor via the base class pointer is UB if the destructor is not virtual.</p>\n<p>Potentially you can make it pure as a sub-class will automatically define its own destructor. But this will make sure you can not instantiate any version of the abstract base class.</p>\n<pre><code>struct declaration {\n\n std::string key;\n\n virtual ~declaration() = 0;\n};\n</code></pre>\n<p>But the above is a bad idea (you are not really using the polymorphic properties anyway. Also when you see <code>dynamic_cast<></code> in the code there is usually something wrong with the design.</p>\n<pre><code>declaration_bool *db = dynamic_cast<declaration_bool*>(line);\n</code></pre>\n<p>Actions based on specific types should be accessed via a call to a virtual function. Where each type then handles that action in their own special way.</p>\n<p>Also you should check that the result of the cast is not NULL.</p>\n<p>You don't need to use dynamic_cast<> when returning.</p>\n<pre><code> return dynamic_cast<declaration*>(d_int);\n</code></pre>\n<p>the result is already a <code>declaration*</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T11:00:16.803",
"Id": "29612",
"ParentId": "29474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T01:09:41.627",
"Id": "29474",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Trying to find a good design for reading in values of different types from a file"
}
|
29474
|
<p>I have written the script, which unzips a zip file (passed as argument to the bash), loops through directory and files, then perform different actions based on directory or file. It is working fine.</p>
<p>However I would like to know some things:</p>
<ol>
<li>Is it possible to do this without the unzip command? I somehow feel like that step can be avoided and we can directly use the zip file to perform the task.</li>
<li>I have used three temporary files/directories(tmp.txt - to store the directory and file lines, out.xml - for the curl command, DIREC - for finding the files and directories). I have removed those three files at the end of the script. Is there a way to optimize this? may be using variables instead of files.</li>
</ol>
<p>Here is the bash script, with comments:</p>
<pre><code>#!/bin/bash
#The below line unzips the zip file as passed as argument
unzip $1
length=${#1}
const=4
count=$((length-const))
DIREC=$(echo $1 | cut -b 1-$count)
OUTPUTFIL=out.xml
#The below line will find the directory, which was created by the unzip command. Creation of tmp.txt here.
find $DIREC -exec echo {} \; >tmp.txt
exec<tmp.txt
while read line
do
if [ -d "${line}" ] ; then
echo "$line is a directory";
else
if [ -f "${line}" ]; then
BASE=$(base64 $line);
echo "${line} is a file";
{
echo "<inpu>${BASE}</inpu>"
} > ${OUTPUTFIL}
curl -u admin:secret --data-binary @out.xml http://dp1-l2.com; echo
else
echo "${line} is not valid";
exit 1
fi
fi
done
rm -f tmp.txt
rm -rf $DIREC
rm -f out.xml
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>There's no documentation. Even a comment at the top of the script summarizing what it does would be better than nothing.</p></li>\n<li><p>There's no error handling. What if the user forgets the argument?</p></li>\n<li><p>This script will break if the argument <code>$1</code> contains a space. You need to write <code>\"$1\"</code> in several places.</p></li>\n<li><p>You don't need to put <code>;</code> at the end of lines like this:</p>\n\n<pre><code>echo \"$line is a directory\";\n</code></pre></li>\n<li><p>This code is really unclear:</p>\n\n<pre><code>length=${#1}\nconst=4\ncount=$((length-const))\nDIREC=$(echo $1 | cut -b 1-$count)\n</code></pre>\n\n<p>First, the variable names are poorly chosen: <code>length</code> of what? why <code>const</code>? <code>count</code> of what? Second, this assumes that <code>$1</code> ends with <code>.zip</code> and will go wrong if the file has any other name. Third, Bash has a feature <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion\" rel=\"nofollow\"><code>${parameter%pattern}</code></a> for removing a suffix from a string, so you can remove the extension from <code>$1</code> like this:</p>\n\n<pre><code>DIREC=${1%.*}\n</code></pre>\n\n<p>But fourth and most importantly, how do you know that the ZIP file will unpack into a directory with the same name as the ZIP file? In the example below I create a ZIP file called <code>b.zip</code> that unzips into the directory <code>a</code>:</p>\n\n<pre><code>$ mkdir a\n$ touch a/a\n$ zip b a/a\n adding: a/a (stored 0%)\n$ rm -r a\n$ unzip b\nArchive: b.zip\n extracting: a/a \n</code></pre>\n\n<p>What you should do instead (that is, if you must unzip <code>$1</code>) is to use the <code>-d</code> option to <a href=\"http://linux.die.net/man/1/unzip\" rel=\"nofollow\"><code>unzip</code></a> to extract it to a known place.</p>\n\n<pre><code>$ unzip -d b b\nArchive: b.zip\n extracting: b/a/a \n</code></pre></li>\n<li><p>Why is <code>OUTPUTFIL</code> misspelled? Why not spell it <code>OUTPUT_FILE</code>?</p></li>\n<li><p>It's a bad idea to put temporary files like <code>$OUTPUTFIL</code> in the current directory. There might already be a file called <code>out.xml</code> in the current directory and then you would end up overwriting it. You should use the <a href=\"http://linux.die.net/man/1/mktemp\" rel=\"nofollow\"><code>mktemp</code></a> program to create a unique temporary file name or directory, for example like this:</p>\n\n<pre><code>OUTPUT_FILE=$(mktemp -t unzip-XXXXXX.xml)\n</code></pre></li>\n<li><p>These lines have several problems:</p>\n\n<pre><code>find $DIREC -exec echo {} \\; >tmp.txt\nexec<tmp.txt\nwhile read line\n</code></pre>\n\n<p>First, this will go wrong if <code>$DIREC</code> contains a space: you need to use quotes.\nSecond, this will go wrong if <code>$DIREC</code> starts with a <code>-</code> (it will be interpreted as an option): you need to use the <code>-f</code> option to <a href=\"http://linux.die.net/man/1/find\" rel=\"nofollow\"><code>find</code></a>.\nThird, there's no need to run a separate <code>echo</code> command for each file: <a href=\"http://linux.die.net/man/1/find\" rel=\"nofollow\"><code>find</code></a> has a <code>-print</code> option.\nFourth, you don't need to write the output to a temporary file in order to read it using <code>while read line</code>; you can pipe the output of <a href=\"http://linux.die.net/man/1/find\" rel=\"nofollow\"><code>find</code></a> into the <code>while</code> loop. Like this:</p>\n\n<pre><code>find -f \"$DIREC\" -- -print | while read line; do\n</code></pre></li>\n<li><p>Inside your <code>while</code> loop you use <code>[ -f ... ]</code> to ensure that you only process plain files (not directories). But you could use the <code>-type f</code> argument to <a href=\"http://linux.die.net/man/1/find\" rel=\"nofollow\"><code>find</code></a> to ensure that it only outputs plain files:</p>\n\n<pre><code>find -f \"$DIREC\" -- -type f -print | while read line; do\n</code></pre></li>\n<li><p>This line will go wrong if <code>$line</code> contains a space or starts with a <code>-</code>:</p>\n\n<pre><code>BASE=$(base64 $line);\n</code></pre>\n\n<p>You should write:</p>\n\n<pre><code>BASE=$(base64 -i \"$line\")\n</code></pre></li>\n<li><p>It's not a good idea to read the output of the <a href=\"http://linux.die.net/man/1/base64\" rel=\"nofollow\"><code>base64</code></a> program into a variable like this: the output might be very large and cause Bash to use large amounts of memory. It is better to let <a href=\"http://linux.die.net/man/1/base64\" rel=\"nofollow\"><code>base64</code></a> write its output directly to your output file, so that it does not have to be stored in a variable in Bash. Instead of:</p>\n\n<pre><code>BASE=$(base64 $line);\n{\n echo \"<inpu>${BASE}</inpu>\"\n} > ${OUTPUTFIL}\n</code></pre>\n\n<p>you should write:</p>\n\n<pre><code>{\n echo \"<inpu>\"\n base64 -i \"$line\"\n echo \"</inpu>\"\n} > \"${OUTPUT_FILE}\"\n</code></pre></li>\n<li><p>However, there is no need for an <code>OUTPUT_FILE</code> at all here, because <a href=\"http://linux.die.net/man/1/curl\" rel=\"nofollow\"><code>curl</code></a> accepts the filename <code>-</code> meaning \"standard input\", so you can write:</p>\n\n<pre><code>{\n echo \"<inpu>\"\n base64 -i \"$line\"\n echo \"</inpu>\"\n} | curl -u admin:secret --data-binary @- http://dp1-l2.com\n</code></pre></li>\n<li><p><code><inpu></code> looks like a typo to me. Are you sure you don't mean <code><input></code>? If <code><inpu></code> is correct, you should probably add a comment to explain why.</p></li>\n<li><p>It would be better to put configuration settings like <code>admin:secret</code> and <code>http://dp1-l2.com</code> in named variables at the top of the file. (It might be even better to accept them as command-line arguments.)</p></li>\n<li><p>The way you have written this code means that each individual file in the archive gets uploaded as a separate XML file to the server. Is this really what you want? It seems more likely to me that you would want to upload the whole archive as one XML file. Otherwise, what's the point of using XML?</p></li>\n<li><p>As you suspected, there is in fact no need to unzip the file, because you can use <a href=\"http://linux.die.net/man/1/zipinfo\" rel=\"nofollow\"><code>zipinfo -1</code></a> to get a listing of the contents, and then use the <code>-p</code> option to <a href=\"http://linux.die.net/man/1/unzip\" rel=\"nofollow\"><code>unzip</code></a> to extract a file to standard output.</p></li>\n</ol>\n\n<p>Putting all this together, I would write the script line this:</p>\n\n<pre><code>#!/bin/bash\n# upload-zip.sh -- encode contents of ZIP archive as base64\n# strings in an XML document, and upload it.\n\n# Destination and credentials for upload.\nUPLOAD_URL=http://dp1-l2.com\nUSER=admin\nPASSWORD=secret\n\nif [ \"$#\" != 1 ]; then\n echo \"Usage: $0 zipfile\"\n exit 1\nfi\nZIPFILE=$1\n\nzipinfo -1 -- \"$ZIPFILE\" | while read FILE; do\n echo \"<input>\"\n unzip -p -- \"$ZIPFILE\" \"$FILE\" | base64\n echo \"</input>\"\ndone | curl --user \"$USER:$PASSWORD\" --data-binary @- --url \"$UPLOAD_URL\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T14:37:31.087",
"Id": "33178",
"ParentId": "29477",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T03:20:31.417",
"Id": "29477",
"Score": "1",
"Tags": [
"bash"
],
"Title": "script- loop through files and directories"
}
|
29477
|
<p>All this code does is transfer the files. In order to make changes to the file, one has to re-transfer the file. During this time, I stand by to automate the update operation, where the server listens to the files and updates them automatically whenever any changes are made.</p>
<pre><code>fileserver.java
import java.io.*;
import java.net.*;
import java.util.*;
public class FileServer {
private static ServerSocket serverSocket;
private static Socket clientSocket = null;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(13850);// creating a new serversocket
System.out.println("Server started.");
} catch (Exception e)// catches errors and display them to the user for eg in case the port is busy we may specify a different port
{
System.err.println("Port already in use.");
System.exit(1);
}
while (true)
{
try {
clientSocket = serverSocket.accept();// establishing the connection
System.out.println("Accepted connection : " + clientSocket);
Thread t = new Thread(new CLIENTConnection(clientSocket));
/*creating thread for clientconnection.java file and sending socket as an object thus everytime a connection is established a new thread/process is generated through which the file is sent and recieved*/
t.start();// executing the thread. here the new process or thread is created and ready to be implemented
} catch (Exception e) // catches error if any and displays it in the terminal/command prompt
{
System.err.println("Error in connection attempt.");
}
}
}
}
clientconnection.java
import java.util.*;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.String;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
receiveFile();
in.close();
}
catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File "+fileName+" received from client.");
} catch (IOException ex) {
System.err.println("Client error. Connection closed.");
}
}
}
filecliet.java
import java.io.*;
import java.util.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileClient {
private static Socket sock;// defining a socket
private static String fileName;// defining a file
private static BufferedReader stdin;// creating a buffered reader object to take and read the input from the users
private static PrintStream os;// creating an object of printstream to display text or output in the terminal/command prompt
public static void main(String[] args) throws IOException {
try {
sock = new Socket("localhost", 13850);// creating a socket specifying the port and the ip address of the server to the client
stdin = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later."+e);
System.exit(1);
}
os = new PrintStream(sock.getOutputStream());
try {
sendFile();
} catch (Exception e) {
System.err.println("not valid input");
}
sock.close();
}
public static void sendFile() {
try {
System.err.print("Enter file name: ");
fileName = stdin.readLine();//reads the file entered by the user
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];//determining the lenght of the file
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);//creating an input stream to read the contents of the file
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);//creating an output stream to send the file to the server
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);//writing the contents of the file to the server
dos.flush();
System.out.println("File "+fileName+" sent to Server.");
} catch (Exception e) { //reports error if any
System.err.println("File does not exist!");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your socket communication protocol is asymmetrical..... the client-side cannot correctly send files larger than 2GB (though the server side looks like it can handle it).</p>\n<p>Additionally, your client-side code reads the entire file in to memory.... which is wasteful and unnecessary.</p>\n<p>Using the functions available in Java7, you should be using try-with-resources. As it is, you are not closing your sockets correctly, and you're not closing file-handles right either.</p>\n<p>Additionally, your methods should complete just a single function. Your sendFile method does user-input as well as the network transfer. I would recommend that you take the user-input out of the method. The receiveFile side of things also has hard-coded file names and locations. I recommend parameterizing it.</p>\n<p>Finally, you do not do anything to trap problems with file-changes that may happen mid-transfer, and your error-handling in general is a problem.</p>\n<p>I have taken these two methods and re-structured them in a way that:</p>\n<ul>\n<li>has single functionality in each method.</li>\n<li>does correct resource-closing (even in exceptional conditions)</li>\n<li>is symmetrical (you can send and receive large files)</li>\n<li>handles cases where the file changes mid-send, or is not completely received.</li>\n<li>uses the socket send/recieve buffer-sizes to set the right size byte-buffer arrays</li>\n</ul>\n<p>The methods take some input parameters that are not part of your specification. This is to ensure single-responsibility is maintained.</p>\n<p>The exception handling is still not great, but would need to conform to your overall system.</p>\n<p>Consider the methods...</p>\n<h2>receiveFile:</h2>\n<pre><code>public static final void receiveFile(File outdir, Socket sock) {\n try (DataInputStream clientData = new DataInputStream(new BufferedInputStream(sock.getInputStream()))) {\n\n String fileName = clientData.readUTF();\n \n try (OutputStream output = new BufferedOutputStream(new FileOutputStream(new File(outdir, "received_from_client_" + fileName)))) {\n long size = clientData.readLong();\n long bytesRemaining = size;\n byte[] buffer = new byte[sock.getReceiveBufferSize()];\n int bytesRead = 0;\n while (bytesRemaining > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, bytesRemaining))) >= 0) {\n output.write(buffer, 0, bytesRead);\n bytesRemaining -= bytesRead;\n }\n output.flush();\n if (bytesRemaining > 0) {\n throw new IllegalStateException("Unable to read entire file, missing " + bytesRemaining + " bytes");\n }\n if (clientData.read() >= 0) {\n throw new IllegalStateException("Unexpected bytes still on the input from the client");\n }\n }\n\n } catch (IOException ex) {\n System.err.println("Unexpected Client error: " + ex.getMessage());\n ex.printStackTrace();\n }\n \n}\n</code></pre>\n<h2>sendFile:</h2>\n<pre><code>public static void sendFile(String fileName, String host, int port) throws IOException {\n\n File myFile = new File(fileName);\n long expect = myFile.length();\n try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));\n Socket sock = new Socket(host, port);\n DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()))) {\n \n byte[] buffer = new byte[sock.getSendBufferSize()];\n dos.writeUTF(myFile.getName());\n dos.writeLong(expect);\n \n long left = expect;\n int inlen = 0;\n while (left > 0 && (inlen = bis.read(buffer, 0, (int)Math.min(left, buffer.length))) >= 0) {\n dos.write(buffer, 0, inlen);\n left -= inlen;\n }\n dos.flush();\n if (left > 0) {\n throw new IllegalStateException("We expected " + expect + " bytes but came up short by " + left);\n }\n if (bis.read() >= 0) {\n throw new IllegalStateException("We expected only " + expect + " bytes, but additional data has been added to the file");\n }\n }\n}\n</code></pre>\n<p>I have tested this using some junk data I have, and the main method:</p>\n<pre><code>public static void main(String[] args) {\n \n File outdir = new File("copiedfiles");\n if (!outdir.isDirectory()) {\n outdir.mkdirs();\n }\n \n final int port = 13850;\n final String host = "localhost";\n \n Runnable client = new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(2000);\n sendFile("core.20131214.230701.4868.0001.dmp", host, port);\n } catch (IOException | InterruptedException e) {\n e.printStackTrace();\n }\n }\n };\n \n Thread clientthread = new Thread(client);\n clientthread.setDaemon(true);\n clientthread.start();\n \n try (ServerSocket ssocket = new ServerSocket(port)) {\n Socket clientsock = ssocket.accept();\n receiveFile(outdir, clientsock);\n } catch (IOException e) {\n e.printStackTrace();\n }\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:49:36.873",
"Id": "40971",
"ParentId": "29478",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T04:09:31.117",
"Id": "29478",
"Score": "4",
"Tags": [
"java",
"socket"
],
"Title": "Transfer log file between client and server while updating files automatically"
}
|
29478
|
<p>I have a <code>Customer</code> class that has the code below. I can refactor the two if condition clauses into the <code>Memebership</code> class. Apart from that, I am wondering how I should refactor the if clause within the <code>Benefits</code> set property, without over-complicating thing.</p>
<p>Does any one of these below apply?</p>
<p>Patterns of refacotring if to subclass/strategy/state/polymorphism.</p>
<pre><code> public class Customer
{
public Membership Membership { get; private set; }
public bool Hasbenefits { get; private set; }
private int benefits;
public int Benefits
{
get
{
return benefits;
}
set
{
if (Membership.Name == "MembershipA")
{
this.Hasbenefits = false;
}
else if (Membership.Name == "MembershipB")
{
this.Hasbenefits = true;
this.benefits = value * 4 + 2;
}
else
{
this.Hasbenefits = true;
this.benefits = value;
}
}
}
}
</code></pre>
<p>Any advice would be very much appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:04:38.113",
"Id": "46618",
"Score": "1",
"body": "I'd be wary of this initial design from the get-go. That's all fine because you're asking about re-factoring, but the general consensus is that properties shouldn't really have adverse side-effects, and yet that's what is happening here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:05:18.550",
"Id": "46619",
"Score": "1",
"body": "well, for one, `Membership.Name` doesn't look like a **name** so much as it looks like a **type**, and it should be probably defined as an `enum` of some sort instead of a `string`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:05:28.257",
"Id": "46620",
"Score": "0",
"body": "This logic should be in its own method, since your setting two fields in this setter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:08:00.313",
"Id": "46621",
"Score": "0",
"body": "@Moo-Juice Could you elaborate? Do you mean property cannot have Set property?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:11:04.703",
"Id": "46622",
"Score": "0",
"body": "@Karl Anderson How should I transfer to there? Or close/delete it and repost it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:11:55.293",
"Id": "46623",
"Score": "1",
"body": "Looks like HasBenefits belong to Membership object (likely to be extended)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:12:39.277",
"Id": "46624",
"Score": "0",
"body": "@Pingpong, the consensus is that properties should be pretty simple getters and setters. Basically \"don't over-complicate things\". In this case, you are changing quite a bit which the unwary programmer might not understand the consequences. You're performing some business logic. Have a property to return the benefits, and a method that explicitly declares it's going to do something, e.g. `SetBenefitModel` or whatever is pleasing to you and your team."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:14:04.297",
"Id": "46625",
"Score": "0",
"body": "@Pingpong - you do not have enough reputation to request the question be moved (3,000 is the cutoff for that). Would you like for me to request the question be moved?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:15:10.083",
"Id": "46626",
"Score": "0",
"body": "@ Karl Anderson please do that for me. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:17:50.750",
"Id": "46627",
"Score": "1",
"body": "@Pingpong - I have notified a moderator of your wish to move this question to the Code Review site. I cannot automatically do it, because Code Review is not a choice for migration yet, it must be done by a moderator, which I am not."
}
] |
[
{
"body": "<p>Personally here's what I would do :</p>\n\n<p>Use the Membership type to create derived class; this will remove the if chain completely.\nAvoid side effects in setters; bad practice in my opinion.\nAvoid using properties with private sets; bad practice in my opinion.</p>\n\n<p>This results in the following code :</p>\n\n<pre><code>public abstract class Customer\n{\n protected int benefits;\n\n public abstract void UpdateBenefits(int newBenefits);\n\n public bool HasBenefits()\n {\n return benefits != 0;\n }\n\n public int GetBenefits()\n {\n return benefits;\n }\n }\n\n public class MembershipACustomer : Customer\n {\n public override void UpdateBenefits(int newBenefits)\n {\n }\n }\n\n public class MembershipBCustomer : Customer\n {\n public override void UpdateBenefits(int newBenefits)\n {\n benefits = newBenefits * (4 + 2);\n }\n }\n\n public class MembershipSomethingElseCustomer : Customer\n {\n public override void UpdateBenefits(int newBenefits)\n {\n benefits = newBenefits;\n }\n }\n</code></pre>\n\n<p>IMO it would also be a good idea to make a hierarchy with a new Benefit class, instead of customers. You can pass the benefit type to the customer by DI and that way it is the Benefit class that is responsible for calculating the benefit, not the customer. This would respect SRP a little more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:19:48.513",
"Id": "46629",
"Score": "0",
"body": "Thanks! This is pretty valid, which is also one of my refactoring choices."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:24:22.357",
"Id": "46630",
"Score": "0",
"body": "What does it mean to return true from HasBenefits() if the UpdateBenefits() has yet to be called so there is no defined benefit yet?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:29:03.070",
"Id": "46631",
"Score": "0",
"body": "@djna Hmm.. indeed! Don't know why, but at first I saw it as \"This membership can have benefits\" instead of \"This customer currently have benefits\". Fixed the code, it simplified the things a lot more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T01:55:34.597",
"Id": "46632",
"Score": "0",
"body": "@Pierre-LucPineault is it `newBenefits * (4 + 2)` or `(newBenefits * 4) + 2`? Looks like the example uses the second. On a side note, it can be refactored into interfaces `IBenefitable` and completely removing the need of `HasBenefits`. But it can be an overkill for such scenario."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:15:49.570",
"Id": "29480",
"ParentId": "29479",
"Score": "4"
}
},
{
"body": "<p>My solution is thus:</p>\n\n<ol>\n<li><p>Remove the setter, it fundamentally changes the object in ways that the \"property\" idiom would be violated:</p>\n\n<pre><code>public class Customer\n{\n public Membership Membership { get; private set; }\n public bool Hasbenefits { get; private set; }\n\n private int benefits;\n\n public int Benefits\n {\n get\n {\n return benefits;\n }\n }\n</code></pre>\n\n<p>}</p></li>\n</ol>\n\n<p>Right, so what now. We're still left with refactoring that if, and (imho) we've made the concious decision to use a method so that the caller of the method understand that there may be fundamental changes. My solution involves putting a setter back in, but making it simple:</p>\n\n<pre><code> public int Benefits\n {\n get\n {\n return benefits;\n }\n set \n {\n benefits = value;\n }\n }\n</code></pre>\n\n<p>Now I would have another class. The one that is responsible for determining benefits. Let's call it a <code>BenefitProvider</code>.</p>\n\n<pre><code> public sealed class BenefitProvider\n {\n public void ProvideBenefit(Customer customer) // You have ONE job to do\n {\n /*\n * Do you stuff here. You could use some predicates to cut down on the \n * if/else kind of stuff\n */\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:24:47.507",
"Id": "46633",
"Score": "0",
"body": "You said: \"setter, it fundamentally changes the object in ways that the \"property\" idiom would be violated\" Could you please elaborate on this idiom?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T22:09:44.073",
"Id": "46634",
"Score": "1",
"body": "Setting a property should just set the value of the property. It shouldn't do other stuff. If you want to do other stuff use a method or extract a class as in this answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:19:44.387",
"Id": "29481",
"ParentId": "29479",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T20:02:06.237",
"Id": "29479",
"Score": "1",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Refactoring If clause"
}
|
29479
|
<p>I want to create an like button like on Twitter. I used Twitter bootstrap and this code:</p>
<pre><code>$(document).ready(function(){
$('.btn-follow').on('mouseover', function(e){
if ($(this).hasClass('following')){
$(this).removeClass('btn-primary').addClass('btn-danger').text('UnFollow');
}
})
$('.btn-follow').on('mouseleave',function(e){
if ($(this).hasClass('following')){
$(this).text('Following').removeClass('btn-danger').addClass('btn-primary');
}
})
$('.btn-follow').on('click',function(e){
$(this).toggleClass('following follow')
if ($(this).hasClass('follow')){
alert('unfollow')
$(this).text('Follow').removeClass('btn-danger')
}else{
alert('follow')
$(this).text('Following')
}
})
});
</code></pre>
<p>And in HTML I have this:</p>
<pre><code> <button class="btn btn-primary btn-follow following">Following</button>
<br />
<br />
<button class="btn btn-follow follow">Follow</button>
</code></pre>
<p>But I think it's very dirty code and has some bugs. How can I summarize this code? </p>
<p>This code has a bug. When I click on click of the follow button, the text is changed to "Following", but the color of the button is not changed while the mouse leave from the button area. How I can fix it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T17:04:17.357",
"Id": "46674",
"Score": "0",
"body": "Care to add what *bugs* you are experiencing? That would speed up answering..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T00:16:13.700",
"Id": "46694",
"Score": "0",
"body": "I edit this question. You can test it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T04:41:45.263",
"Id": "46699",
"Score": "0",
"body": "Please add the CSS code to your question if you need info about colors changing."
}
] |
[
{
"body": "<p>I reworked the code a bit. Check out the comments for explanation. </p>\n\n<pre><code>$(document).ready(function() {\n //Don't copy and paste the same string.\n //It is also helpful when the CSS or text changes. There is just one part\n //of the code to look at.\n var followBtn = $('.btn-follow'),\n followCls = 'following',\n dangerCls = 'btn-danger',\n primaryCls = 'btn-primary',\n unfollowText = 'UnFollow',\n followText = 'Follow'\n\n //No need to keep making a jQuery \"query\" to get a the button every time.\n //I am not sure about the internals of jQuery, but I assume it is reading the \n //DOM on every $('.btn-follow') call.\n\n\n //Don't pass argument to method if it is not being used.\n followBtn.on('mouseover', function(){\n //same thing inside the handler no need for $(this).\n if (followBtn.hasClass(followCls)){ \n followBtn.removeClass(primaryCls).addClass(dangerCls).text(unfollowText);\n }\n });\n\n followBtn.on('mouseleave',function(){\n if (followBtn.hasClass(followCls)){\n //Keep the same order as before, just be consistent.\n followBtn.removeClass(dangerCls).addClass(primaryCls).text(followText);\n }\n });\n //The rest\n});\n</code></pre>\n\n<p>If you post the <a href=\"http://en.wikipedia.org/wiki/Cascading_Style_Sheets\" rel=\"nofollow\">CSS</a> I can help you with that. I suspect that a few of the removeClass calls can be removed in favor of more specific selectors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T01:15:49.140",
"Id": "29577",
"ParentId": "29486",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T08:30:45.317",
"Id": "29486",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"twitter-bootstrap"
],
"Title": "Follow button like on Twitter"
}
|
29486
|
<pre><code>if ((key == null && group.Key == null) || (key is DBNull && group.Key is DBNull) ||
(!(key is IComparable) && !(group.Key is IComparable)))
</code></pre>
<p>Can the above code simplified like below,</p>
<pre><code>if(key == group.key || (!(key is IComparable) && !(group.Key is IComparable)))
</code></pre>
|
[] |
[
{
"body": "<p>No, not unless you restrict what values the variables can have, or what type they are declared as.</p>\n\n<p>If for example <code>key</code> is an <code>int</code> with the value <code>4</code> and <code>group.Key</code> is an <code>int</code> with the value <code>4</code>, the first code gives <code>false</code> while the second code gives <code>true</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T10:38:33.373",
"Id": "29490",
"ParentId": "29489",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29490",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T09:48:55.937",
"Id": "29489",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "IComparable comparision"
}
|
29489
|
<p>The following is a code written in Javascript. It let's me change the appearance of a canvas depending on user input.
The question is, how can I make this code more CPU efficient?
I ask that because this code is just barely snappy enough on the iPad 2 and any improvement in speed would be really great to have.</p>
<p>With speed I am mainly focusing on that loop that iterates thousands of times (right now 3.600).</p>
<pre><code>function repeat(){
//pc, input_mouse_x/y becomes input x/y.
if(device_type==0){
ix=input_mouse_x;
iy=input_mouse_y;
//if pc's left mouse button isn't clicked then this isn't a valid input.
if(input_mouse_button_left==0) {ix='-';iy='-';}
}
//ipad, input_touch becomes x/y.
if(device_type==1){
ix=input_touch[0][0];
iy=input_touch[0][1];
//iy=trigonometry.flip({'number':iy,'around':screen_center});
iy+=(screen_center-iy)*2;
}
var pencil_x=ix;
var pencil_y=iy; pencil_y+=(screen_center-pencil_y)*2;
var pencil_width=30;
var pencil_height=30;
var data_quantity=(pencil_width*pencil_height*4);
var pencil_width_half=(pencil_width/2);
var pencil_height_half=(pencil_height/2);
var pencil_begin_x=(pencil_x-pencil_width_half);
var pencil_begin_y=(pencil_y-pencil_height_half);
var image_data=drawing_board_canvas_twod.getImageData(pencil_begin_x,pencil_begin_y,pencil_width,pencil_height);
//everything in this loop must be as cpu efficient as possible.
for(var cdata=3;cdata<3600;cdata+=4){
//data to pixel, and then to x/y.
var cpixel=Math.floor(cdata/4);
var cx=(cpixel%pencil_width);
var cy=parseInt(cpixel/pencil_width);
//find distance to center of pencil.
var to_center_x=Math.abs(pencil_width_half-cx);
var to_center_y=Math.abs(pencil_height_half-cy);
var to_center=Math.pow((Math.pow(to_center_x,2)+Math.pow(to_center_y,2)), 0.5);
if(to_center<17){
image_data.data[cdata]=0;//the higher the denser.
}
}
drawing_board_canvas_twod.putImageData(image_data,pencil_begin_x,pencil_begin_y);
}
</code></pre>
|
[] |
[
{
"body": "<p>The short answer is that you can't, not really anyways. You have no real control over how this code will be compiled. Since you mention iPad, the code is likely to be JIT-compiled to bytecode, prior to execution. How this is done depends (in part) on how the code is written, and <em>how JS is implemented</em>. The second factor, the implementation, is beyond your control.</p>\n\n<p>You're also working with a canvas element. That's not JS that causes the bottleneck there, that's the DOM, which is gouverned by W3C, and is not part of ECMAScript in any way. JS merely has an API, via which it can request the DOM to change state. The DOM API isn't all that good: it's badly designed, slow, counter intuitive and one of the main reasons why many people claim JS is a terrible language. JS isn't, it's the DOM. But I'm going off course.</p>\n\n<p>Inside that loop, which repeats <code>3600</code> times, you're calling a function which isn't part of your post (perhaps provide the source for that). But my guess is, that this function interacts with the dom (perhaps moves something about). If so: request a repaint, using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame\" rel=\"nofollow noreferrer\">the <code>requestAnimationFrame</code> method</a>, it makes a huge difference!</p>\n\n<p>After that, to further optimize your code, use <a href=\"http://jslint.com\" rel=\"nofollow noreferrer\">jslint</a>. As the page says, it will hurt your feelings, but it's the best way to teach yourself some good practices, like not declaring 10001 vars seperatly, but using:</p>\n\n<pre><code>var i, j, another = 123, someArray = [], andAnObject = {};\n</code></pre>\n\n<p>The main bottleneck, however is <code>putImageData</code>. <a href=\"http://jsperf.com/buffering\" rel=\"nofollow noreferrer\">this JSPerf</a> demonstrates an alternative, up to x5000 more performant alternative!<Br/>\nIt uses a neat little trick to buffer the states: it draws from one canvas onto the other, which is a lot faster. As is loading the image, then using:</p>\n\n<pre><code>drawing_board_canvas_twod.getContext('2d').drawImage(image_data, pencil_begin_x, pencil_begin_y);\n</code></pre>\n\n<p>But the way the <code>image_data</code> is gotten in your code still relies on the horrid <code>getImageData</code>, which is outpaced even by getting the img data pixel-by-pixed. <a href=\"https://stackoverflow.com/questions/8453712/horrible-canvas-getimagedata-putimagedata-performance-on-mobile\">Perhaps refer to this question on StackOverflow</a> and all linked pages for details...</p>\n\n<p>For now, the next to last thing I'd suggest is: look into <em>how</em> you call this <code>repeat</code> function of yours. If it's called in response to an event, check to see if you can't, perhaps, <em>delegate</em> that event, eliminating any excess event listeners is always good for performance. Are you using libs like jQuery? Get rid of them if you can, because they <em>are</em> slower than VanillaJS, if you know how to write good vanillaJS, of course.</p>\n\n<p>The last, but certainly not least important thing I'd suggest: <em>never <strong>ever</strong> use globals</em>. Globals are risky, slow, and make for hellish debugging: your code relies on global variables, because the <code>repeat</code> function starts of with:</p>\n\n<pre><code>if(device_type==0)\n</code></pre>\n\n<p><code>device_type</code> is not declared in the scope of <code>repeat</code>, so that implies it being a global variable. Learn about closures, scopes and how to use them. It's what makes JS worth your while.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:46:08.727",
"Id": "46660",
"Score": "0",
"body": "putImageData is a built in canvas function. http://www.w3schools.com/tags/canvas_putimagedata.asp"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:55:52.260",
"Id": "46661",
"Score": "0",
"body": "@HermannIngjaldsson: Good point, mind you `w3schools` is a bad place for info, use MDN instead, as w3fools.com pointed out, w3schools is often lacking, or even providing dead wrong information. Avoid until fixed!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:03:15.193",
"Id": "46662",
"Score": "0",
"body": "In the 3600 function, the only functions I'm calling are parseInt(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) and Math functions, i don't think they mess with the DOM."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T17:51:57.297",
"Id": "46676",
"Score": "1",
"body": "That doesn't matter, you're using 'image_data' which is a reference. Besides, a loop of 3600 times calling core functions isn't likely to be the bottleneck, a single DOM call like yours can _easily_ take twice as long..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:37:59.250",
"Id": "29496",
"ParentId": "29494",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29496",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:08:52.620",
"Id": "29494",
"Score": "2",
"Tags": [
"javascript",
"performance",
"ios",
"canvas"
],
"Title": "Drawing to a canvas based on user input"
}
|
29494
|
<p>The function <code>hash_blog</code> is inspired by <a href="http://git-scm.com/book/en/Git-Internals-Git-Objects" rel="nofollow">"how git stores its objects"</a>. It is supposed to take a <code>String</code>, append a header to it, compute the SHA1 of it, then compress it and write it to a file. The first two characters of SHA1 is a directory name, and the rest of the characters are the file name.</p>
<p>Since I am learning the language, I am looking for general review. Is my code idiomatic Java code? Are there parts where I could make the code better?</p>
<pre><code>package yas;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.DeflaterOutputStream;
// import java.util.zip.Inflater;
public class Yas {
public static void main(String[] args) {
try {
hash_blob("yasar arabaci");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* @param args
* @throws NoSuchAlgorithmException
*/
public static String hash_blob(String content) throws NoSuchAlgorithmException {
String hash_string; // hold sha1 hash
String input = "blob " + content.length() + '\0' + content;
// Step 1 is to compute sha1
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
{ // to create namespace for StringBuilder
// This code block was borrowed from internet ;)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
hash_string = sb.toString();
}
System.out.println("hash string is " + hash_string);
// Step 3 is to write to a file
File dest_file;
{
File yas_dir = new File(System.getProperty("user.dir"), ".yas");
File object_dir = new File(yas_dir, "objects");
File dest_dir = new File(object_dir, hash_string.substring(0, 2));
dest_dir.mkdirs();
dest_file = new File(dest_dir, hash_string.substring(2));
System.out.println("dest file = " + dest_file);
}
try {
if (!dest_file.exists()) {
dest_file.createNewFile();
}
try (OutputStream out = new DeflaterOutputStream(new FileOutputStream(dest_file))) {
out.write(input.getBytes());
}
} catch (IOException e) {
e.printStackTrace();;
}
return "Dummy Return";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T17:57:11.133",
"Id": "46678",
"Score": "0",
"body": "Beginning to learn the language or beginning to learn Object Oriented programming as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T18:02:44.850",
"Id": "46679",
"Score": "0",
"body": "@bowmore I have used Python before, I know the basics of OOP, however I am not much of a fan of OOP :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T18:13:00.560",
"Id": "46681",
"Score": "1",
"body": "Then why adopting an OO language?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T18:23:48.427",
"Id": "46683",
"Score": "0",
"body": "@bowmore Because I was curious what Java would be like since it is a quite popular language."
}
] |
[
{
"body": "<p><strong>Problems</strong> :</p>\n\n<ul>\n<li>methods mkdirs() and createNewFile() return booleans to indicate whether they are successful. You should check and handle if they return false.</li>\n<li>IOException gets ignored, you print the stacktrace but clients have no way of knowing the method failed.</li>\n</ul>\n\n<p><strong>Style</strong> :</p>\n\n<ul>\n<li>This is one procedural block in which different concerns ( finding and creating files, directories, computing hash, converting byte[] to a String, ... ) are handled. Despite an attempt to limit the of variables scope with a block statement, variable scope is unclear and often wider than strictly needed. There is but one cure : refactor : extract method.</li>\n<li>variable naming does not follow <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow\">Java conventions</a>.</li>\n<li>Don't return a dummy return value, declare the method to have <code>void</code> as return value, and you don't need to return a value.</li>\n<li>Comments : step 1, step 3 what happened to step 2?</li>\n<li><code>printStackTrace()</code> statement ends with ;; only one is needed. (probably a typo)</li>\n<li>loop over the byte array can be a foreach loop :</li>\n</ul>\n\n<p>like this : </p>\n\n<pre><code>for (byte aResult : computeSha1Hash(input)) {\n builder.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n}\n</code></pre>\n\n<ul>\n<li>coupling should be reduced. The hashing algorithm (sha1), output mechanism (files) and byte[] to String encoding are all hardwired.</li>\n<li>use of magic numbers; replace with explaining constants.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T15:12:17.277",
"Id": "46718",
"Score": "0",
"body": "Thanks for the input. I have refactored the code and added second version."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T19:26:34.893",
"Id": "29504",
"ParentId": "29501",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T17:29:01.300",
"Id": "29501",
"Score": "3",
"Tags": [
"java",
"io",
"cryptography"
],
"Title": "File I/O, SHA1 sum and compression"
}
|
29501
|
<p>I recently set out to create an open-source ASP.net MVC web development framework. Specifically, I wanted to automate some of the tasks associated with the creation of data-driven applications. I've had to create a number of CRUD screens over the years and wanted to automate as many aspects of these screens as possible.</p>
<p>Today, I published an <a href="https://github.com/DanielLangdon/ExpressForms">early release of this framework on GitHub</a> and gave it the name "Express Forms".</p>
<p>One of the core parts of Express Forms is a Controller class that takes two type parameters. The first type parameter tells Express Forms what class represents a data record to work with, and the second is meant to specify a type that represents an Id, though at the moment it is hard-coded in many places to be a 32-bit integer.</p>
<p>I have included the code to the generic Controller class below.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ExpressForms.Buttons;
using ExpressForms.Inputs;
using System.Reflection;
namespace ExpressForms
{
public class ExpressFormsController<T, TId> : Controller
where T : class, new()
{
protected IExpressFormsExchange<T, TId> Exchange { get; set; }
public ExpressFormsController()
{
// Set default values to properties
IndexViewName = "ExpressFormsIndex";
EditorViewName = "ExpressFormsEditor";
CustomPropertyNames = new Dictionary<string, string>();
CustomPropertyDisplay = new Dictionary<string, Func<dynamic, string>>();
CustomEditorInputs = new Dictionary<string, ExpressFormsInput>();
IgnoredPropertyNames = new string[] { };
}
protected void Initialize(IExpressFormsExchange<T, TId> exchange)
{
Exchange = exchange;
}
#region properties and functions that are used to customize the appearance and behavior of forms
protected string FormName { get { return typeof(T).Name; } }
protected virtual ExpressFormsButton[] IndexButtons
{
get
{
throw new NotImplementedException();
}
}
/// <summary>
/// A virtual helper function that is meant to be used to get the buttons to display on the editor form.
/// May be overridden in a derived class to change what buttons appear.
/// </summary>
/// <param name="model"></param>
/// <param name="isNew"></param>
protected virtual ExpressFormsButton[] GetEditorButtons(bool isNew)
{
List<ExpressFormsButton> buttons = new List<ExpressFormsButton>()
{
new ExpressFormsModifyDataButton()
{
// If the user is inserting a new record, show the user an [Insert] button.
IsVisible = isNew,
Text = "Save",
FormName = FormName,
ActionType = ExpressFormsModifyDataButton.ActionTypeEnum.Insert,
PostUrl = Url.Action("Postback"),
PostType = ExpressFormsModifyDataButton.PostTypeEnum.Ajax
},
new ExpressFormsModifyDataButton()
{
// If the user is updating an existing record, show the user an [Update] button.
IsVisible = !isNew,
Text = "Save",
FormName = FormName,
ActionType = ExpressFormsModifyDataButton.ActionTypeEnum.Update,
PostUrl = Url.Action("Postback"),
PostType = ExpressFormsModifyDataButton.PostTypeEnum.Ajax
}
};
return buttons.ToArray();
} // end GetEditorButtons
// A virtual helper function that is meant to be used to get the inputs that appear on the form.
// May be overridden in a derived class to customize how the form works.
protected virtual Dictionary<string, ExpressFormsInput> GetEditorInputs(T record)
{
// t.GetType() is used here rather than typeof(T) in order to get the most specific type implemented by the object passed in.
IEnumerable<PropertyInfo> properties = record.GetType().GetProperties()
.Where(p => (IgnoredPropertyNames==null) || !IgnoredPropertyNames.Contains(p.Name));
Func<PropertyInfo, ExpressFormsInput> InputSelector = p => GetEditorInput(record, p);
Dictionary<string, ExpressFormsInput> inputs = properties
.ToDictionary(p => p.Name, InputSelector);
return inputs;
}
private ExpressFormsInput GetEditorInput(T record, PropertyInfo property)
{
ExpressFormsInput input;
string inputName = property.Name;
string value = Convert.ToString(property.GetValue(record, null));
bool isVisible = true;
input = GetCustomEditorInput(inputName, value, isVisible);
if (input == null) // we didn't get an input from GetCustomEditorInput
{
switch (property.PropertyType.Name)
{
case "Boolean":
input = new ExpressFormsCheckBox()
{
FormName = FormName,
InputName = inputName,
Value = value,
IsVisible = isVisible,
};
break;
default:
input = new ExpressFormsTextBox()
{
FormName = FormName,
InputName = inputName,
Value = value,
IsVisible = isVisible
};
break;
}
}
// If this property has an associated "CustomPropertyName", use that for the display name. Otherwise, use the inputName.
input.InputDisplayName = CustomPropertyNames.Keys.Contains(input.InputName) ? CustomPropertyNames[input.InputName] : input.InputName;
return input;
}
protected virtual ExpressFormsInput GetCustomEditorInput(string inputName, string value, bool isVisible)
{
ExpressFormsInput customInput;
// If there is a custom input with matching inputName, assign it the value of the input passed in and return it.
if (CustomEditorInputs.Keys.Contains(inputName))
{
customInput = CustomEditorInputs[inputName];
customInput.Value = value;
return customInput;
}
// Otherwise, return null.
else
return null;
}
protected Dictionary<string, ExpressFormsInput> CustomEditorInputs { get; set; }
protected string IndexTitle { get; set; }
protected Dictionary<string, string> CustomPropertyNames { get; set; }
protected IEnumerable<string> IgnoredPropertyNames { get; set; }
protected Dictionary<string, Func<dynamic, string>> CustomPropertyDisplay { get; set; }
protected string IndexViewName { get; set; }
protected string EditorViewName { get; set; }
#endregion
#region public methods that render views
/// <summary>
/// Returns a ViewResult to display an "Index" view from which the user may select a row to edit (or view details that may be hidden)
/// </summary>
/// <returns></returns>
public virtual ActionResult Index()
{
ExpressFormsIndexViewModel model = new ExpressFormsIndexViewModel()
{
RecordType = typeof(T),
Title = IndexTitle == null ? this.GetType().Name : IndexTitle,
CustomIndexHeaders = CustomPropertyNames,
CustomPropertyDisplay = CustomPropertyDisplay,
Records = Exchange.Get().ToArray()
};
return View(IndexViewName, model);
}
/// <summary>
/// Returns a ViewResult to display an "Editor" form from which the user can insert or update data.
/// </summary>
/// <param name="id">the ID of the row to update; if null, the user may insert a new row.</param>
public virtual ActionResult Editor(TId id)
{
T record = (id == null) ? new T() : Exchange.Get(id);
bool isNew = id == null;
ExpressFormsEditorModel model = new ExpressFormsEditorModel()
{
Record = record,
IsNew = isNew,
Buttons = GetEditorButtons(isNew),
Inputs = GetEditorInputs(record)
};
return View(EditorViewName, model);
}
#endregion
#region methods that modify the data when called
/// <summary>
/// Postback is a single point of entry for the client to update server-side data.
/// This method may be called via either form post or AJAX as the page designates.
/// Declared virtual so that other developers may specify alternative implementation.
/// </summary>
/// <param name="record">the record that the user wants to insert/update/delete</param>
/// <param name="actionType">'INSERT', 'UPDATE', or 'DELETE'</param>
/// <param name="postType">'AJAX' or 'FORM' to tell the server how to respond</param>
/// <returns></returns>
[ValidateInput(false)]
public virtual ActionResult Postback(T record, string actionType, string postType)
{
// Check that a valid postType was specified
if (postType == null || !new []{"AJAX", "FORM"}.Contains(postType.ToUpper()))
throw new ArgumentOutOfRangeException("Must specify 'AJAX' or 'FORM' for postType, encountered: " + postType);
// Check that a valid action was specified.
if (actionType == null || !new[] { "INSERT", "UPDATE", "DELETE" }.Contains(actionType.ToUpper()))
throw new ArgumentOutOfRangeException("Must specify 'INSERT', 'UPDATE', or 'DELETE' for actionType, encountered: " + actionType);
OperationResult result = null;
switch (actionType.ToUpper())
{
case "INSERT":
result = Insert(record);
break;
case "UPDATE":
result = Update(record);
break;
case "DELETE":
// TODO: This depends on the ID field being called "Id". This needs to be fixed so that the ID is properly looked up.
TId id = (TId)(((dynamic)(record)).Id);
result = Delete(id);
break;
}
switch(postType.ToUpper())
{
case "AJAX":
return Json(result);
case "FORM":
return Redirect(Request.UrlReferrer.ToString());
default:
throw new InvalidOperationException();
}
} // End Postback
private OperationResult Insert(T record)
{
TId id = Exchange.Insert(record);
return new OperationResult()
{
Result = "Insert OK",
Id = id
};
}
private OperationResult Update(T record)
{
Exchange.Update(record);
return new OperationResult()
{
Result = "Update OK",
};
}
private OperationResult Delete(TId Id)
{
Exchange.Delete(Id);
return new OperationResult()
{
Result = "Delete OK",
};
}
private class OperationResult
{
public string Result { get; set; }
public TId Id { get; set; }
}
#endregion methods that modify the data when called
}
}
</code></pre>
<p>The generic Controller class is meant to be inherited by a class that specifies the type of data record. There are also a number of protected properties that can be modified in a derived class to modify the resulting <code>ViewModel</code> object, and thus make changes to what appears in the user's browser. The data is expected to be fetched using the <code>IExpressFormsExchange</code> interface. (An implementation for Entity Framework is provided.)</p>
<p>The generic Controller has three public methods: <code>Index</code>, <code>Editor</code>, and <code>Postback</code>. The first two provide views for the user to view and edit data. <code>Postback</code> allows the browser to post data to be updated and returns JSON.</p>
<p>There are examples that can be run bundled in the project. I plan to host them on my personal web site soon.</p>
<hr>
<p>This generic Controller class is the bedrock of the web development framework I'm developing, so I'm posting here for thoughts and ideas about what I've done right, and how I may improve it.</p>
<p>One more thing about the functionality. As you may notice, there is a default name for the views to be used. These names match files provided by the framework that provide "generic" views, but a developer using this controller can specify any view that uses the same <code>ViewModel</code> class.</p>
<p>Here is the generic Entity Framework Controller class.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using ExpressForms.Inputs;
namespace ExpressForms.Entities
{
public abstract class EntityController<TEntity> : ExpressForms.ExpressFormsController<TEntity, int?>
where TEntity : EntityObject, new()
{
public EntityController()
: base()
{
IgnoredPropertyNames = new[] { "EntityState", "EntityKey" };
}
protected void Initialize(ObjectContext objectContext)
{
EntityExchange<TEntity, int?> exchange = EntityExchangeFactory.GetEntityExchange<TEntity, int?>(objectContext);
Initialize(exchange);
}
}
}
</code></pre>
<p>The above Controller comes with the framework. The code below inherits this class and provides a data source:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ExpressForms;
using ExpressForms.Entities;
using System.Data.Objects.DataClasses;
namespace ExpressFormsExample.Controllers
{
/// <summary>
/// This abstract class inherits the EntityController class and provides the code to initialize the Controller
/// with the appropriate Entity Framework reference.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseController<T> : ExpressForms.Entities.EntityController<T>
where T : EntityObject, new()
{
protected ExpressFormsExampleEntities db;
public BaseController()
{
db = new ExpressFormsExampleEntities();
Initialize(db);
}
~BaseController()
{
db.Dispose();
}
}
}
</code></pre>
<p>With the above Controller class in the web project, the only thing that you need do to spin up CRUD screens for any record that comes from the data source is to write a Controller that inherits from the BaseController and specifies the generic parameter like so:</p>
<pre><code>using System.Web.Mvc;
namespace ExpressFormsExample.Controllers
{
public class Engineer0Controller : BaseController<Engineer>
{
}
}
</code></pre>
<p>That's a lot of code to post here; if you want to see more code, please visit the link to the project :-)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T19:49:13.707",
"Id": "46687",
"Score": "0",
"body": "It would help us if you gave a class that actually inherits from this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T22:39:45.343",
"Id": "46692",
"Score": "0",
"body": "I've added an example on my personal web page: http://danielsadventure.info/expressformsexample-0.5/ as well as some remarks: http://danielsadventure.info/ef/0introducingexpressforms.htm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-20T21:55:30.303",
"Id": "109909",
"Score": "0",
"body": "Sadly I don't have VS on my surface to test this, but I can't help but think there are much cleaner/easier ways of doing this. For example, you could have a single controller. Modify routing to always go to this single controller. On controller construction check the route values to determine which entity you are dealing with. You can then reflect the model properties and use ado to perform crud operations if not able t dynamically build up anorm context. Etc etc. End result would be, given your template project references some models, a single controller could provide all pages?"
}
] |
[
{
"body": "<p>This switch should be an if statement instead.</p>\n\n<blockquote>\n<pre><code> if (input == null) // we didn't get an input from GetCustomEditorInput\n {\n switch (property.PropertyType.Name)\n {\n case \"Boolean\":\n input = new ExpressFormsCheckBox()\n {\n FormName = FormName,\n InputName = inputName,\n Value = value,\n IsVisible = isVisible,\n };\n break;\n default:\n input = new ExpressFormsTextBox()\n {\n FormName = FormName,\n InputName = inputName,\n Value = value,\n IsVisible = isVisible\n };\n break;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>so it should look like this instead</p>\n\n<pre><code>if (input == null) // we didn't get an input from GetCustomEditorInput\n{\n if (property.PropertyType.Name == \"Boolean\") {\n input = new ExpressFormsCheckBox()\n {\n FormName = FormName,\n InputName = inputName,\n Value = value,\n IsVisible = isVisible,\n };\n } else {\n input = new ExpressFormsTextBox()\n {\n FormName = FormName,\n InputName = inputName,\n Value = value,\n IsVisible = isVisible\n };\n }\n}\n</code></pre>\n\n<p>I indented the multi-lined declaration so that it was more clear to what is going on there (more readable)</p>\n\n<hr>\n\n<p>Your else statements should match the if statement that they are attached to, an example from your code</p>\n\n<blockquote>\n<pre><code>protected virtual ExpressFormsInput GetCustomEditorInput(string inputName, string value, bool isVisible)\n{\n ExpressFormsInput customInput; \n\n // If there is a custom input with matching inputName, assign it the value of the input passed in and return it.\n if (CustomEditorInputs.Keys.Contains(inputName))\n {\n customInput = CustomEditorInputs[inputName];\n customInput.Value = value;\n return customInput;\n }\n // Otherwise, return null.\n else \n return null;\n}\n</code></pre>\n</blockquote>\n\n<p>I would write the else statement like this</p>\n\n<pre><code>} else {\n return null;\n}\n</code></pre>\n\n<p>there is no need for the comment on what the else statement is doing because it is transparent.</p>\n\n<p>you should declare variables with the least amount of scope possible, so you would create your <code>customInput</code> inside the if statement like this</p>\n\n<pre><code>protected virtual ExpressFormsInput GetCustomEditorInput(string inputName, string value, bool isVisible)\n{\n // If there is a custom input with matching inputName, assign it the value of the input passed in and return it.\n if (CustomEditorInputs.Keys.Contains(inputName))\n {\n ExpressFormsInput customInput;\n customInput = CustomEditorInputs[inputName];\n customInput.Value = value;\n return customInput;\n } else { \n return null;\n }\n}\n</code></pre>\n\n<p>I was a little confused here for a minute, you create another custom input when you already have a dictionary of custom editor inputs. I think that you should be assigning the custom input and returning the key to that custom input instead of actually returning a new custom input. doing it this way would help out with your <code>GetEditorInput</code> method greatly, it would allow you to return from inside the <code>if (input == null)</code> block, except you would take and write it something like this:</p>\n\n<pre><code>string inputName = property.Name;\nstring value = Convert.ToString(property.GetValue(record, null));\nbool isVisible = true;\nvar CustomEditorInputIndex = GetCustomEditorInput(inputName, value, isVisible) \n\nif (CustomEditorInputIndex == null) { input = null; }\n\nif (input == null) // we didn't get an input from GetCustomEditorInput\n{\n if (property.PropertyType.Name == \"Boolean\") {\n input = new ExpressFormsCheckBox()\n {\n FormName = FormName,\n InputName = inputName,\n Value = value,\n IsVisible = isVisible,\n };\n } else {\n input = new ExpressFormsTextBox()\n {\n FormName = FormName,\n InputName = inputName,\n Value = value,\n IsVisible = isVisible\n };\n }\n input.inputDisplayName = input.InputName;\n} else {\n input = CustomEditorInputs[CustomEditorInputIndex];\n input.inputDisplayName = CustomPropertyNames[input.InputName];\n}\nreturn input;\n</code></pre>\n\n<p>I changed the return of the <code>GetCustomEditorInput</code>, the name should be changed to something like <code>getCustomEditorInputKey</code> and <code>CustomEditorInputIndex</code> should be something like <code>customEditorInputKey</code></p>\n\n<p>You should probably do away with the <code>isVisble</code> parameter for that too because you don't use it. </p>\n\n<p>The <code>isVisible</code> variable in the <code>GetEditorInput</code> is not needed in my opinion, you use it twice and it isn't ever set anywhere but the declaration, the argument could be made that it is a magic value so I will leave it there. I haven't rewritten <code>GetCustomEditorInput</code> for you, I will let you have that fun.</p>\n\n<hr>\n\n<p>@BenVlodgi mentioned the use of ternary statements to make this a little cleaner</p>\n\n<p>so what I did was take the nested if statement and turn it into a ternary statement, I am sure that it doesn't make much of a difference to the compiler but makes it a little easier to read, in my opinion.</p>\n\n<pre><code>if (input == null)\n{\n input = property.PropertyType.Name == \"Boolean\" \n ? new ExpressFormsCheckBox() {FormName = FormName, InputName = inputName, Value = value, IsVisible = isVisible} \n : new ExpressFormsTextBox() {FormName = FormName, InputName = inputName, Value = value, IsVisible = isVisible} ; \n} else {\n input = CustomEditorInputs[GetCustomEditorInput(inputName, value)];\n input.inputDisplayName = CustomPropertyNames[input.InputName];\n}\nreturn input;\n</code></pre>\n\n<hr>\n\n<p>In an effort to fix my mistakes in the above code I re-wrote the code using the <code>customEditorInputKey</code> and ternary statements.\nI switched things around if it's not null it will retrieve the actual <code>input</code> object otherwise it will create new inputs (these should be added to the <code>CustomEditorInputs</code> list/collection/dictonary/{whatever you are going to use} )</p>\n\n<pre><code>string inputName = property.Name;\nstring value = Convert.ToString(property.GetValue(record, null));\nbool isVisible = true;\nvar customEditorInputKey = GetCustomEditorInput(inputName, value) \n\nif (customEditorInputKey != null) { \n input = CustomEditorInputs[customEditorInputKey];\n input.inputDisplayName = CustomPropertyNames[input.InputName];\n\n} else {\n input = property.PropertyType.Name == \"Boolean\" \n ? new ExpressFormsCheckBox() {FormName = FormName, InputName = inputName, Value = value, IsVisible = isVisible} \n : new ExpressFormsTextBox() {FormName = FormName, InputName = inputName, Value = value, IsVisible = isVisible} ; \n}\nreturn input;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T16:50:04.613",
"Id": "60810",
"ParentId": "29502",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T18:11:13.060",
"Id": "29502",
"Score": "11",
"Tags": [
"c#",
".net",
"asp.net",
"asp.net-mvc-4",
"controller"
],
"Title": "Generic ASP.NET MVC controller that generates many pages"
}
|
29502
|
<p>I have a form that I'm turning into a string value for an email, but the string value that I turn it into seems very complicated, plus I believe this way takes up a lot of memory and is somewhat slow as well. Is there any other way to make a NSString with many arguments besides using <code>[NSString stringWithFormat:]</code>?</p>
<p>Here is what I'm doing now:</p>
<pre><code>strMessage = [NSString stringWithFormat:@"%@\n\n%@\n\n%@\n%@\n%@, Il\n%@\nPhone: %@\nEmail: %@", detailsText.text, nameText.text, addrLn1Text.text, addrLn2Text.text, cityAddrText.text, zipAddrText.text, phoneNumberText.text, emailText.text];
</code></pre>
|
[] |
[
{
"body": "<p>You could use <code>NSMutableString</code>. It has <code>appendString</code> method which you could use to create string by appending other strings.\nFor example: </p>\n\n<pre><code>NSMutableString *mutableString = [NSMutableString stringWithFormat:@\"%@\", someString];\n[mutableString appendString:otherString];\n// and so on...\n</code></pre>\n\n<p>NSMutableString also has the <code>stringByAppendingString</code> method, but <code>appendString</code> method is more memory friendly.</p>\n\n<p>You can also do this:</p>\n\n<pre><code>NSString *exampleString = @\"Multiple \" @\"string \" @\"example\";\n</code></pre>\n\n<p>NSString can even be built using NSArray:</p>\n\n<pre><code>NSArray *stringArray = [NSArray arrayWithObjects:@\"Another\", @\"string\", @\"example\", nil];\nNSLog(@\"%@\",[pathArray componentsJoinedByString:@\"\\n\"]);\n// Log wold look like\n// Another\n// string\n// example\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T15:47:43.510",
"Id": "46835",
"Score": "0",
"body": "I'm a bit confused on the second example. What's the difference between that and concatenation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T07:36:28.427",
"Id": "46867",
"Score": "1",
"body": "Second example just a technique to break up long literal strings within your code. This way your code could look cleaner and more readable but using this technique you can only concatenate string literals and cannot use string variables and methods like stringWithFormat:."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T08:53:39.410",
"Id": "29581",
"ParentId": "29503",
"Score": "4"
}
},
{
"body": "<p>It's straightforward to build a named substitution system that can be easily applied to strings loaded either in code or in files. The following <code>NSString</code> category allows you to specify named substitutions in a dictionary, such that any occurrence of the string <code>${toSubstitute}</code> are replaced by the object corresponding to <code>toSubstitue</code>'s object in a dictionary.</p>\n\n<p>NSString+CVTemplateAdditions.h:</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface NSString (CVTemplateAdditions)\n\n- (NSString *)cvStringByApplyingSubstitutions:(NSDictionary *)substitutions;\n\n@end\n</code></pre>\n\n<p>NSString+CVTemplateAdditions.m:</p>\n\n<pre><code>#import \"NSString+CVTemplateAdditions.h\"\n\n@implementation NSString (CVTemplateAdditions)\n\n- (NSString *)cvStringByApplyingSubstitutions:(NSDictionary *)substitutions\n{\n NSMutableString *toReturn = [self mutableCopy];\n [substitutions enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {\n NSString *stringToSub = [NSString stringWithFormat:@\"${%@}\",key];\n [toReturn replaceOccurrencesOfString:stringToSub withString:obj options:NSLiteralSearch range:NSMakeRange(0, [toReturn length])];\n }];\n return [toReturn copy];\n}\n\n@end\n</code></pre>\n\n<p>We could load your text into a file, like so:</p>\n\n<p>Template.txt:</p>\n\n<pre><code>${detailsText}\n\n${nameText}\n\n${addressLineOneText}\n${addressLineTwoText}\n${cityAddressText}, Il\n${zipAddressText}\nPhone: ${phoneText}\nEmail: ${emailText}\n</code></pre>\n\n<p>And then apply substitutions like:</p>\n\n<pre><code>NSDictionary *substitutions = @{\n @\"detailsText\": @\"details text here\",\n @\"nameText\": @\"name text here\",\n @\"addressLineOneText\": @\"address line one text here\",\n @\"addressLineTwoText\": @\"address line two text here\",\n @\"cityAddressText\": @\"city address text here\",\n @\"zipAddressText\": @\"zip address text here\",\n @\"phoneText\": @\"phone text here\",\n @\"emailText\": @\"email text here\"\n };\nNSString *actual = [input cvStringByApplyingSubstitutions:substitutions];\n</code></pre>\n\n<p>In the above code, <code>actual</code> evaluates to the following string:</p>\n\n<pre><code>details text here\n\nname text here\n\naddress line one text here\naddress line two text here\ncity address text here, Il\nzip address text here\nPhone: phone text here\nEmail: email text here\n</code></pre>\n\n<p>The following <code>SenTestCase</code> subclass and input files demonstrate the functionality further:</p>\n\n<p>TemplatingEngineTests.h:</p>\n\n<pre><code>#import <SenTestingKit/SenTestingKit.h>\n\n@interface TemplatingEngineTests : SenTestCase\n\n@end\n</code></pre>\n\n<p>TemplatingEngineTests.m:</p>\n\n<pre><code>#import \"TemplatingEngineTests.h\"\n#import \"NSString+CVTemplateAdditions.h\"\n\n@implementation TemplatingEngineTests\n\n- (void)setUp\n{\n [super setUp];\n\n // Set-up code here.\n}\n\n- (void)tearDown\n{\n // Tear-down code here.\n\n [super tearDown];\n}\n\n- (void)testApplyingSubstitutionsResultsInExpectedString\n{\n NSString *expected = [self expectedString];\n NSString *input = [self templateString];\n NSDictionary *substitutions = @{\n @\"detailsText\": @\"details text here\",\n @\"nameText\": @\"name text here\",\n @\"addressLineOneText\": @\"address line one text here\",\n @\"addressLineTwoText\": @\"address line two text here\",\n @\"cityAddressText\": @\"city address text here\",\n @\"zipAddressText\": @\"zip address text here\",\n @\"phoneText\": @\"phone text here\",\n @\"emailText\": @\"email text here\"\n };\n NSString *actual = [input cvStringByApplyingSubstitutions:substitutions];\n STAssertEqualObjects(actual, expected, nil);\n}\n\n- (void)testApplyingNilSubstitutionsReturnsStringEqualToItself\n{\n NSString *testString = [self templateString];\n NSString *result = [testString cvStringByApplyingSubstitutions:nil];\n STAssertEqualObjects(result, testString, nil);\n}\n\n- (void)testNonTemplatedStringReturnsStringEqualToItself\n{\n NSString *testString = [self nonTemplateString];\n NSString *result = [testString cvStringByApplyingSubstitutions:@{@\"key\": @\"sub\"}];\n STAssertEqualObjects(result, testString, nil);\n}\n\n- (NSString *)nonTemplateString\n{\n return [self stringFromFile:@\"NoTemplate\"];\n}\n\n- (NSString *)templateString\n{\n return [self stringFromFile:@\"Template\"];\n}\n\n- (NSString *)expectedString\n{\n return [self stringFromFile:@\"TemplateExpected\"];\n}\n\n- (NSString *)stringFromFile:(NSString *)name\n{\n NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:name ofType:@\"txt\"];\n NSString *testString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];\n return testString;\n}\n\n@end\n</code></pre>\n\n<p>Template.txt:</p>\n\n<pre><code>${detailsText}\n\n${nameText}\n\n${addressLineOneText}\n${addressLineTwoText}\n${cityAddressText}, Il\n${zipAddressText}\nPhone: ${phoneText}\nEmail: ${emailText}\n</code></pre>\n\n<p>TemplateExpected.txt:</p>\n\n<pre><code>details text here\n\nname text here\n\naddress line one text here\naddress line two text here\ncity address text here, Il\nzip address text here\nPhone: phone text here\nEmail: email text here\n</code></pre>\n\n<p>NoTemplate.txt:</p>\n\n<pre><code>This is an email with no template parameters.\n\nIt's quite boring.\n\nSigh.\n\n\nTELL ALL YOUR FRIENDS HOW AWESOME OUR APP IS!!!\n</code></pre>\n\n<p>Hopefully you agree that it becomes much more manageable and readable when you can load complex formats from text files and refer to them by name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T18:29:17.503",
"Id": "29622",
"ParentId": "29503",
"Score": "3"
}
},
{
"body": "<p>Since you have a concept of line, an array with one entry per line would be a clear representation:</p>\n\n<pre><code>NSArray *lines = @[detailsText.text,\n @\"\",\n nameText.text,\n @\"\",\n addrLn1Text.text,\n addrLn2Text.text,\n [cityAddrText.text stringByAppendingString:@\", Il\"],\n zipAddrText.text,\n [@\"Phone: \" stringByAppendingString:phoneNumberText.text],\n [@\"Email: \" stringByAppendingString:emailText.text]];\n\nNSString *strMessage = [lines componentsJoinedByString:@\"\\n\"];\n</code></pre>\n\n<p>I wouldn't care about optimizing run time when you're sending an email.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-06T22:16:29.597",
"Id": "30896",
"ParentId": "29503",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29622",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T18:52:21.987",
"Id": "29503",
"Score": "2",
"Tags": [
"strings",
"objective-c"
],
"Title": "Is there a better way of making an NSString with many argument values?"
}
|
29503
|
<p>I wrote this <code>with-input-from-pipe</code> function for Guile. I’m not that comfortable with <code>dynamic-wind</code> or <code>set-current-input-port</code>, so I’d appreciate any critiques.</p>
<pre><code>(use-modules (ice-9 popen)
(srfi srfi-26))
(define (with-input-from-pipe command thunk)
(let ((old (current-input-port))
(pipe (open-input-pipe command)))
(dynamic-wind
(cute set-current-input-port pipe)
thunk
(lambda ()
(set-current-input-port old)
(close-pipe pipe)))))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T19:50:36.157",
"Id": "29505",
"Score": "2",
"Tags": [
"scheme"
],
"Title": "A with-input-from-pipe for Guile"
}
|
29505
|
<p>The goal is to have a <code>DataGrid</code> of comboboxes, 10 rows, 3 columns.</p>
<p>Here's the XAML to create said grid:</p>
<pre class="lang-xaml prettyprint-override"><code><DataGrid Name="grid1"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Product">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="2"
FontSize="25"
MinWidth="70"
ItemsSource="{Binding Product}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Amount">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="2"
FontSize="25"
MinWidth="70"
ItemsSource="{Binding Amount}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Units">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="2"
FontSize="25"
MinWidth="70"
ItemsSource="{Binding Units}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</code></pre>
<p>Here's the code behind for the binding:</p>
<pre class="lang-cs prettyprint-override"><code>private void SetGrid()
{
var materialList = new List<MudMaterial>();
var newMaterial = new MudMaterial();
for (var i = 0; i < 10; i++)
{
materialList.Add(newMaterial);
}
grid1.ItemsSource = materialList;
}
</code></pre>
<p>The <code>MudMaterial</code> Class:</p>
<pre class="lang-cs prettyprint-override"><code>class MudMaterial
{
public ObservableCollection<string> Product { get; set; }
public ObservableCollection<string> Units { get; set; }
public ObservableCollection<string> Amount { get; set; }
public MudMaterial()
{
Product = new ObservableCollection<string>() { " ",
"Gel",
"Barrite",
"Detergent",
"Soap",
"X Gel",
"Bentonite",};
Units = new ObservableCollection<string>() {" ",
"20 lb bag",
"40 lb bag",
"50 lb bag",
"80 lb bag",
"1 gal",
"2 gal",
"3 gal",};
Amount = new ObservableCollection<string>() {" ",
"1",
"2",
"3",
"4",
"5",
"6",};
}
}
</code></pre>
<p>The actual length of the <code>ObservableCOllection<string></code>s ranges from 10-70 items.</p>
<p>Now, aside from a few quirks(extra empty row at the end, extra empty column in the beginning), this works. However, I feel dirty having come up with this. Surely there must be a more efficient way to do this?</p>
<p>Here's a picture of the grid:</p>
<p><img src="https://i.stack.imgur.com/R1TAl.png" alt="enter image description here"></p>
<p>I'm using a datagrid because it seemed easier to do than anything else. Every box under "Product" has the same exact items, every box under "Amount" has the same exact items, and every box under "Units" has the exact same items. Essentially, I'm just looking for a better way, if it exists, to populate those boxes than what I'm already doing.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T05:46:49.380",
"Id": "46701",
"Score": "1",
"body": "What is your problem exactly? Please add more context. Is there a reason, you use strings? Is there a reason you use observable collections? Are those collections supposed to be unique per item? Stuff like that. Its hard to tell from your code, what behaviour you are trying to achieve, so its hard to give you a proper advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T12:35:34.027",
"Id": "46710",
"Score": "0",
"body": "@Nik: There's no \"problem\" per se. If there was a problem, I'd have posted this on SO. This works the way I intend. I'm just looking for a better way to do this. Also, the first line of my post shows what I'm trying to achieve."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T13:17:10.017",
"Id": "46711",
"Score": "0",
"body": "do you have a viewable sample of what this looks like? I am not sure why you would use a Datagrid instead of a Table, if I could see it in action it might be more clear to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T14:12:30.377",
"Id": "46712",
"Score": "1",
"body": "@MyCodeSucks, if your first line was enough to understand your intent, i would not ask, would I? Its not like i'm asking for fun. :) As it is, all i can say for sure is: your design is wrong. But its hard to tell, how your code can be altered without knowing how are you going to use this grid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T14:41:29.767",
"Id": "46716",
"Score": "0",
"body": "what is this application supposed to do? does it keep track of the supplies in a warehouse, keep track of supplies being used on a job site? if it were something like that then i would suggest only having one row, then have to click submit/save, then give the user acknowledgment that the row has been saved. I am pretty sure that a Datagrid doesn't suit the application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T14:52:49.027",
"Id": "46717",
"Score": "2",
"body": "@Malachi: It doesn't matter what it does. I'm asking if this is the most effective way to populate them, not store them. And if 1 row were good enough, I wouldn't be trying to do 10. My boss wants 10."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T17:02:44.220",
"Id": "46719",
"Score": "0",
"body": "This would be so much easier using WinForms :)"
}
] |
[
{
"body": "<p>If your items in the ComboBox are static, you don't need binding at all.</p>\n\n<pre><code><DataGridTemplateColumn Header=\"Product\">\n <DataGridTemplateColumn.CellTemplate>\n <DataTemplate>\n <ComboBox>\n <ComboBoxItem>Grapes</ComboBoxItem>\n <ComboBoxItem>Apples</ComboBoxItem>\n <ComboBoxItem>Oranges</ComboBoxItem>\n </ComboBox>\n </DataTemplate>\n </DataGridTemplateColumn.CellTemplate>\n</DataGridTemplateColumn>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T19:42:50.150",
"Id": "29529",
"ParentId": "29507",
"Score": "3"
}
},
{
"body": "<p>Alright. This is how your code can be improved in my opinion:</p>\n\n<p>1) You do not need observable collections for <code>ComboBox</code> itemsources. It is used to support changes to collection, and you have none. In your case, a simple array or <code>List</code> will do.</p>\n\n<p>2) You should try to avoid using string arrays for storing entities which are not exactly strings. You should avoid hardcoding 70 string values as well. If you need to populate such array - this is the first sign that you need a database. You will be able to add new Products without recompiling your code, populating arrays will require a single query, you will operate using Product ID's or some complex object, etc, etc. There are many advantages. <code>Amount</code> can be made a <code>List<int></code> and can be populated in a simple loop (you can implement <code>IValueConverter</code> to add an empty row, if you need one). <code>Units</code> should be a list of some objects, representing volume.</p>\n\n<p>3) As for UI, you can improve your code using standart MVVM practices. Instead of setting up bindings in code behind, set your <code>UserControl.DataContext</code> to some viewmodel and use data binding.</p>\n\n<p>ViewModel example (i left strings intact for simplicity):</p>\n\n<pre><code>class MyViewModel\n{\n public IList<string> Products { get; private set; }\n public IList<string> Amounts { get; private set; }\n public IList<string> Units { get; private set; }\n\n public ObservableCollection<MudMaterial> Materials { get; private set; } \n\n public MyViewModel()\n {\n //populate above collections\n }\n}\n\nclass MudMaterial\n{\n public string Product { get; set; }\n public string Unit { get; set; }\n public string Amount { get; set; }\n}\n</code></pre>\n\n<p>xaml example:</p>\n\n<pre><code><DataGrid ItemsSource=\"{Binding Materials}\" AutoGenerateColumns=\"False\">\n <DataGrid.Resources>\n <Style TargetType=\"ComboBox\" x:Key=\"products\">\n <Setter Property=\"ItemsSource\" Value=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=DataContext.Products}\" />\n </Style>\n </DataGrid.Resources>\n <DataGrid.Columns>\n <DataGridComboBoxColumn\n Header=\"Product\" \n MinWidth=\"70\" \n ElementStyle=\"{StaticResource products}\"\n EditingElementStyle=\"{StaticResource products}\"\n SelectedItemBinding=\"{Binding Product}\"/>\n</code></pre>\n\n<p>Dont forget to set DataContext by calling <code>DataContext = new MyViewModel();</code> in constructor in code-behind or by setting it in xaml.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T06:40:17.593",
"Id": "29546",
"ParentId": "29507",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T21:09:14.687",
"Id": "29507",
"Score": "4",
"Tags": [
"c#",
"wpf"
],
"Title": "Populating a datagrid of comboboxes"
}
|
29507
|
<p>I'm working on an old PHP website, and NetBeans is complaining about an uninitialized variable. I'm seeing some code like this:</p>
<pre><code>$app->soapAPIVersion($apiVersion);
$_SESSION['apiVersion'] = $apiVersion;
</code></pre>
<p>The function looks something like this:</p>
<pre><code>function soapAPIVersion(&$apiVersion)
{
$apiVersion = '';
$result = false;
$soapResult = $client->call('getAPIVersion', array('sessionKey' => $sessionKey), $url);
if (is_string($soapResult))
{
$apiVersion = $soapResult;
$result = true;
}
return $result;
}
</code></pre>
<p>I believe it's using this line to initialize the <code>$apiVersion</code> variable:</p>
<pre><code>$app->soapAPIVersion($apiVersion);
</code></pre>
<p>For better coding practice, should that really be this:</p>
<pre><code>$apiVersion = '';
$app->soapAPIVersion($apiVersion);
</code></pre>
<p>Or is it a valid trick?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:54:17.147",
"Id": "82548",
"Score": "0",
"body": "While I agree with the advice to refactor and avoid the reference, *sometimes* you have no choice (e.g. the built-in function `preg_match`). Yes, this is a [bug in NetBeans](https://netbeans.org/bugzilla/show_bug.cgi?id=242520), and there's no reason to initialize `$apiVersion` before calling the function. You will only get a warning if you *read* its value before initializing it."
}
] |
[
{
"body": "<ol>\n<li><p><em>Clean Code, Chapter 3. Functions</em> has some guidance:</p>\n\n<blockquote>\n <p><strong>Have No Side Effects</strong></p>\n \n <p>Side effects are lies. Your function promises to do one thing, but it also does other hidden\n things.</p>\n \n <p>[...]</p>\n \n <p>Anything that forces you to check the function signature is equivalent to a double-take. It’s\n a cognitive break and should be avoided.</p>\n</blockquote>\n\n<p>The side effect here is that the function changes the argument. A more readable approach would be returning the API version (instead of true/false) or throwing an exception in case of errors.</p></li>\n<li>\n\n<pre><code>$app->soapAPIVersion($apiVersion);\n$_SESSION['apiVersion'] = $apiVersion;\n</code></pre>\n\n<p>Note that the code should check the return value of <code>soapAPIVersion</code> and handle <code>false</code> somehow.</p></li>\n<li><p>The <code>soapAPIVersion</code> name is unclear. What does it do with the API version? From <em>Clean Code, Chapter 2: Meaningful Names</em>:</p>\n\n<blockquote>\n <p><strong>Method Names</strong></p>\n \n <p>Methods should have verb or verb phrase names like postPayment, deletePage, or save.\n Accessors, mutators, and predicates should be named for their value and prefixed with get,\n set, and is according to the javabean standard.</p>\n</blockquote>\n\n<p>I'd rename it to <code>getApiVersion</code> or <code>fetchApiVersion</code>. </p>\n\n<p>Note the camelCase too which is usually easier to read. From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T01:29:24.133",
"Id": "29514",
"ParentId": "29511",
"Score": "5"
}
},
{
"body": "<p>With all do respect, this code really did hurt. Netbeans is complaining, because the function <code>soapAPIVersion</code> expects a <em>reference</em> to a variable. You're passing an undeclared, and uninitialized variable to the function. Sort of like a void pointer/null-pointer thing.<br/>\nIt's not really a big deal, but I cannot, for the life of me, get <em>why</em> this function uses a reference as an argument. I think it better to change it to:</p>\n\n<pre><code>function soapAPIVersion()\n{\n $soapResult = $client->call('getAPIVersion', array('sessionKey' => $sessionKey), $url);\n if (is_string($soapResult))\n {\n return $soapResult;\n }\n //implicitly return null, or throw exception\n}\n</code></pre>\n\n<p>And call it like so:</p>\n\n<pre><code>$apiVersion = $app->soapAPIVersion();\nif ($apiVersion === null)\n{\n throw new RuntimeException('unable to get the API version');\n}\n$_SESSION['apiVersion'] = $apiVersion;\n</code></pre>\n\n<p>Bottom line: only pass by reference if you need your function to do 2 things <em>at the same time</em>, and you can't split those two things over 2 functions. situations are <em>Very</em> rare. Since PHP5, I've only had to use a reference argument 5~10 times, I think, so avoid, if at all possible</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T21:17:33.393",
"Id": "46725",
"Score": "1",
"body": "Excellent, fully agree, thankyou! Unfortunately what you saw was just the very tip of the iceberg. This code base has more of the same and even worse examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T07:03:17.670",
"Id": "46738",
"Score": "0",
"body": "@user2640336: In that case, even though I'm not religious, I'll pray for your sanity :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T08:45:01.040",
"Id": "29517",
"ParentId": "29511",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29517",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T23:25:06.957",
"Id": "29511",
"Score": "5",
"Tags": [
"php",
"php5"
],
"Title": "Initializing a variable with a function reference (PHP)"
}
|
29511
|
<p>I am hoping someone can help me attain better performance and better ways of writing this script. Any help would be awesome!</p>
<p><strong>Overall Goal:</strong> I have a dropdown that allows someone to select an option from it. It will add that record to the table below, and then the option will be removed. If they delete that row in the table, it then adds that option back to the dropdown.</p>
<pre><code>$(function() {
$('#addResource').on('change', function(){
var $selectBox = $(this),
oID = $selectBox.val(),
oText = $selectBox.children(':selected').text(),
url = '/admin/contacts/json',
oSize = $selectBox.children('option').size()
noResources = '<tr class="no-resources"><td colspan="5">No Resources.</td></tr>';
//if select box out of options lets hide it
if((oSize-1) == 1) {
$selectBox.hide().parent().append('<div class="alert alert-info">No More Contacts Available</div>');
}
// lets remove the selected option
$selectBox.children(':selected').remove();
$selectBox.children(':first').attr('selected','selected');
// lets get the contact to add to the table
$.post(url, { id: oID },function(data){
var tableRow = "<tr class='resource_"+data.id+"'><input type='hidden' value='"+data.id+"' name='resouces[]'><td class='name'>"+data.name+"</td><td>"+data.phone+"</td><td>"+data.email+"</td><td>$"+data.rate+"</td><td><a href='#' title='Remove Resource' class='remove_"+data.id+"' data-id='"+data.id+"'><i class='icon-trash'></i></a></td></tr>",
table = $("#resourcesTable tbody");
table.find('tr.no-resources').remove();
table.append(tableRow);
cssClass = '.remove_'+data.id;
table.on('click',cssClass, function(e){
var $trash = $(this),
rowId = $trash.attr('data-id');
// open confirm modal window
modalMsg('Are you sure you wish to delete '+data.name+' as a resource?','',function(result){
// remove deleted row
$(".resource_"+rowId).fadeOut(function(){
var size = table.find('tr').size(),
name = $(this).find('.name').text();
$selectBox.append("<option value='"+rowId+"'>"+name+"</option>"); // add option back to dropdown
$(this).remove(); // remove the table row when deleted
if((size-1) == 0 ){ // if no more talbe rows put back no resources message
table.append(noResources);
}
});
// need to
})
e.preventDefault();
});
// need to add input fields to post to save to database
}, "json" );
}); // end on change
});
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Your indentation is a little funky. I can understand not indenting after <code>$(function () {</code> (though I would do so myself), but the <code>change</code> handler's body really should be indented</p></li>\n<li><p>You've got everything in one function, though it'd probably be more readable to separate things. For instance, <code>addRecord</code>, <code>removeRecord</code> (with further specialized functions for adding/removing a row, and adding/removing an option.</p></li>\n<li><p>Use jQuery to build the HTML; don't type it out as a long string. Doing so is error-prone</p></li>\n<li><p>I don't know how <code>modalMsg</code> works, but I imagine that the <code>result</code> you receive in the callback can have at least 2 different values. What happens if the user says \"No, I <em>don't</em> want to delete that resource\"? It looks like it gets removed anyway...<br>\nMoreover, the wording of that modal seems a bit severe considering you can just add the resource back in a moment later. The word \"Delete\" can scare the pants of people.</p></li>\n<li><p>I have to wonder why your ajax call is a POST. I'm guessing you're updating something server-side when a record is added to the table, but in that case, shouldn't there also be a POST or DELETE call when the user removes something from the table?</p></li>\n<li><p>You don't have any error handling, so if the ajax call should fail for any reason, the option is already gone, and the record isn't in the table either.</p></li>\n<li><p>It'd be easy to add a little bit of caching, just in case someone changes their mind twice (adds, removes, adds again)</p></li>\n<li><p>The hidden input should be in a <code>td</code>, rather than floating around inside a <code>tr</code>.</p></li>\n<li><p>There's no need to create unique class names for every row. The idea of class names is that they can be applied to several elements. If you want to uniquely identify something, use an ID attribute - it's what they're for. However, in this case, we don't even need that, as we can use closures instead.</p></li>\n<li><p>Rather than add and remove the <code>no-resources</code> row and the \"No more contacts available\" alert, it'd be easier to have these in the HTML already, and simply show/hide them as needed. The less HTML you have to build in JS, the better.</p></li>\n<li><p>There's the issue of sorting the records, too. Not so much in the table, but rather in the dropdown. If I were to select the 3rd option out of, say, 10, and then change my mind, I'd expect it to behave like \"undo\": That's the option is back in the dropdown, as the 3rd option. But tackling this is a bit beyond the scope of this review.</p></li>\n</ul>\n\n<p>I'd do something like this (assuming that the 1st option - the do-nothing option - has its <code>value</code> attribute set to an empty string). I haven't looked at error handling because I don't know how you'd prefer to do that.</p>\n\n<p>Haven't tested this, but the general idea should be apparent</p>\n\n<pre><code>$(function () {\n var dropdown = $(\"#addResource\"),\n table = $(\"#resourcesTable tbody\"),\n noResourcesRow = table.find(\".no-resources\"),\n noContactsAlert = dropdown.parent().find(\".alert\"),\n url = \"/admin/contacts/json\",\n recordsCache = {};\n\n function fetchRecord(id) {\n if(recordsCache[id]) {\n addTableRow(records[id]); // use cache if possible\n } else {\n $.post(url, {id: id}, function (record) {\n recordsCache[id] = record; // add to cache\n addTableRow(record);\n });\n }\n }\n\n function addTableRow(record) {\n var row = $(\"<tr></tr>\").addClass(\"resource\").data(\"record\", record),\n removeLink = $(\"<a></a>\", {\n \"href\": \"#\",\n \"class\": \"remove-resource\",\n \"title\": \"Remove resource\"\n }).append($(\"<i></i>\", { \"class\": \"icon-trash\" }));\n\n row.append($(\"<td></td>\").text(record.name)).append($(\"<input></input>\", {\n type: \"hidden\",\n value: record.id\n }));\n\n // this could be done with a loop too\n row.append($(\"<td></td>\").text(record.phone));\n row.append($(\"<td></td>\").text(record.email));\n row.append($(\"<td></td>\").text(record.rate));\n\n row.append($(\"<td></td>\").append(removeLink));\n\n removeLink.on(\"click\", function (event) {\n event.preventDefault();\n modalMsg(\"Are you sure you wish to remove \" + record.name + \" as a resource?\", \"\", function (result) {\n // FIXME: Add proper checking of the result\n if(...) {\n removeTableRow();\n }\n });\n });\n\n table.append(row);\n }\n\n function removeTableRow(row) {\n var record = row.data(\"record\");\n row.fadeOut(function () {\n row.remove();\n if(!table.children.length) {\n noResourcesRow.show(); // or fadeIn() maybe\n }\n addOption(record.id, record.name); // add the option back in\n }\n }\n\n function addOption(id, name) {\n dropdown.append($(\"<option></option>\", { value: id }).text(name));\n noContactsAlert.hide();\n dropdown.show();\n }\n\n function removeOption(option) {\n option.remove();\n if(dropdown.children.length === 1) { // includes the do-nothing option\n dropdown.hide();\n noContactsAlert.show();\n }\n }\n\n dropdown.on(\"change\", function (event) {\n if(!this.value) {\n return; // ignore event if the do-nothing option is selected\n }\n\n fetchRecord(this.value);\n removeOption(dropdown.children(\":selected\"));\n this.value = \"\"; // set the do-nothing option\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T00:40:10.153",
"Id": "61040",
"ParentId": "29512",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T00:01:48.993",
"Id": "29512",
"Score": "2",
"Tags": [
"javascript",
"optimization",
"jquery"
],
"Title": "Recording options selected from dropdown menu"
}
|
29512
|
<p>How could this scala code be made more concise and/or idiomatic? Do I need to define each functions as a <code>val</code> in order to pass them as values, or is there a shorthand for this? Also looking for feedback on the <code>disenvowel</code> function.</p>
<pre><code>// See: http://nurkiewicz.blogspot.com/2012/04/secret-powers-of-foldleft-in-scala.html
def transformString(s: String, fns: List[Function1[String,String]]) :String =
(s /: fns) { (s: String, f: Function1[String,String]) => f apply s }
val toUpper = (s: String) => s.toUpperCase
val reverse = (s: String) => s.reverse
val disenvowel = (s: String) => s filterNot { Set('a','e','i','o','u') contains _ }
// scala> transformString("blah",List(disenvowel))
// res175: String = blh
// scala> transformString("blah",List(disenvowel, toUpper))
// res176: String = BLH
// scala> transformString("blah",List(disenvowel, toUpper, reverse))
// res177: String = HLB
</code></pre>
|
[] |
[
{
"body": "<p>Depending on the function definition, you can do this inline using a function literal (which is basically a lambda):</p>\n\n<pre><code>transformString(\"blah\", List(s => s.toUpperCase, s => s.reverse))\n</code></pre>\n\n<p>In fact, you can make this even more concise using <code>_</code>:</p>\n\n<pre><code>transformString(\"blah\", List(_.toUpperCase, _.reverse))\n</code></pre>\n\n<p>For larger functions like <code>disenvowel</code> (which I'd probably call <code>removeVowels</code>), it'd likely be better to define it as a separate function, since it's likely less readable as a function literal. The implementation itself looks fine to me. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T12:57:44.260",
"Id": "29519",
"ParentId": "29516",
"Score": "1"
}
},
{
"body": "<p>If I might chime in briefly, it all looks fine, any modifications here are mostly a matter of taste and personal preference; for example, I'd make it a curried function with varargs:</p>\n\n<pre><code>def transformString(s : String)(functions : String => String*) = \n functions.foldLeft(s) { (str, fun) => fun(str) }\n</code></pre>\n\n<p>And you don't need to define functions as literals, for example:</p>\n\n<pre><code>scala> def toUpper(s : String) = s.toUpperCase\ntoUpper: (s: String)String\n\nscala> def reverse(s : String) = s.reverse\nreverse: (s: String)String\n</code></pre>\n\n<p>And then, using the slightly modified version above:</p>\n\n<pre><code>scala> transformString(\"blah\")(toUpper, reverse)\nres3: String = HALB\n</code></pre>\n\n<p>Of course, you can always use the literal, too:</p>\n\n<pre><code>scala> val reverse2 = (s : String) => s.reverse\nreverse2: String => String = <function1>\n\nscala> transformString(\"blah\")(reverse2)\nres4: String = halb\n</code></pre>\n\n<p>Or even provide the lambda in-place:</p>\n\n<pre><code>scala> transformString(\"blah\")(_ + \"1\", _.reverse)\nres9: String = 1halb\n</code></pre>\n\n<p>IMO, varargs here work nicely, and you can transform any sequence/collection into varargs by <code>:_*</code>; there are a few differences, though:</p>\n\n<ol>\n<li><code>def</code> methods have to be partially applied in the list (e.g. : <code>toUpper_</code> below)</li>\n<li>Underscore shorthand syntax won't work</li>\n</ol>\n\n<p>so:</p>\n\n<pre><code>scala> transformString(\"blah \")(List(reverse2, (s : String) => s + \"12\", toUpper_):_*)\nres21: String = \" HALB12\"\n</code></pre>\n\n<p>[EDIT for the comments]</p>\n\n<p>1 & 2. Oh, there is a difference. You can easily make a function partially applied if it's curried, not so much if it just takes in arguments. Also, you <em>can</em> make shorthand underscore syntax work <em>after</em> applying the function partially:</p>\n\n<pre><code>scala> def blahArg = transformString(\"blah\")_\nblahArg: Seq[String => String] => String\n</code></pre>\n\n<p>Note the trailing underscore and the return type: a function (with lower arity). Now you can pass that function somewhere else where the second argument can be supplied. You can't do that when taking in both arguments at once. That also means that your second parameter changed from <code>varargs</code> to <code>Seq</code>, which - in turn - means you explicitly have to pass a <code>Seq</code>, <code>List</code> or something similar:</p>\n\n<pre><code>scala> blahArg(List(_.reverse))\nres10: String = halb\n</code></pre>\n\n<p>3.Removing vowels looks fine :) If that's contained inside an <code>object</code>, you can move the <code>Set</code> initialization to the object level, so it's only initialized once instead of on every function call, but that's nitpicking.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T11:35:47.900",
"Id": "46746",
"Score": "0",
"body": "So there's no solution for `error: missing parameter type for expanded function ((x$1) => x$1.reverse)` when trying `transformString(\"blah\", List(_.reverse))` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T11:37:02.043",
"Id": "46747",
"Score": "0",
"body": "Also, is there any behavioral difference between `transformString(\"blah\",_.toUpperCase)` and `transformString(\"blah\")(_.toUpperCase)` - or is it just style?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T11:38:38.347",
"Id": "46748",
"Score": "0",
"body": "Lastly, how does `disenvowel` look?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T11:58:07.367",
"Id": "46749",
"Score": "0",
"body": "@noahz edited to address your questions :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T17:34:01.517",
"Id": "46764",
"Score": "0",
"body": "Thanks, I also found a better (IMO) disenvowel too: `def disenvowel (s: String) = s filterNot {Set(\"aeiou\": _*)(_) }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T13:23:31.877",
"Id": "46803",
"Score": "0",
"body": "Even better: `def disenvowel (s: String) = s filterNot { \"aeiouAEIOU\" toSet _ }`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T07:03:42.473",
"Id": "29547",
"ParentId": "29516",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29547",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T06:09:27.677",
"Id": "29516",
"Score": "4",
"Tags": [
"scala"
],
"Title": "Improve scala functional string transformation"
}
|
29516
|
<p>I have a Java/Swing/Guice application that uses multiple frames. When the application runs normally, I just want some of these frames to hide (and the "master" frame can unhide them).</p>
<p>When testing the view, I have various other <code>main</code> methods that can open just one frame, and perhaps populate them with sample data. However, then the test application has no way to close (because their normal operation is to be hidden). But, I don't want to mess around with the constructor because I don't want this testing functionality to affect appear anywhere else, I want the "normal operation" module to have no knowledge of this behavior, because it's for testing, only.</p>
<p>Note: this is View testing (like, does it look the way I want it to?), so it's not really appropriate for JUnit.</p>
<p>How is this solution? Is there a better one?</p>
<pre><code>public class SubView {
private JFrame frame;
public SubView() {
initialize();
}
private void initialize() {
frame = new JFrame();
// etc. note, I don't call frame.setDefaultCloseOperation
// here, as hide is what I want
}
@Inject
private void setCloser(Closer c) {
frame.setDefaultCloseOperation(c.closeOperation);
}
private static class Closer {
@Inject(optional=true) @Named("closeOperation")
private int closeOperation = WindowConstants.HIDE_ON_CLOSE;
}
}
</code></pre>
<p>And then in my test class:</p>
<pre><code>public SubViewTester {
public static void main(String... args) {
Module testSpecific = new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("closeOperation"))
.to(WindowConstants.EXIT_ON_CLOSE);
}
};
Injector inj = Guice.createInjector(/* maybeSomeOtherModule, */ testSpecific);
SubView view = inj.getInstance(SubView.class);
EventQueue.invokeLater(new Runnable() {
view.setVisible(true);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The <code>Closer</code> class and its <code>setCloser</code> method does not close anything so I'd rather call it <code>CloseOperationProvider</code>. I guess you could get rid of it and annotate the <code>setCloser()</code> parameter instead:</p>\n\n<pre><code>@Inject(optional = true)\nprivate void setCloseOperation(@Named(\"closeOperation\") int closeOperation) {\n frame.setDefaultCloseOperation(closeOperation);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T14:59:34.303",
"Id": "42507",
"ParentId": "29520",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T14:44:43.757",
"Id": "29520",
"Score": "3",
"Tags": [
"java",
"unit-testing",
"swing",
"dependency-injection",
"guice"
],
"Title": "Guice custom behavior for testing"
}
|
29520
|
<p>I am quite new to Java, and I am trying to read a file into a string (or should I use byte arrays for this?). File can be anything, such as a text file or executable file etc. I will compress what I read and write it to another file.</p>
<p>I am thinking of using this code:</p>
<pre><code>public static String readFile(File f) {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
} catch (IOException e) {
System.err.println("I/O Exception:" + e.getMessage());
return null;
}
return sb.toString();
}
</code></pre>
<p>Does this look good to you? I was reading <a href="http://www.javapractices.com/topic/TopicAction.do?Id=42" rel="nofollow" title="Reading and writing text files">"Reading and writing text files"</a> and I was a little bit confused over all the different ways one can use to read files.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T17:42:59.440",
"Id": "46720",
"Score": "0",
"body": "I would suggest that you read this : http://stackoverflow.com/questions/3402735/what-is-simplest-way-to-read-a-file-into-string-in-java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T19:33:16.053",
"Id": "46722",
"Score": "4",
"body": "Strings are for character data only. Since the file might be an executable, that means it's not always going to be valid character data, so yes, you should use byte arrays instead of strings."
}
] |
[
{
"body": "<p>Why reinvent the wheel? </p>\n\n<p>Use <a href=\"https://commons.apache.org/proper/commons-io/download_io.cgi\" rel=\"nofollow\">commons-io</a>'s <code>FileUtils.readFileToByteArray(File)</code><a href=\"https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToByteArray%28java.io.File%29\" rel=\"nofollow\">(javadoc)</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T20:56:09.853",
"Id": "57182",
"Score": "1",
"body": "In this day and age, you'd most probably want to use [Guava](https://code.google.com/p/guava-libraries/) instead of Apache Commons. (With Guava it's [equally easy](http://codereview.stackexchange.com/a/35313/5665) to read a file into a string or byte array.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T23:11:45.877",
"Id": "35262",
"ParentId": "29521",
"Score": "2"
}
},
{
"body": "<p>Is this good code? The answer is, it depends!</p>\n\n<p>If you're just looking to read a short text file in the <a href=\"https://stackoverflow.com/q/1749064/1157100\">default charset</a> of the JVM, then it's quite adequate. I would prefer to propagate the <code>IOException</code> instead of returning <code>null</code>, so that the caller has flexibility in presenting the reason for the failure to the user. Also, I'd read a larger chunk at a time — blocks of 4 kiB or 8 kiB might be good choices, since they should align with the blocks of the underlying disk storage. I don't see any advantage to building the string one line at a time — scanning for the line-break characters is pointless busy work, and you're just going to concatenate everything together again anyway.</p>\n\n<p>On the other hand, if you are expecting binary data, or textual data in some other encoding, or textual data that is possibly malformed (e.g. invalid UTF-8 sequence), then you should read the data into a byte array instead of a <code>String</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T05:51:10.210",
"Id": "35275",
"ParentId": "29521",
"Score": "0"
}
},
{
"body": "<p>Old question, two new answers so far each with some concerns....</p>\n\n<p>Firstly, the original code has a significant bug, which should be pointed out:</p>\n\n<pre><code> String sCurrentLine;\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n</code></pre>\n\n<p>The above code will read a line from the <code>BufferedReader</code> but it will <strong>strip the end-of-line marker</strong> (whether that is <code>\\r\\n</code>, <code>\\n</code>, or whatever). When you append this value to the <code>StringBuilder</code> you lose this data.</p>\n\n<p>Unless there is a general need for importing third-party libraries, I try to avoid them. In this case, while the apache commons may have a convenience function, I would hesitate to create a dependency on it for just this function.</p>\n\n<p>Anyway, this particular commons call has a new-in-java7 analogue: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes%28java.nio.file.Path%29\" rel=\"nofollow\">byte[] Files.readAllBytes(Path);</a></p>\n\n<p>Similarly, the OP's actual situation may be solvable by: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29\" rel=\"nofollow\">String[] Files.readAllLines(Path, Charset);</a></p>\n\n<p>If neither of the above methods will solve the OP's situation, then I would recommend a more traditional approach.....</p>\n\n<p>If you want the data as a byte[] array, then use an Stream approach, but if you want the file as a String, use a Reader, and then:</p>\n\n<pre><code>// guess the amount of characters to be about half the number\n// of bytes in the file. It will be something more than this, but\n// this will be enough to limit the number of memory re-allocations.\nfinal int charguess = f.length() > Integer.MAX_VALUE\n ? Integer.MAX_VALUE // will likely throw OutOfMemory, not our fault...\n : ((int)(f.length() + 2) / 2 );\nfinal StringBuilder sb = new StringBuilder(charquess);\nfinal char[] buffer = new char[f.length() > 4096 ? 4096 : (int)f.length() + 1];\ntry (FileReader reader = new FileReader(f)) {\n int len = 0;\n while ((len = reader.read(buffer)) > 0) {\n sb.write(buffer, 0, len);\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>For more robust solutions I recommend specifying the charset encoding that you require the file to be in, and using an InputStream with an InputStreamReader to get the encoding right.</p>\n\n<p>EDIT: Finally, none of the answers so far (including mine, until now) have addressed the OP's actual anticipated usage. He wants to compress the file. The logical solution for this would be a CompressedOutputStream, and a byte[] based InputStream</p>\n\n<pre><code>File outfile = new File(f.getPath() + \".gz\");\ntry (FileInputStream fis = new FileInputStream(f);\n GZipOutputStream gzos = new GZipOutputStream(new FileOutputStream(outfile))) {\n\n byte[] buffer = new byte[4096];\n int len = 0;\n while ((len = fis.read(buffer)) > 0) {\n gzos.write(buffer, 0, len);\n }\n gzos.finish();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:01:59.177",
"Id": "35308",
"ParentId": "29521",
"Score": "2"
}
},
{
"body": "<p>With <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Guava</a>, a popular Java utility library, you'd do this:</p>\n\n<pre><code>try {\n String contents = Files.toString(new File(\"file.txt\"), Charsets.UTF_8);\ncatch (IOException e) { \n // ...\n}\n</code></pre>\n\n<p>Guava is a clean, actively maintained, very well documented library from Google.</p>\n\n<p>If you wanted to use pure Java, try <a href=\"https://stackoverflow.com/a/326440/56285\">this approach from Stack Overflow</a>.</p>\n\n<p>And since (from question comments) you may actually want to read into a byte array instead of string, with Guava you'd do that similarly with:</p>\n\n<pre><code>Files.toByteArray(new File(\"debug.apk\"));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T20:54:03.517",
"Id": "35313",
"ParentId": "29521",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T17:02:21.517",
"Id": "29521",
"Score": "4",
"Tags": [
"java",
"beginner",
"io"
],
"Title": "Reading a file into string in Java"
}
|
29521
|
<p>I'm not so good with recursion, so I've decided to tackle an exercise consisting of drawing this pattern using characters:</p>
<pre><code> *
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
</code></pre>
<p>Here is my code so far. What could be improved? Furthermore, is recursion suitable for a task like this or not?</p>
<pre><code>class Main
{
public static void main (String[] args)
{
Main.drawDiamond("*", 0, 5 );
}
public static void drawDiamond( String seed, int turn, int centerLevel ){
if( seed.length() <= 0 ){
return;
}
char[] chars = new char[Math.abs(turn-centerLevel-1)];
Arrays.fill(chars, ' ' );
String spaces = new String(chars);
System.out.print( spaces );
System.out.println( seed );
if( turn <= centerLevel ){
seed += "**";
} else {
if( seed.length() >= 3 ) {
seed = seed.substring(1,seed.length()-1);
} else {
seed = "";
}
}
turn++;
drawDiamond( seed, turn, centerLevel );
}
}
</code></pre>
|
[] |
[
{
"body": "<p>My few cents,</p>\n\n<ol>\n<li>Probably this is not the best exercise for recursive coding.</li>\n<li>the caller should not have to know about the middle parameter, ideally it would just be <code>Main.drawDiamond(\"*\", 5 );</code></li>\n<li><code>seed += \"**\";</code> this should use the seed, which might not be \"*\" but \"#\"</li>\n</ol>\n\n<p>4.</p>\n\n<pre><code>char[] chars = new char[Math.abs(turn-centerLevel-1)];\nArrays.fill(chars, ' ' );\nString spaces = new String(chars);\nSystem.out.print( spaces );\n</code></pre>\n\n<p>Could have been replaced with a loop that prints a space turn-centerLevel-1 times.</p>\n\n<p>Finally, if you think about the progresses of spaces and stars, then you see that you can do something with recursion.</p>\n\n<pre><code> Stars Spaces\n * 1 6\n *** 3 5\n ***** 5 4\n ******* 7 3\n ********* 9 2\n *********** 11 1\n************* 13 0\n *********** 11 1\n ********* 9 2\n ******* 7 3\n ***** 5 4\n *** 3 5\n * 1 6\n</code></pre>\n\n<p>Now if you consider the spaces as a negative number past 0, you can do this:</p>\n\n<pre><code>public class Diamond{\n\n public static void main( String[] args ) {\n draw( '*' , 5 );\n }\n\n static void draw( char c , int size ) {\n recurse( c , 1 , size++ );\n }\n\n static void recurse( char c , int count , int spaces ) {\n for( int i = 0 ; i < Math.abs( spaces ) ; i++ )\n System.out.print(\" \");\n for( int i = 0 ; i < count ; i++ )\n System.out.print( c );\n System.out.println(\"\");\n spaces--;\n count = count + ( spaces >= 0 ? +2 : -2 );\n if( count > 0 )\n recurse( c , count , spaces );.\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T20:29:17.153",
"Id": "29531",
"ParentId": "29523",
"Score": "1"
}
},
{
"body": "<p>The trick to getting this simple is expressing the start index of the stars and the number of stars as a mathematical function of the line they are on. <code>Math.abs()</code> is your friend for creating that turning point.</p>\n\n<p>I basically played around in excel to tune for the right formulas.</p>\n\n<p>As a kicker you can fill a <code>String</code> of stars and a <code>String</code> of spaces and use substring to avoid filling arrays over and over again. <code>substring()</code> does not copy the underlying array.</p>\n\n<pre><code>public class DrawDiamond {\n\n public static void main(String[] args) {\n new DrawDiamond().draw(7);\n }\n\n private void draw(int max) {\n String maxStars = filledString(max, '*');\n String maxSpaces = filledString(max, ' ');\n for (int i = 0; i < max; i++) {\n String spaces = maxSpaces.substring(0, startIndex(max, i));\n String stars = maxStars.substring(0, width(max, i));\n System.out.println(spaces + stars);\n }\n }\n\n private int width(int max, int line) {\n return -Math.abs(line - (max - 1) / 2) * 2 + max;\n }\n\n private int startIndex(int max, int line) {\n return Math.abs(line - (max + 1) / 2 + 1);\n }\n\n private String filledString(int width, char val) {\n char[] characters = new char[width];\n Arrays.fill(characters, val);\n return new String(characters);\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T21:46:29.227",
"Id": "46730",
"Score": "1",
"body": "But then it is not recursive any more ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T22:16:16.723",
"Id": "46732",
"Score": "2",
"body": "@tomdemuyt That the OP attempted to solve it with recursion, does not imply it is the most elegant solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T08:09:13.023",
"Id": "46741",
"Score": "0",
"body": "It's not recursive but I like how the problem has been separated into different tasks. I have changed the title to suit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T09:41:34.917",
"Id": "46742",
"Score": "1",
"body": "It's not a problem that lends itself to tackling with recursion, unless you find an easy way to draw an n size diamond starting from an n-2 size diamond"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T21:37:49.853",
"Id": "29533",
"ParentId": "29523",
"Score": "1"
}
},
{
"body": "<p>You can make this a recursion exercise with two parts:</p>\n\n<p>1) Write a recursive method to repeat a char n times.</p>\n\n<p>Signature:</p>\n\n<pre><code>public static String getCharRepeatedTimes(final char c, final int times)\n</code></pre>\n\n<p>(Read at end to see a solution)</p>\n\n<p>2) Write a recursive method to create a diamond pattern.</p>\n\n<p>Signature for recursive start method:</p>\n\n<pre><code>public static String getDiamondWithSize(final int size)\n</code></pre>\n\n<p>Signature for recursive \"work\" method:</p>\n\n<pre><code>private static String getDiamondWithSize(final int size, final int currentSize)\n</code></pre>\n\n<p>Hint 1: You can use the method from 1)<br>\nHint 2: Think about a pattern in the diamon and how to exploit it.</p>\n\n<p>(Read at end to see a solution)</p>\n\n<hr>\n\n<p>Let us start with 1):</p>\n\n<pre><code>public static String getCharRepeatedTimes(final char c, final int times) {\n if (times == 0)\n return \"\";\n return String.valueOf(c) + getCharRepeatedTimes(c, times - 1);\n}\n</code></pre>\n\n<p>And continue with 2):</p>\n\n<pre><code>public static String getDiamondWithSize(final int size) {\n return getDiamondWithSize(size, 2 - (size & 1));\n}\n</code></pre>\n\n<p>The start method can be done in two ways. Starting from the outer area to the inner area or vice-versa. I have done the out->in way. If you allow even and odd diamonds, then we have to manage the start or end size in the correct way. There the <code>2 - (size & 1)</code> part, which is 2 for even size and 1 for odd size.<br>\nThe idea is now to create the outer lines first and append it to the next inner part then. Until the inner part is the full part.</p>\n\n<pre><code>private static String getDiamondWithSize(final int size, final int currentSize) {\n if (currentSize == size)\n return getCharRepeatedTimes('*', size) + \"\\n\";\n final int nonDiamondSpace = (size - currentSize) / 2;\n final String currentLine = getCharRepeatedTimes(' ', nonDiamondSpace) + getCharRepeatedTimes('*', currentSize) + \"\\n\";\n return currentLine + getDiamondWithSize(size, currentSize + 2) + currentLine;\n}\n</code></pre>\n\n<p>The <code>+</code> concatenation could be replaced by <code>StringBuilder</code> , <code>insert</code> and <code>append</code>. For clarity and the exercise purpose, it is not done here.</p>\n\n<hr>\n\n<p>Suggestions for your code:</p>\n\n<pre><code>public static void drawDiamond(String seed, int turn, final int centerLevel) {\n ...\n if (turn <= centerLevel)\n</code></pre>\n\n<p>Noone would expect this if the method is called. At least for me, it is unclear how the argument centerLevel is related to the size of the diamond. You should add at least some JavaDoc, I would prefer to change the behavior.</p>\n\n<pre><code> turn++;\n drawDiamond(seed, turn, centerLevel);\n</code></pre>\n\n<p>In general, you should avoid to change arguments, if possible. In this case, we can go with this:</p>\n\n<pre><code> drawDiamond(seed, turn + 1, centerLevel);\n</code></pre>\n\n<p>This looks a bit complex:</p>\n\n<pre><code> if( turn <= centerLevel ){\n seed += \"**\";\n } else {\n if( seed.length() >= 3 ) {\n seed = seed.substring(1,seed.length()-1); \n } else {\n seed = \"\";\n }\n }\n</code></pre>\n\n<p>You should add at least some comments. And you can decrease the branch depth by one:</p>\n\n<pre><code> if (turn <= centerLevel) //until the mid is reached, increase by two stars\n seed += \"**\";\n else if (seed.length() >= 3) //until the end is reached, reduce by 2 chars\n seed = seed.substring(1, seed.length() - 1);\n else //finished\n seed = \"\";\n</code></pre>\n\n<p>Rest is more a subjective view. I would rather introduce a method to generate a char/String repeated n times than doing it inside the diamond method. And I would avoid the seed argument as shown above.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T10:37:41.390",
"Id": "29552",
"ParentId": "29523",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T17:40:40.790",
"Id": "29523",
"Score": "7",
"Tags": [
"java",
"algorithm",
"recursion"
],
"Title": "Attempt at method to draw diamond (recursive or not ?)"
}
|
29523
|
<p>Would the following be considered idiomatic Go code?</p>
<p>My main concerns are:</p>
<ol>
<li><p>The use of maps for this purpose. I basically want the data structure to be completely dynamic in size and have easy access to elements by id. This is because I will want to retrieve specific items on demand lots of times, so I don't want to loop each time.</p></li>
<li><p>The check for the map element</p></li>
<li><p>My use of pointers</p></li>
<li><p>General flow and structure</p></li>
</ol>
<p></p>
<pre><code>package main
import (
"fmt"
)
type BoxItem struct {
Id int
Qty int
}
func NewBox() *Box {
return &Box{make(map[int]*BoxItem), 0}
}
type Box struct {
BoxItems map[int]*BoxItem
}
func (this *Box) AddBoxItem(id int, qty int) *Box {
i, ok := this.BoxItems[id]
if ok {
i.Qty += qty
} else {
boxItem := &BoxItem{id, qty}
this.BoxItems[id] = boxItem
}
return this
}
func main() {
box := NewBox()
box.AddBoxItem(1, 1)
fmt.Printf("There are %d items in the box", len(box.BoxItems))
}
</code></pre>
|
[] |
[
{
"body": "<p>Instead of </p>\n\n<pre><code>i, ok := this.BoxItems[id]\nif ok {\n i.Qty += qty\n} \n</code></pre>\n\n<p>a more idiomatic usage is </p>\n\n<pre><code>if i, ok := this.BoxItems[id]; ok {\n i.Qty += qty\n} \n</code></pre>\n\n<p>Calling the receiver <code>this</code> doesn't seem like a good practice to me. Calling it <code>box</code> would be clearer.</p>\n\n<p>You seem to want to make your method chainable. I'm not sure this is a frequent practice in Go but it's probably more a matter of style and experience than a question of idiomatic code or not.</p>\n\n<p>The rest could be condensed a little but that's not a matter of idiom. I have nothing to say regarding your use of pointers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T18:18:46.963",
"Id": "46721",
"Score": "0",
"body": "I didnt set out to make it chainable, can you point to where you think i have purposely done this? Was it because the add method returns the box instance? and also where you think it can be condensed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-03T16:57:32.260",
"Id": "112538",
"Score": "0",
"body": "Seems chainable because the AddBoxItem function returns the Box reference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T18:11:33.967",
"Id": "29525",
"ParentId": "29524",
"Score": "4"
}
},
{
"body": "<p>In Go, you should hide the data structures and other implementation details of a box, then you can start with some plausible implementation of a box and later improve it if necessary. Implement box as a Go package. For example,</p>\n\n<p><code>box.go</code>:</p>\n\n<pre><code>package box\n\nfunc New() *Box {\n return &Box{items: make(map[int]int)}\n}\n\ntype Box struct {\n items map[int]int\n}\n\nfunc (b *Box) NumItems() int {\n return len(b.items)\n}\n\nfunc (b *Box) AddItem(id int, qty int) {\n b.items[id] += qty\n}\n\nfunc (b *Box) ItemQuantity(id int) int {\n return b.items[id]\n}\n</code></pre>\n\n<p><code>main.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"box\"\n \"fmt\"\n)\n\nfunc main() {\n b := box.New()\n id, qty := 1, 42\n b.AddItem(id, 1)\n b.AddItem(id, qty-1)\n fmt.Printf(\"There are %d items in the b.\\n\", b.NumItems())\n fmt.Printf(\"There are %d of item %d in the b.\\n\", b.ItemQuantity(id), id)\n id = 7\n fmt.Printf(\"There are %d of item %d in the b.\\n\", b.ItemQuantity(id), id)\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>There are 1 items in the box.\nThere are 42 of item 1 in the box.\nThere are 0 of item 7 in the box.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-03T17:57:57.753",
"Id": "161599",
"Score": "0",
"body": "BTW, both here and in the original, using `*Box` (other than as a receiver in methods that need to initialize the map itself, i.e. `make`) is undesirable for a type that only contains a simple map. It just adds an extra level of indirection. E.g. just use `func New() Box { return Box{…} }`; `func (b Box) NumItems()`, etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T14:24:52.080",
"Id": "29556",
"ParentId": "29524",
"Score": "3"
}
},
{
"body": "<p>So far, everything you want is provided by a map, so with just the requirements you've given in the original code, I'd use a map to keep things as simple as possible. You can later add methods to Box if you need them, but will have to refactor if you need to store more information than just quantities.</p>\n\n<pre><code>// An ID uniquely identifies a type of item that goes in a Box.\ntype ID int\n\n// A Box holds quantities of items (indexed by their ID).\ntype Box map[ID]int\n</code></pre>\n\n<p>If you want to know how many items you have:</p>\n\n<pre><code>n := box[someID]\n</code></pre>\n\n<p>If you want to add items to the box:</p>\n\n<pre><code>box[someID] += 3\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T08:26:16.483",
"Id": "47699",
"ParentId": "29524",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29525",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T18:09:11.500",
"Id": "29524",
"Score": "4",
"Tags": [
"go"
],
"Title": "Box data structure in Go"
}
|
29524
|
<pre><code>public static bool IsAnagramOf(this string word1, string word2)
{
return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
}
public static void Main()
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
string test = Console.ReadLine();
string[] split = test.Split(new Char[] { ',', '.', ' ' },
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < split.Length; i++)
{
foreach (string s in split)
{
if (split[i] != s)
if (split[i].IsAnagramOf(s))
{
Console.WriteLine(s);
}
}
}
Console.ReadLine();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T22:42:28.873",
"Id": "46733",
"Score": "0",
"body": "I really don't see how could this have too high memory footprint. I think you need to include some more details."
}
] |
[
{
"body": "<p>Not sure what memory issue you're having with this, but there is a simpler way to write this, since you're already employing LINQ:</p>\n\n<pre><code>private static bool IsAnagramOf(this string word1, string word2)\n{\n return word1\n .OrderBy(x => x)\n .SequenceEqual(word2.OrderBy(x => x));\n}\n\nprivate static void Main()\n{\n using (var si = new StreamReader(Console.OpenStandardInput(8192)))\n {\n Console.SetIn(si);\n\n var test = Console.ReadLine();\n var split = test == null\n ? Enumerable.Empty<string>().ToArray()\n : test.Split(new[] { ',', '.', ' ' }, StringSplitOptions.RemoveEmptyEntries);\n\n foreach (var s in split.SelectMany(t => split.Where(s => (t != s) && t.IsAnagramOf(s))))\n {\n Console.WriteLine(s);\n }\n\n Console.ReadLine();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T08:00:55.677",
"Id": "46740",
"Score": "0",
"body": "Will you please shed some light how using LINQ will be more beneficial than my code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T13:32:28.713",
"Id": "46752",
"Score": "0",
"body": "It's shorter, more concise, and indicates *intent* rather than the *way* to get to the results. Optimized LINQ libraries may also give you the memory and/or speed you are looking for. Measure early and often!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T22:02:17.057",
"Id": "29534",
"ParentId": "29527",
"Score": "0"
}
},
{
"body": "<p>and just shortening it up Jesse's answer...</p>\n\n<pre><code>private static bool IsAnagramOf(this string word1, string word2)\n{\n return word1\n .OrderBy(x => x)\n .SequenceEqual(word2.OrderBy(x => x));\n}\n\nstatic void Main(string[] args)\n{\n using (var si = new StreamReader(Console.OpenStandardInput(8192)))\n {\n Console.SetIn(si);\n var split = (Console.ReadLine() ?? \"\").Split(new[] {',', '.', ' '}, StringSplitOptions.RemoveEmptyEntries);\n split.SelectMany(t => split.Where(s => (t != s) && t.IsAnagramOf(s))).ToList().ForEach(Console.WriteLine); \n Console.ReadLine();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T02:17:03.047",
"Id": "29540",
"ParentId": "29527",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T18:20:16.050",
"Id": "29527",
"Score": "2",
"Tags": [
"c#",
"linq",
"memory-management"
],
"Title": "Reducing memory footprint in anagram-finding program for text"
}
|
29527
|
<p>I have this code snippet below that I am looking for a way to make smaller if possible. Any help or suggestions would be appreciated, thanks!</p>
<pre><code>Private Sub ShowAlternateRows(Show As Boolean)
If Show = True Then
splitter.Visible = True
lblAlternateActualPercent.Visible = True
lblAltEstimated.Visible = True
lblStaticAltEstimated.Visible = True
Grid.Cols.Item("Alternate Type").Visible = True
Grid.Cols.Item("Alternate Start").Visible = True
Grid.Cols.Item("Alternate End").Visible = True
Grid.Cols.Item("Alternate Hours").Visible = True
Grid.Cols.Item("Alternate Burn").Visible = True
Grid.Cols.Item("Start Estimated").Visible = False
Grid.Cols.Item("End Estimated").Visible = False
Grid.Cols.Item("Start Actual").Visible = False
Grid.Cols.Item("End Actual").Visible = False
Grid.Cols.Item("Estimated Hours").Visible = False
Grid.Cols.Item("Actual Hours").Visible = False
Grid.Cols.Item("Burn Estimated").Visible = False
Grid.Cols.Item("Object Count").Visible = False
Grid.Cols.Item("Request Count").Visible = False
Grid.Cols.Item("Resource Count").Visible = False
lblStaticActual.Visible = False
lblActual.Visible = False
lblActualPercent.Visible = False
lblStaticEstimated.Visible = False
lblEstimated.Visible = False
lblStaticFiltered.Visible = False
lblFiltered.Visible = False
lblFilteredPercent.Visible = False
Else
splitter.Visible = False
lblAlternateActualPercent.Visible = False
lblAltEstimated.Visible = False
lblStaticAltEstimated.Visible = False
lblStaticActual.Visible = True
lblActual.Visible = True
lblActualPercent.Visible = True
lblStaticEstimated.Visible = True
lblEstimated.Visible = True
lblStaticFiltered.Visible = True
lblFiltered.Visible = True
lblFilteredPercent.Visible = True
Grid.Cols.Item("Start Estimated").Visible = True
Grid.Cols.Item("End Estimated").Visible = True
Grid.Cols.Item("Start Actual").Visible = True
Grid.Cols.Item("End Actual").Visible = True
Grid.Cols.Item("Estimated Hours").Visible = True
Grid.Cols.Item("Actual Hours").Visible = True
Grid.Cols.Item("Burn Estimated").Visible = True
Grid.Cols.Item("Object Count").Visible = True
Grid.Cols.Item("Request Count").Visible = True
Grid.Cols.Item("Resource Count").Visible = True
Grid.Cols.Item("Alternate Type").Visible = False
Grid.Cols.Item("Alternate Start").Visible = False
Grid.Cols.Item("Alternate End").Visible = False
Grid.Cols.Item("Alternate Hours").Visible = False
Grid.Cols.Item("Alternate Burn").Visible = False
End If
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>Assuming <code>OPTION STRICT OFF</code> (since I don't know the type of <code>Grid.Cols.Item</code>):</p>\n\n<pre><code>Private Sub ShowAlternateRows(show As Boolean)\n Dim grpShow = \n {\n splitter, lblAlternateActualPercent, \n lblAltEstimated, lblStaticAltEstimated, \n Grid.Cols.Item(\"Alternate Type\"), Grid.Cols.Item(\"Alternate Start\"),\n Grid.Cols.Item(\"Alternate End\"), Grid.Cols.Item(\"Alternate Hours\"),\n Grid.Cols.Item(\"Alternate Burn\")\n }\n Dim grpHide = \n {\n Grid.Cols.Item(\"Start Estimated\"), Grid.Cols.Item(\"End Estimated\"),\n Grid.Cols.Item(\"Start Actual\"), Grid.Cols.Item(\"End Actual\"),\n Grid.Cols.Item(\"Estimated Hours\"), Grid.Cols.Item(\"Actual Hours\"),\n Grid.Cols.Item(\"Burn Estimated\"), Grid.Cols.Item(\"Object Count\"),\n Grid.Cols.Item(\"Request Count\"), Grid.Cols.Item(\"Resource Count\"),\n lblStaticActual, lblActual,\n lblActualPercent, lblStaticEstimated,\n lblEstimated, lblStaticFiltered,\n lblFiltered, lblFilteredPercent\n }\n For Each ctrl in grpShow\n ctrl.Visible = show\n Next\n For Each ctrl in grpHide\n ctrl.Visible = Not show\n Next\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T21:55:59.417",
"Id": "46925",
"Score": "0",
"body": "This does cut things down 1/2 at least, ty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T07:05:11.970",
"Id": "46947",
"Score": "0",
"body": "@AdamShip Yeah; also, the code duplication is removed. You could save 4 more lines by replacing the `For Each` loops by using lists and using the `ForEach()` extension method, but I would not recommend doing so because of the loss of readability."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T12:06:11.290",
"Id": "29646",
"ParentId": "29535",
"Score": "1"
}
},
{
"body": "<p>First, if you can put the labels in 1 or more panels, you can just show/hide the panels. This means instead of:</p>\n\n<pre><code>splitter.Visible = Show\nlblAlternateActualPercent.Visible = Show\nlblAltEstimated.Visible = Show\nlblStaticAltEstimated.Visible = Show\n\nlblStaticActual.Visible = Not Show\nlblActual.Visible = Not Show\nlblActualPercent.Visible = Not Show\nlblStaticEstimated.Visible = Not Show\nlblEstimated.Visible = Not Show\nlblStaticFiltered.Visible = Not Show\nlblFiltered.Visible = Not Show\nlblFilteredPercent.Visible = Not Show\n</code></pre>\n\n<p>You could do something like:</p>\n\n<pre><code>Panel1.Visible = Show\nPanel2.Visible. Not Show\n</code></pre>\n\n<p>Also, noticed how I used <code>Show</code> or <code>Not Show</code> instead if an If/Else statement with all the code twice.</p>\n\n<p>Last, Itererate through the columns, assuming that you want to do something with each column. (I am assuming Grid.Cols returns a DataGridColumnCollection. You might need to change for your specific type)</p>\n\n<pre><code>For each col as DataGridColumn in Grid.Cols\n If col.Name.tolower.StartsWith(\"alternate \") then\n col.visible = Show\n Else\n col.Visible = Not Show\n End If\nNext\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T21:06:54.443",
"Id": "32837",
"ParentId": "29535",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T22:03:40.497",
"Id": "29535",
"Score": "2",
"Tags": [
"vb.net"
],
"Title": "Better Way to Show and Hide Items in Project"
}
|
29535
|
<p>Here's a Python script to optimize JSON documents:</p>
<pre><code>#!/usr/bin/python3
"""jopo - Optimize JSON documents."""
from collections import defaultdict
def optimize(data):
"""Optimize a JSON-like data structure."""
if isinstance(data, list):
if len(data) == 1:
return optimize(data[0])
digest = defaultdict(lambda: defaultdict(set))
for element in data:
if not isinstance(element, dict) or len(element) != 2:
break
for key, value in element.items():
digest[key][type(value)].add(repr(value))
else:
if len(digest) == 2:
pool = {k for k in digest if len(digest[k][str]) == len(data)}
if pool:
if len(pool) > 1:
meta = input("Which key (%s)? " % "|".join(pool))
else:
meta = next(iter(pool))
infra = (digest.keys() - {meta}).pop()
return {d[meta]: optimize(d[infra]) for d in data}
return [optimize(x) for x in data]
if isinstance(data, dict):
if len(data) == 1:
return optimize(next(iter(data.values())))
else:
return {k: optimize(v) for k, v in data.items()}
return data
if __name__ == "__main__":
import json
import sys
for arg in sys.argv[1:]:
with open(arg) as f:
doc = json.load(f)
print(json.dumps(optimize(doc), indent=2))
</code></pre>
<p>... which, given a JSON document <code>recipes.json</code> like this:</p>
<pre><code>{
"recipes": [
{
"name": "pizza",
"ingredients": [
{
"quantity": "100g",
"ingredient": "cheese"
},
{
"quantity": "200g",
"ingredient": "tomato"
}
]
},
{
"name": "pizza 2",
"ingredients": [
{
"quantity": "300g",
"ingredient": "ham"
},
{
"quantity": "300g",
"ingredient": "pineapple"
}
]
}
]
}
</code></pre>
<p>... is used like this:</p>
<pre><code>$ ./jopo.py recipes.json
Which key (ingredient|quantity)? ingredient
{
"pizza 2": {
"ham": "300g",
"pineapple": "300g"
},
"pizza": {
"tomato": "200g",
"cheese": "100g"
}
}
</code></pre>
<p>It does two things:</p>
<ol>
<li><p>Collapse 1-item objects and arrays.</p></li>
<li><p>Reduce arrays of congruent 2-item objects to a single object, if possible.</p></li>
</ol>
<p>I think the <code>optimize()</code> function is both too long and too hard to follow.</p>
<p>Obviously I could separate out the <code>if isinstance(data, <type>): # ...</code> blocks into separate functions, but even then, an <code>optimize_list()</code> function along those lines is still going to be quite long and, IMO, somewhat impenetrable.</p>
<p>How can I improve the legibility of this code?</p>
|
[] |
[
{
"body": "<pre><code> digest = defaultdict(lambda: defaultdict(set))\n</code></pre>\n\n<p>It's pretty rare that we have a good reason for such a nested data structure in python.</p>\n\n<pre><code> for element in data:\n if not isinstance(element, dict) or len(element) != 2:\n break\n for key, value in element.items():\n digest[key][type(value)].add(repr(value))\n</code></pre>\n\n<p>Why are we adding the repr of the value? I assume you do it to avoid taking the hash of unhashable objects. But what if somebody puts some strange object in your list that has a repr which always returns the same thing. Besides you are only interested in strings.</p>\n\n<pre><code> else:\n if len(digest) == 2:\n</code></pre>\n\n<p>This is an unintuive way to check for your requirement. Your requirement is actually that all elements have the same keys. Check for that instead.</p>\n\n<pre><code> pool = {k for k in digest if len(digest[k][str]) == len(data)}\n</code></pre>\n\n<p>Your actually checking to see if that key was always a string. Perhaps you should check that more directly.</p>\n\n<pre><code> if pool:\n if len(pool) > 1:\n meta = input(\"Which key (%s)? \" % \"|\".join(pool))\n</code></pre>\n\n<p>Its deeply suspicious if you need to ask the user for instructions. </p>\n\n<pre><code> else:\n meta = next(iter(pool))\n infra = (digest.keys() - {meta}).pop()\n return {d[meta]: optimize(d[infra]) for d in data}\n return [optimize(x) for x in data] \n</code></pre>\n\n<p>Here is my reworking of it.</p>\n\n<pre><code>def optimize(data):\n \"\"\"\n Dispatcher, figure out which algorithm to use to compress the json\n \"\"\"\n if isinstance(data, list):\n if len(data) == 1:\n return optimize(data[0])\n else:\n keys = determine_key(data)\n if keys is None: # unable to determine tkeys\n return [optimize(element) for element in data]\n else:\n return optimize_list(data, keys)\n elif isinstance(data, dict):\n if len(data) == 1:\n return optimize(next(iter(data.values())))\n else:\n return optimize_dict(data)\n else:\n return data\n\ndef optimize_dict(data):\n \"\"\"\n Optimize a dict, just optimizes each value\n \"\"\"\n return {key : optimize(value) for key, value in data.items()}\n\ndef can_be_key(data, key):\n \"\"\"\n return true if key could be a key\n \"\"\"\n if not all( isinstance(element[key], str) for element in data):\n return False\n return len(set(element[key] for element in data)) == len(data)\n\ndef determine_key(data):\n \"\"\"\n Determine the key, value to compress the list of dicts\n or None if no such key exists\n \"\"\"\n for element in data:\n if not isinstance(element, dict):\n return None\n if len(element) != 2:\n return None\n if element.keys() != data[0].keys():\n return None\n\n key1, key2 = data[0].keys()\n key1_possible = can_be_key(data, key1)\n key2_possible = can_be_key(data, key2)\n\n if key1_possible and key2_possible:\n meta = input(\"Which key (%s|%s)? \" % (key1, key2))\n if meta == key1:\n return key1, key2\n else:\n return key2, key1\n elif key1_possible:\n return key1, key2\n elif key2_possible:\n return key2, key1\n else:\n return None\n\ndef optimize_list(data, keys):\n key_key, key_value = keys\n return {element[key_key]: optimize(element[key_value]) for element in data}\n</code></pre>\n\n<p>But... I must question the wisdom of the entire approach. The function is actually rather useless. Suppose that you use it on web service that returns a json object. It gives you</p>\n\n<pre><code>{\"results\" : [\n {\"name\" : \"foo\", \"age\": 42}\n {\"name\" : \"bar\", \"age\": 36}\n}\n</code></pre>\n\n<p>Which optimize to </p>\n\n<p>{\"foo\": 42, \"age\": 36}</p>\n\n<p>So you write:</p>\n\n<pre><code>for name, age in optimize(the_json).items():\n print(name, age)\n</code></pre>\n\n<p>But then in another request, the server returns </p>\n\n<pre><code>{\"results\" : [\n {\"name\" : \"foo\", \"age\": 42}\n}\n</code></pre>\n\n<p>which optimizes to:</p>\n\n<p>42</p>\n\n<p>So when you run:</p>\n\n<pre><code>for name, age in optimize(the_json).items():\n print(name, age)\n</code></pre>\n\n<p>You get an error.</p>\n\n<p>Or the server adds extra data to the json:</p>\n\n<pre><code>{\n \"salinity\" : \"high\",\n \"results\" : [\n {\"name\" : \"foo\", \"age\": 42, \"status\" : \"sad\"}\n {\"name\" : \"bar\", \"age\": 36, \"status\" : \"happy\"}\n}\n</code></pre>\n\n<p>Which should be backwards compatible using json, but will break your code or anything doing the same job. </p>\n\n<p>This is not to say that can't or shouldn't simplify the json. But don't try to do it by analyzing the data like this. You should do it by some external record of the schema. </p>\n\n<pre><code>class Fetch(object):\n \"\"\"\n Fetch one element from a dictionary\n \"\"\"\n def __init__(self, name, inner):\n self._name = name\n self._inner = inner\n\n def __call__(self, data):\n return self._inner(data[self._name])\n\nclass KeyValue(object):\n \"\"\"\n Given a list of dicts, convert to a dictionary\n with each key being taken from the `key` on each element\n and each value being taken from the `value`\n \"\"\"\n def __init__(self, key, value, inner):\n self._key = key\n self._value = value\n self._inner = inner\n\n def __call__(self, data):\n return {element[self._key] : self._inner(element[self._value]) for element in data}\n\nclass Literal(object):\n def __call__(self, data):\n return data\n\nschema = Fetch(\"recipes\",\n KeyValue(\"name\", \"ingredients\",\n KeyValue(\"ingredient\", \"quantity\", Literal())\n )\n)\n</code></pre>\n\n<p>That's actually simpler then what you were doing, and its much more robust. Its also very flexible as you can write code to perform just about any transformation on the data. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T11:30:28.973",
"Id": "46745",
"Score": "0",
"body": "Thanks for the detailed critique ... I'll take some time to give it the attention it deserves, but for the moment, re: \"I must question the wisdom of the entire approach\" - it's not intended to work with live data (as you say, that would be horribly fragile), but as an aid in analysing the design of a JSON document. The idea came from [this SO question](http://stackoverflow.com/q/17913469/1014938), and the realisation that I could get a machine to replicate the rules I'd applied in answering it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:51:48.630",
"Id": "46980",
"Score": "0",
"body": "On your criticisms:\nI agree the nested defaultdict is less readable than it could be. I'm using it to check complex-ish criteria in as few passes as possible; perhaps I shouldn't.\nYes, the `repr` is for hashability. I'm unaware of any two distinct JSON fragments with the same `repr`; do you know of any?\nMy requirement is that all objects in the array have the same *two* keys, so that the array can be converted to an object.\nI'm checking that the value is always a *unique* string, so that it can be a key.\nUser input is necessary if both potential keys all have unique string values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:52:31.633",
"Id": "46981",
"Score": "0",
"body": "Given the purpose of the code - suggest improvements to an implicit schema from example data - I can't really use a nonexistent schema to optimize against. My apologies for not being clearer about that in my question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:53:56.843",
"Id": "46982",
"Score": "0",
"body": "And ... it turns out I can't put linebreaks in comments. Further apologies for the mess that's made of my response. If code review is a dialogue, it's kinda tricky in the SO format, isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:04:43.943",
"Id": "46984",
"Score": "0",
"body": "No two JSON fragments will never have the same repr. But somebody could pass something that wasn't json into your code. Its probably not a serious thing to be concerned about. But its a rather odd use of repr."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:05:53.777",
"Id": "46985",
"Score": "0",
"body": "I didn't understand the purpose of your code initially, I do get people around here who are trying to do the sort of thing I was warning you against. I'm glad to know you aren't doing that, and my suggested approach is just irrealvent."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T03:36:44.900",
"Id": "29542",
"ParentId": "29536",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T22:28:10.160",
"Id": "29536",
"Score": "2",
"Tags": [
"python",
"json"
],
"Title": "Critique my JSON-optimizing Python script"
}
|
29536
|
<p>I want to display a town name in my navigation, depending on the town I am requesting from the model. The following code works, but I am mixing logic in my view which I know is wrong and I haven't been successful in accessing the <code>@town</code> instance variable from my <code>TownsController</code>.</p>
<p>Can someone lead me down the road to enlightenment in a situation like this? Should I be using a helper? How do I access it in my <code>_header.html.erb</code> partial?</p>
<pre><code><li class="name">
<% @towns = Town.all %>
<% @towns.each do |t| %>
<h1><%= link_to "#{t.name}", '#', id: "logo" %></h1>
<% end %>
</li>
</code></pre>
|
[] |
[
{
"body": "<p>Is _header.html.erb part of the layout? If so, i would advice you to move this logic to helper, if not all the controllers would need to set the @towns instance variable.</p>\n\n<pre><code>module ApplicationHelper\n def town_names\n Town.all.collect(&:name)\n end\nend\n</code></pre>\n\n<p>And in your view call the town_names. I think you want each name to be in an <code>li</code> element. I have changed the code accordingly.</p>\n\n<pre><code><% town_names.each do |name| %>\n <li class=\"name\">\n <h1><%= link_to name, '#', id: \"logo\" %></h1>\n </li>\n <% end %>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-23T18:15:22.080",
"Id": "148230",
"Score": "0",
"body": "You should not be doing ActiveRecord queries in a view helper. Instead, do set the `@towns` instance variable in all required controller actions using a `before_filter`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-11T14:21:15.657",
"Id": "31103",
"ParentId": "29538",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T00:15:37.877",
"Id": "29538",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"erb"
],
"Title": "Moving instance variable from partial to helper"
}
|
29538
|
<p>I have done some tests of my code, which I got help to improve here before. The code simply takes a screenshot of a selected process window, encodes it to JPEG (if I want), saves it to a <code>memorystream</code> and returns it (necessary for sending it).</p>
<p>My test simply runs the code 1000 times, and posts the time it took in ms.</p>
<p>It's very simple to look at it this way. I think that 10 seconds is 0% delay, but I'm not sure. From the results, it should be that for some reason (it should be 60fps as my screen displays that, not 100).</p>
<p>So here are the results:</p>
<pre><code>800x600 = 11160 ms
1152x864 = 20218 ms
1600x1200 = 36399 ms
</code></pre>
<p>The resolution isn't exactly correct as I am not counting the window borders, etc, so it is a bit larger. 800x600 is super fast, even with JPEG encoding, just a little slower than BMP.</p>
<p>But then, even the little jump to 1152x864 makes a huge performance hit, about twice as slow (with BMP, there was about 17k ms, so the encoding did quite the hit, but it's still very slow).</p>
<p>1600x1200 was more than 3x times slower. I didn't try BMP there, but I would guess it would land on 30k ms.</p>
<pre><code>private static MemoryStream PrintWindow(IntPtr hwnd, EncoderParameters JpegParam)
{
NativeMethods.Rect rc;
NativeMethods.GetWindowRect(hwnd, out rc);
using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics gfxBmp = Graphics.FromImage(bmp))
{
IntPtr hdcBitmap = gfxBmp.GetHdc();
try
{
NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);
}
finally
{
gfxBmp.ReleaseHdc(hdcBitmap);
}
}
MemoryStream ms = new MemoryStream();
bmp.Save(ms, GetEncoderInfo(ImageFormat.Jpeg), JpegParam);
return ms;
}
}
</code></pre>
<p>It basically hooks to a window and takes a screenshot of that window.</p>
<p>I didn't even think that capturing took make such a big performance hit, so I really need to solve this.</p>
<p>I am using <code>User32.dll</code> to capture. I do, however, want to try out <code>CaptureBlt</code> as I think it may be faster, as <code>User32.dll</code> forces the window that's being captured to refresh all the time, which causes some problems on some applications (flicker).</p>
<p>If you know any way to improve this (excluding the encoding part (JPEG)), let me know, as I must improve this.</p>
<p>Worth mentioning:</p>
<blockquote>
<p>Graphic Card = 6970 2GB (High End)</p>
<p>CPU = 4ghz 4 core</p>
</blockquote>
<p>After testing a bit more, I noticed that the thing that takes about 30-40% of the speed is actually the saving of the bitmap to a <code>Memorystream</code>.</p>
<pre><code>MemoryStream ms = new MemoryStream();
bmp.Save(ms, GetEncoderInfo(ImageFormat.Jpeg), JpegParam);
return ms;
</code></pre>
<p>Even with .bmp it takes a huge performance hit. I don't really know what to improve there, as I must save it to a <code>memorystream</code> to use it.</p>
<p><strong>UPDATE 1:</strong></p>
<p>Performance increases by 5-10% if I reuse the same <code>memorystream</code> all the time. So I don't let the static function make a new one, and handle that outside.</p>
<p><strong>UPDATE 2:</strong></p>
<blockquote>
<p>Setting a static capacity to Memorystream MAY give a performance
increase, not really sure, if it give, it´s extremely little, here are
the tests.</p>
<p>Static</p>
<pre><code>Execute1 time = 11144 ms
Execute1 time = 11223 ms
Execute1 time = 11183 ms
</code></pre>
<p>Dynamic</p>
<pre><code>Execute1 time = 11301 ms
Execute1 time = 11282 ms
Execute1 time = 11194 ms
</code></pre>
<p>As you can see, it is give and take, but it doesn't hurt performance
it seems that´s for sure.</p>
</blockquote>
<p>It seems setting capacity doesn't even work from the looks of it. I can set it to 2 bytes, and it will still work normally.</p>
<p><strong>Update 3:</strong></p>
<p>There must be something that can be done, maybe not to this code, but another way.
As else, how can captured software be able to save high resolutions like 1080p at 60fps, only to be limited by CPU or GPU and not the actual algorithm?</p>
<p><strong>Update 4:</strong></p>
<p>I finally got <code>GDI32</code> to work. It solves the flicker, however the performance seems to be pretty much the same, maybe a bit better.</p>
<pre><code>IntPtr dc1;
IntPtr dc2;
NativeMethods.Rect rc;
NativeMethods.GetWindowRect(hwnd, out rc);
using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
dc1 = g.GetHdc();
dc2 = NativeMethods.GetWindowDC(hwnd);
try
{
NativeMethods.BitBlt(dc1, 0, 0, rc.Width, rc.Height, dc2, 0, 0, 13369376);
}
finally
{
g.ReleaseHdc(dc1);
}
}
bmp.Save(ms, GetEncoderInfo(ImageFormat.Jpeg), JpegParam);
return ms;
}
</code></pre>
<p><strong>Update 5:</strong></p>
<p>Another optimization is to remove everything that is disposable, and have it enabled all the time, until you are done.</p>
<p>Meaning, <code>Bitmap</code> and <code>Graphics</code> and <code>Intptr</code> to the window handle.</p>
<p>Also, calling <code>GetWindowRect</code> takes a lot of performance and is really only needed if the window size changed, so you can move that and call it before the loop. If you change the size, just rerun it. </p>
<p>All this improves quite a bit, and the final limitation is the capture <code>Bitblt</code>, and compressing (if not BMP).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T17:18:32.410",
"Id": "46761",
"Score": "0",
"body": "What are you building? Why is it not enough for you for a screenshot to take on the order of tens of ms? Perhaps use a highly optimized system tool written in C that can grab the picture of a Window from a display buffer somewhere and dump it as bmp. I am sure there are plenty of fast tools to do this on Linux; there must be something for Windows as well. You could settle for dumping the screenshot in whatever format makes it quicker, and then try to catch up on processing in a separate thread. Again, it all depends on what you are trying to build. What is it? Who creates the requirements?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T17:23:22.400",
"Id": "46762",
"Score": "0",
"body": "I am building an application that records a window(preferably a buffer but don´t know how to do that), and then sends it and displays it (pretty much, Remote Desktop to simplify).\nI would gladly like to get a bmp from the display buffer if that´s faster. But i don´t know how to implement it.\nThe requirements are made by myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T17:39:35.863",
"Id": "46765",
"Score": "0",
"body": "Looks like MSFT has created a library for creating a Remote Desktop application, and here is a simple example of how one would use it :) http://www.codeproject.com/Articles/43705/Remote-Desktop-using-C-NET"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T17:41:50.980",
"Id": "46766",
"Score": "0",
"body": "Looked at that, but what i meant with Remote Desktop was just that an imaged at the client is displayed at the server, was wrong to say Remote Desktop really, sorry for that:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T16:33:14.943",
"Id": "46813",
"Score": "1",
"body": "Hm ... if you log in programmatically and disable moue events, then what is the difference? I think the specialized library is able to do this fast because it was engineered with performance in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T10:43:45.360",
"Id": "46831",
"Score": "0",
"body": "The difference is latency probably. How it takes the picture, how it sends it, and in what format. Remote Desktop things aren´t normally made for the looks, and purely made for \"Remote Desktoping\". My application is \"Remote Displaying\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T04:16:17.240",
"Id": "54793",
"Score": "0",
"body": "Have you considered using BitBlt instead? http://pinvoke.net/default.aspx/gdi32/BitBlt.html"
}
] |
[
{
"body": "<p>Well, first of all, what you call \"the little jump\" is not that little. You can easily devide <code>1152x864</code> by <code>800x600</code> for yourself and see, that it, surprisingly enough, equals <code>2</code>. Which means, that your algorithm most likely has a complexity of <code>O(n)</code>, which makes sense.</p>\n\n<p>As for your code - you can find the common way to save screenshots in .Net <a href=\"https://stackoverflow.com/a/363008/1386995\">on SO</a> (just dont forget to clean up: dispose bitmap, etc. ). You dont need to use interop for such tasks. I doubt it can be optimized any further.</p>\n\n<p><strong>Edit:</strong> you should also set <code>MemoryStream</code> buffer size <a href=\"http://msdn.microsoft.com/ru-ru/library/bx3c0489.aspx\" rel=\"nofollow noreferrer\">manually</a>, to fit the size of resulting data. If you don't, it might cause <code>MemoryStream</code> to resize constantly and lead to performance loss.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T10:58:40.193",
"Id": "46743",
"Score": "0",
"body": "Well true enough, but i need to be able to handle higher resolutions.\nWell i am using the \"fastest\" one i got knowledge about, which is User32 printwindow. Would gladly try something else. SourceCopy isn´t the way to go though.\n\nI actually remake the memorystream everytime, though i actually changed that just now to use the same memorystream over and over, and only dispose once everything is completed. This increase performance by about 5-10%.\n\nWill try setting the buffer to the ms to be as big as the possible image, to see if a static buffer will improve it even further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:19:18.763",
"Id": "47149",
"Score": "0",
"body": "Good point about the \"little bumb\", I had the same thought. If you take (resolution.x * resolution.y) / execution time you get roughly 43, 49, 52. So your slowdown as size gets larger is linear with a small slope, but is certainly not exponential."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T10:37:22.603",
"Id": "29551",
"ParentId": "29548",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T08:36:19.093",
"Id": "29548",
"Score": "3",
"Tags": [
"c#",
"performance",
"image"
],
"Title": "Encoding a screenshot to JPEG and saving it to a memorystream"
}
|
29548
|
<p>I'm doing an exercise where I need to convert <code>int</code> to <code>bignum</code> in OCaml, for example:</p>
<blockquote>
<pre><code>123456789 -> {neg:false; coeffs:[123;456;789]}
</code></pre>
</blockquote>
<p>There were a lot of things going inside my head when writing the function, and it was a load of fun. However, I'm not really sure if this is the cleanest, and fastest way to do this.</p>
<pre><code>type bignum = {neg: bool; coeffs: int list};;
let base = 1000;;
let fromInt (n: int) : bignum =
let rec aux num:int list=
if num==0 then
[]
else
abs (num mod base) :: aux (num/base)
in
{neg=n<0; coeffs=List.rev (aux n)}
;;
</code></pre>
<p>fromInt turns an <code>int</code> to a <code>bignum</code>. Things to note:</p>
<ul>
<li>I decided to mod the number with the base, and then divide the number
by the base and use that as the input. This is so I can avoid having to do exponents on ints. Was actually pretty excited when I realized that.</li>
<li>Used abs on (num mod base) every recursive call. Do you think there is a cleaner way of doing this? The the reason I didn't <code>abs</code> it on the first call was because <code>(-max_int) <> min_int</code></li>
<li>As you can see I'm using List.rev because I do it in reverse order. This is so I can avoid having snoc lists. I'm not really sure if it's the only way though so feel free to note me.</li>
</ul>
<p>And here is <code>toInt</code>, which turns a <code>bignum</code> into an <code>int</code>.</p>
<pre><code>let toInt (b: bignum) =
let rec aux (b:int list) (p:int)=
match b with
|hd::[]-> Some (hd*p)
|hd::tl-> (match aux tl (p*base) with
|Some c-> let bint = (hd*p) in
if bint < hd then None
else Some (bint+c)
|None -> None)
|[]->Some 0
in
let {neg=n; coeffs=x} = b in
let c = List.rev x in
match aux c 1 with
|Some c-> if n then Some (-c) else Some c
|None -> None
;;
</code></pre>
<p>I'm particularly not fond of the nested match statements, and there is probably still room for cleanup. Is there?</p>
|
[] |
[
{
"body": "<p><code>num==0</code> is misleading, use <code>num=0</code> (although it has the same meaning for integers). Also, <code>fromInt</code> is spread over too many lines for my taste, I'd prefer the following choice of line breaks:</p>\n\n<pre><code>let fromInt (n: int) : bignum =\n let rec aux num : int list =\n if num=0 then []\n else abs (num mod base) :: aux (num/base) in\n {neg=n<0; coeffs=List.rev (aux n)}\n</code></pre>\n\n<p>This is fine for short lists of coefficients. In general tail recursion is preferred. I drop type annotations below. I add type annotations during debugging if I start getting confusing type errors, other than that I put types of functions in the interface (.mli).</p>\n\n<pre><code>let fromInt n =\n let rec aux acc num =\n if num=0 then acc\n else aux (abs (num mod base) :: acc) (num/base) in\n {neg=n<0; coeffs=aux n}\n</code></pre>\n\n<p>General note. I use the following kinds of line breaks with <code>if..then..else</code> depending on what fits in 80 columns and looks nice.</p>\n\n<pre><code>if test then blah\nelse blah\n\nif test\nthen blah\nelse blah\n\nif test\nthen\n blah\nelse\n blah\n</code></pre>\n\n<p>Now on to <code>toInt</code>. First, the way I would format it:</p>\n\n<pre><code>let toInt b =\n let rec aux b p =\n match b with\n | [] -> Some 0\n | hd::tl ->\n match aux tl (p*base) with\n | Some c->\n let bint = hd*p in \n if bint < hd then None \n else Some (bint+c)\n | None -> None in\n let c = List.rev b.coeffs in\n match aux c 1 with\n | Some c -> if b.neg then Some (-c) else Some c\n | None -> None\n</code></pre>\n\n<p>Again, it is interesting to explore the tail-recursive variant. I use my preferred style.</p>\n\n<pre><code>let toInt b =\n let rec aux acc p = function\n | [] -> Some acc\n | hd::tl ->\n let bint = hd*p in \n if bint < hd then None \n else aux (bint + acc) (p*base) tl in\n let c = List.rev b.coeffs in\n match aux 0 1 c with\n | Some c -> if b.neg then Some (-c) else Some c\n | None -> None\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T21:58:22.477",
"Id": "29598",
"ParentId": "29549",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T09:16:12.867",
"Id": "29549",
"Score": "2",
"Tags": [
"functional-programming",
"ocaml"
],
"Title": "Functional Programming: int to bignum conversions"
}
|
29549
|
<p>First off, I know there are other solutions and practices but I'm referring to MS proposed code from .NET documentation.</p>
<p>It goes like this:</p>
<pre><code>client.Connect(anEndPoint);
bool blockingState = client.Blocking;
try
{
byte [] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
Console.WriteLine("Connected!");
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
Console.WriteLine("Still Connected, but the Send would block");
else
{
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
}
finally
{
client.Blocking = blockingState;
}
Console.WriteLine("Connected: {0}", client.Connected);
</code></pre>
<p>I've tried using it in my TCP client to detect disconnection from server. My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.</p>
<p>I'm asking anyone who tried using this method to share experiences and maybe help make it more robust.</p>
|
[] |
[
{
"body": "<p>First off, I'm not an expert about TCP and Sockets, though I have had some experiences in the past.</p>\n\n<blockquote>\n <p>My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.</p>\n</blockquote>\n\n<p>If you have a client-server scenario, then one will never ever know about what is the state of the other without <strong>explicitly finding out</strong>! </p>\n\n<p>Say you open the connection, client is idle for 10 seconds and now suddenly the client loses all power. The server doesn't know that the client lost it's power, the client didn't send a disconnect signal, the client was in an idle state so there is no sending/receiving that cut out midway or timed out. The only way for the server to know what is the state of the client on the 11-th second (for instance) is to query/ping the client. The term <strong>Keep-Alive</strong> applies here, although I can't think of good wording for it right now...</p>\n\n<blockquote>\n <p>I'm asking anyone who tried using this method to share experiences and maybe help make it more robust</p>\n</blockquote>\n\n<p>The state of the problem isn't currently very clear to me. In what specific scenario does the problem exist? When you remove the LAN cable? When you close the client application?</p>\n\n<p>So what, if the connection on the server is left hanging? You have to account for such a very likely possibility. You will need to apply some sort of timeout or keep-alive methodology, inorder to keep the server from hanging on to the connection indefinently and thus consuming and running out of resources. Accounting for all possible scenarios - <strong>that is robustness!</strong></p>\n\n<p>As I said, I'm no expert, so I won't be able to tell you exactly which <code>Socket</code> class properties or methods to apply to your code to help you make it more robust. But I will say this, your code example is missing <code>Disconnect() / Close()</code> statements, most likely even <code>using</code> statements. I see no timeouts being applied, surely the <code>Connect() and Send()</code> methods have some sort timeout mechanism (maybe a property, eg <code>client.SendTimeout</code>)...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T08:22:39.997",
"Id": "48225",
"Score": "0",
"body": "It is not 'the' TCP management code contained in this code example. I've actually cut out this part from MSDN documentation and I'm interested in it as 'first base' method to detect disconnects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T17:53:37.510",
"Id": "48309",
"Score": "0",
"body": "@Bizniztime - Ok, that explains why your code example does not have Disconnect() or using elements. But my previous statements still stand. You cannot find out about the (dis-)connected state of the other party without explicit action - either via Keeo-Alive, timeouts, ping or other mechanism..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T07:53:50.943",
"Id": "48477",
"Score": "0",
"body": "I agree with you completley. This code is supposed to be some sort of a ping method but from my experience it fails completley even in that one function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T16:11:32.240",
"Id": "30141",
"ParentId": "29550",
"Score": "2"
}
},
{
"body": "<p>I've found <em>Connected</em> property that is used in this code to be highly unreliable. It should reflect last known state of connection based on success of package sent or retrieved but it is affected by some other underlying mechanics and it gives continuous false readings in some network arrangements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T08:06:56.610",
"Id": "30494",
"ParentId": "29550",
"Score": "0"
}
},
{
"body": "<p>I ran into a similar problem on the client side using that code. Instead I switched from testing a non-blocking send to checking the number of bytes read from a receive request. If it returns zero bytes then the connection is closed. I found this to be far more reliable. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T19:56:41.900",
"Id": "32041",
"ParentId": "29550",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T10:19:20.077",
"Id": "29550",
"Score": "2",
"Tags": [
"c#",
".net",
"socket",
"tcp"
],
"Title": "Detecting socket disconnect in .NET"
}
|
29550
|
<p>I have an Eclipse plugin which creates a <code>JavaSourceViewer</code> to visualize specific source code in a separate view.
I would like to configure the font of the viewer to match the settings of the <em>Java Editor Text Font</em> preference:</p>
<pre><code>JavaSourceViewer textViewer = new JavaSourceViewer(...);
...
// get the SWT component which displays the text
StyledText textControl = textViewer.getTextWidget();
// retrieve the font preference from the theme manager
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
FontRegistry fontRegistry = currentTheme.getFontRegistry();
Font font = fontRegistry.get(PreferenceConstants.EDITOR_TEXT_FONT);
// set the font on the SWT component
textControl.setFont(font);
</code></pre>
<p>My question is especially about the code block which retrieves the font from the theme manager:</p>
<ul>
<li>Is this the correct approach to get the font?</li>
<li>Is there anything else which needs to be considered?</li>
</ul>
|
[] |
[
{
"body": "<p>I'm not familiar with Eclipse plugin development, so just two minor notes after going through javadoc of the relevant APIs:</p>\n\n<ol>\n<li><p><a href=\"http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/resource/FontRegistry.html\" rel=\"nofollow\"><code>FontRegistry</code></a> has an <code>addListener</code> method which you might want and/or need to listen to and change the font of the <code>textControl</code> when the user changes their font settings.</p></li>\n<li><p>The comment could be a great method name here (<code>retrieveFontPreference</code>, for example):</p>\n\n<blockquote>\n<pre><code>// retrieve the font preference from the theme manager\nIThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();\nITheme currentTheme = themeManager.getCurrentTheme();\nFontRegistry fontRegistry = currentTheme.getFontRegistry();\nFont font = fontRegistry.get(PreferenceConstants.EDITOR_TEXT_FONT);\n</code></pre>\n</blockquote>\n\n<p>See also: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Bad Comments</em>, p67: <em>Don’t Use a Comment When You Can Use a Function or a Variable</em></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T15:35:56.007",
"Id": "44983",
"ParentId": "29554",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T13:24:47.657",
"Id": "29554",
"Score": "3",
"Tags": [
"java",
"eclipse"
],
"Title": "Retrieving font preference setting in Eclipse JDT plugin"
}
|
29554
|
<p>I am building a PHP framework and would like to get some feedback on a few different sections of the project so far. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing these different tasks in an efficient and or correct way. </p>
<p>This section is of the MySQL database interaction classes I have created for it. I thought is would be best to divide its processes into two different part. The Database class; which over sees the connection to the the database and the DBcontrol class; which over see the interaction with the database, the querying.</p>
<p>I am trying to create the classes so their methods and returned values and be easily worked on the on with PHP's MySQL API. My reason from creating these classes is to offer easy interaction with the database when working with the framework.</p>
<p>My question is if this is a good way to build this type of function/feature? I am open to any tip, tricks, suggestions and advice.</p>
<p>I have include the code for the Database and DBcontrol classes below. </p>
<p><strong>Database class</strong> </p>
<pre><code>class Database{
protected $connection = array();
protected $activeConnection = 0;
//Not in use
protected $lastactiveConnection;
public function __construct(){
//Empty
}
/**
* Change the select DB of the selected DB connection
* @param Int $connection_id - Index of DB connection
* @param String $database - name of DB to select
* @return Null
*/
public function ChangeSelectedDB($connection_id,$database){
if(array_key_exists($connection_id, $this->connection)){
if($this->connection[$connection_id]->select_db($database)){
}else{
trigger_error('Unable to change selected database', E_USER_ERROR);
}
}else{
trigger_error('Unable to find connection Index', E_USER_ERROR);
}
}
/**
* Create a new mysqli object using the parameters supplied
* @param String $host, $user, $pass, $batabase - Required DB connection information
* @return Index number of the current connection ID
*/
public function CreateConnection($host,$user,$pass,$batabase){
$this->connection[] = @new mysqli($host,$user,$pass,$batabase);
//Connection index
$currentconnect_id = count($this->connection)-1;
if(mysqli_connect_errno()){
trigger_error('Class Error: Unable to connect to database'.$this->connection[$currentconnect_id]->error, E_USER_ERROR);
}
//Set activeConnection to most recently created connection
//Using this method
$this->activeConnection = $currentconnect_id;
return $currentconnect_id;
}
/**
* Set DB connection currently being used
* @param Int $connection_id - Index number of DB connection to set to
* @return Null
*/
public function SetActiveConnection($connection_id){
if(array_key_exists($connection_id, $this->connection) || is_integer($connection_id)){
$this->activeConnection = $connection_id;
}else{
trigger_error('Connection does not exists',E_USER_ERROR);
}
}
/**
* Get and return active db connection
* @param Null
* @return active connection
*/
public function GetActiveConnection(){
//Check using empty because $connection is set to 0
if(!empty($this->activeConnection)){
return $this->connection[$this->activeConnection];
}else{
trigger_error('A connection is not set',E_USER_ERROR);
}
}
/**
* Close selected DB connection
* @param Null
* @return Null
*/
public function CloseActiveConnection(){
$this->connection[$this->activeConnection]->close();
}
/**
* Returns number of the current active
* @param Null
* @return Int index of the active DB connection
*/
public function ShowActiveConnection(){
echo "Current Connection index[".$this->activeConnection."]";
}
public function __destruct(){
foreach ($this->connection as $connection) {
$connection->close();
}
}
}
</code></pre>
<p><strong>DBcontrol Class</strong><br>
The DBcontrol class extends the Database Class </p>
<pre><code>include_once('database.object.php');
class DBControl extends Database{
//Array of cached queries
private $cacheQuery = array();
public function __constuct(){
//Empty
}
/**
* Stores an query in cacheQuery array
* @param Query String $query - query sent to DB
* @return Index number of the cached query
*/
public function CacheQuery($query){
if($result = $this->connection[$this->activeConnection]->query($query)){
$this->cacheQuery[] = $result;
//Number if it's index
$index = count($this->cacheQuery)-1;
return $this->cacheQuery[$index];
}else{
trigger_error('Unable to send or cache query',E_USER_ERROR);
return false;
}
}
/**
* Returns a query stored in the cacheQuery array
* @param Int $cache_id - Index number of cached query
* @return The cached query
*/
public function GetCacheQuery($cache_id){
if(array_key_exists($cache_id, $this->cacheQuery)){
return $this->cacheQuery[$cache_id];
}else{
trigger_error('Cache ID does not exists',E_USER_ERROR);
return false;
}
}
/**
* Returns a cached query array as an associative, numeric array, or both
* @param Int $cache_id - Index number of cached query
* @param Parameter $resulttype - Retruned result type default MYSQLI_BOTH
* @return Cached query in result type chosen
*/
public function GetCacheQueryArray($cache_id,$resulttype = MYSQLI_BOTH){
if(array_key_exists($cache_id, $this->cacheQuery)){
return $this->cacheQuery[$cache_id]->fetch_array($resulttype);
}else{
trigger_error('Cache ID does not exists',E_USER_ERROR);
return false;
}
}
/**
* Debugging method
* @param Null
* @return var_dum of the cachedQuery array
*/
public function ShowCache(){
echo '<pre>';
print_r($this->cacheQuery);
echo '</pre>';
}
/**
* Returns number of rows changed in DB when using RunnQuery() method
* Note: Only use after a query has been sent
* @param Null
* @return Number of row changed
*/
public function AffectedRows(){
return $this->connection[$this->activeConnection]->affected_rows;
}
public function __destruct(){
parent::__destruct();
}
}
</code></pre>
<p>Here is an example if using the classes methods </p>
<pre><code>//Create Connection
$dbcontrol = new DBControl();
//Returns 0 for connection ID to be used for
//methods SetActiveConnection and ChangeSelectedDB
$connectionID1 = $dbcontrol->CreateConnection('localhost','root','password','splice_app');
//Send first cache query
//$query1 holds results
$query1 = $dbcontrol->CacheQuery('SELECT * FROM app_state LIMIT 10');
//Change database but use same user connection cred
$dbcontrol->ChangeSelectedDB($connectionID1,'dummy');
//Send second cache query
//$query2 holds results
$query2 = $dbcontrol->CacheQuery('SELECT * FROM post');
//Get cached queries
$cachedquery1 = $dbcontrol->GetCacheQueryArray(0);
$cachedquery2 = $dbcontrol->GetCacheQueryArray(1);
//Combine $cachedquery1 and $cachedquery2 if needed
//using the cached queries is the same as
//using $query1 and $query2
$combinequeries = array_merge($cachedquery1,$cachedquery2);
//Change DB connection
//automatically set connection to be used
$connectionID2 = $dbcontrol->CreateConnection('127.0.0.1','root','password','gencore');
//Send third cache query using new connection
//$query3 holds results
$query3 = $dbcontrol->CacheQuery('SELECT * FROM logqueries');
//Switch back to first connection
//Using localhost, root, password, splice_app
$dbcontrol->SetActiveConnection($connectionID1);
</code></pre>
<p>My question is if this a good way to go about created a database interaction class.</p>
<p><strong>Thank you for taking the time to read my question.</strong></p>
|
[] |
[
{
"body": "<p>Always think this: everything you code must solve some kind of problem.\nIf it doesn't solve a problem. Remove it.</p>\n\n<p>Now by looking at your code I think you are trying to solve two problems being:</p>\n\n<ol>\n<li>Handling of multiple connections</li>\n<li>Caching query results for later use</li>\n</ol>\n\n<p>Let's define each problem so that it is easy to use, easy to extend and easy to code.\nAlso note that in every step of writing code you should be sure to not restrict anything. It will become clear what I mean here.</p>\n\n<p><strong>1. Handling of multiple databaseconnections</strong></p>\n\n<p>We have a <code>DatabaseConnectionHandler</code> that handles <code>DatabaseConnection</code>'s. Allready a vague word: 'handles'. So let's define it:\nA <code>DatabaseConnectionHandler</code> should be able to keep track of all current DatabaseConnection's. You can add, remove and get <code>DatabaseConnection</code>'s from the <code>DatabaseConnectionHandler</code>.</p>\n\n<p>A simple DatabaseConnectionHandler would look something like this:</p>\n\n<pre><code><?php\n\nclass DatabaseConnectionHandler {\n\n private $connections;\n\n public function addConnection(String $connectionName, DatabaseConnection $connections) {\n $this->connection[$connectionName] = $connections;\n }\n\n public function removeConnection(String $connectionName) {\n unset($this->connection[$connectionName]);\n }\n\n public function getConnection($connectionName) {\n return $this->connection[$connectionName];\n }\n\n}\n</code></pre>\n\n<p>We also mentioned a <code>DatabaseConnection</code>. This class obviously represents a <code>DatabaseConnection</code>. This is very vague, so we have to keep the methods 'vague'. Make sure we don't restrict anything. mysqli_* isn't the only way to connect to a database.</p>\n\n<p>Now, what should a DatabaseConnection be able to do? Obviously you need to be able to query it. A nice plus would be to be able to open and close it. so a DatabaseConnection would look something like this:</p>\n\n<pre><code><?php\n\nclass DatabaseConnection {\n\n public function query($query) {}\n\n public function close() {}\n\n public function open() {}\n\n}\n</code></pre>\n\n<p>But hmm, because this is such a Generic class and in fact it shouldn't really exist on its own. It's more an abstract class. So let's fix that:\n \n\n<pre><code>abstract class DatabaseConnection {\n\n public abstract function query($query);\n\n public abstract function close();\n\n public abstract function open();\n\n}\n</code></pre>\n\n<p>Ofcourse, our program needs to be able to communicate with a mysql connection. So we need to write a DatabaseConnection class that handles all that stuff. But, lucky us mysqli_* can do all the heavy lifting for us. We only have to write an adapter for it that extends the DatabaseConnection. this would look something like this:</p>\n\n<pre><code><?php\n\nclass MysqliDatabaseConnection extends DatabaseConnection {\n\n private $host;\n\n private $user;\n\n private $pass;\n\n private $database;\n\n private $connection;\n\n public function __costruct($host,$user,$pass,$batabase) {\n $this->host = $host;\n $this->user = $user;\n $this->pass = $pass;\n $this->database = $database;\n }\n\n public function query($query) {\n $this->connection->query($query);\n }\n\n public function close() {\n return $this->connection->close();\n }\n\n public function open() {\n $this->connection = new mysqli($host,$user,$pass,$batabase);\n return !!$this->connection->connect_errno;\n }\n\n public function getError() {\n return $this->connection->connect_errno\n }\n}\n</code></pre>\n\n<p>now we could start using our classes as follows:</p>\n\n<pre><code><?php\n\n//create a DBC handler\n$myDatabaseHandler = new DatabaseConnectionHandler();\n\n//add some db connections\n$myDatabaseHandler->addConnection(\n 'foo',\n new MysqliDatabaseConnection('localhost','root','password','splice_app')\n);\n$myDatabaseHandler->addConnection(\n 'bar',\n new MysqliDatabaseConnection('127.0.0.1','root','password','gencore')\n);\n\n//lets open both connections\n$myDatabaseHandler->getConnection('foo')->open();\n$myDatabaseHandler->getConnection('bar')->open();\n\n//lets query the first one\n$resultFirstQuery = $myDatabaseHandler->getConnection('foo')->query(\"SELECT * FROM app_state LIMIT 10\");\n\n//lets query the second one\n$resultSecondQuery = $myDatabaseHandler->getConnection('bar')->query(\"SELECT * FROM logqueries\");\n</code></pre>\n\n<p>Now this is neat, clean. And if I would like to change mysqli_ to PDO. I wouldn't have to change my entire application. I simply create PDODatabaseConnection class and insert that into the handler instead of mysqli variant.</p>\n\n<p>Other application also don't have to know what the connectionID is. They only need a name (foo and bar in my example).</p>\n\n<p>The next part would be to add caching of queries. This can be done at different levels in the application depending on your need.</p>\n\n<p>But then again, if you really need caching of queries, maybe you shouldn't request the same thing all over your application. Caching wil then not be the answer, just a fix.</p>\n\n<p>I hope you learned something out of my code. Good luck!</p>\n\n<p>And as a last thing, enjoy this link: <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29</a></p>\n\n<p>Some notes: Is my code picture perfect? no. Not at all. Is it production ready? no, not at all. you probably would add some error handling. throw exceptions if the open() fails etc etc</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T17:02:28.340",
"Id": "46760",
"Score": "0",
"body": "thank you for your helpful answer. If I understand correctly it's best to keep the db control/handling class(es) abstract and only add the functionality in which the application will need to complete it's different tasks and that the mysqli_ library does not offer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T21:48:44.597",
"Id": "46780",
"Score": "1",
"body": "A classname should always represent what it does. If it says DatabaseConnectionHandler it should handle DatabaseConnection. This is very vague so the class should be very abstract. You then create child classes that add functionality and limit the scope it can be used. This is the Open/closed principle of Solid: http://en.wikipedia.org/wiki/Open/closed_principle"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-04T00:07:16.193",
"Id": "143934",
"Score": "0",
"body": "There is an error with the first code block. There is no `String` type-hint in PHP. Now PHP assumes a `string` class exists and expects the arguments to of such type. Only classes, abstract classes, interfaces and arrays can be type-hinted."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T16:11:38.040",
"Id": "29560",
"ParentId": "29555",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29560",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T13:38:56.123",
"Id": "29555",
"Score": "3",
"Tags": [
"php",
"design-patterns",
"mysql"
],
"Title": "PHP framework building: Database Control Classes"
}
|
29555
|
<p>I'm looking to let people define arbitrarily nested lists of lists and return a random json document for them. Right now the assumption is that if you have a structure like this:</p>
<pre><code>[item1, item2, [item3, item4]]
</code></pre>
<p>The desired document is:</p>
<pre><code>{item1: value,
item2: {
item3: value,
item4: value
}
}
</code></pre>
<p>This is my current solution:</p>
<pre><code>def random_document(document_layout, type_, **kwargs):
document_layout.append("dummy_item")
doc = lambda l:{l[i]:doc(l[i+1]) if isinstance(l[i+1],list) else random_item(type_,**kwargs) for i in range(len(l)-1)}
return doc(document_layout)
</code></pre>
<p>as a one line fetishist, I feel like the middle line is beautiful, but I think the general hack of adding a dummy element to the end is hackish. Any thoughts on how to make this more elegant?</p>
<p>Also, not looking for deeply readable, this is just for my own private use and isn't going to spread out in any meaningful way, so I would just like to preempt the commentary about it not being readable.</p>
<p>Here's a more "readable" version:</p>
<pre><code>def random_document(document_layout, type_, **kwargs):
document_layout.append("dummy_item")
full_dict = {}
def internal_comprehension(document):
for i in range(len(document)-1):
if isinstance(document[i+1], list):
full_dict.update({document[i]: internal_comprehension(document[i+1])})
else:
full_dict.update({document[i]: random_item(type_, **kwargs)})
return internal_comprehension(document_layout)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T14:37:49.763",
"Id": "46753",
"Score": "0",
"body": "Your understanding of elegant code is so different, that I can't improve your solution. However, variable named 'type' is not a good idea, because it shadows built-in function type()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T14:44:29.390",
"Id": "46754",
"Score": "0",
"body": "@RomanSusi It's not my understanding of elegant that's different, it's my understanding of readable. The solution for the problem is elegant regardless, the difference is that most people wouldn't find it as readable as I do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T16:47:39.087",
"Id": "46758",
"Score": "0",
"body": "Perhaps in Python elegance can't be achieved without readability unless you are participating in shortest program contest. Thanks for the normal version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T16:49:32.267",
"Id": "46759",
"Score": "0",
"body": "@RomanSusi Different strokes for different folks. I'm not going to argue since I already addressed this argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T14:56:21.407",
"Id": "46811",
"Score": "0",
"body": "Could you give a example of how `random_document` is called? I can't see how you can include a `list` in the layout and not end up with an _unhashable type: list_ exception."
}
] |
[
{
"body": "<p>The only idea, which comes to my mind, is to replace</p>\n\n<pre><code>for i in range(len(document)-1)\n</code></pre>\n\n<p>with </p>\n\n<pre><code>for (l, l1) in zip(document, document[1:])\n# or izip from itertools\n</code></pre>\n\n<p>to get pairs of consecutive items.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-10T11:21:28.740",
"Id": "49417",
"Score": "0",
"body": "Do not use `l`(lowercase L) as a variable name. Also, it doesn't make much sense to use `itertools.izip` in that code, since `document[1:]` is already copying the list. Use `iterable = iter(document); for a, b in zip(iterable, iterable):`. Or you can use `itertools.islice` to get two iterables on even and odd indexes and `zip` them together."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T16:44:52.340",
"Id": "29562",
"ParentId": "29557",
"Score": "0"
}
},
{
"body": "<p>Your one-liner is too unreadable for my taste. Furthermore, neither version actually works.</p>\n\n<p>The fundamental obstacle to elegance is that the problem requires you to look ahead one element to interpret how to handle the current element.</p>\n\n<pre><code>def random_document(document_layout, type_, **kwargs):\n def internal_comprehension(document):\n full_dict = {}\n for i in range(len(document)):\n if isinstance(document[i], list):\n # This item should have already been processed in a previous\n # recursive call to internal_comprehension()\n pass\n elif i == len(document) - 1 or not isinstance(document[i+1], list): \n # This item is an independent item\n full_dict.update({document[i]: random_item(type_, **kwargs)}) \n else:\n # Next item is a list, so create a level of nesting\n full_dict.update({document[i]: internal_comprehension(document[i+1])}) \n return full_dict\n return internal_comprehension(document_layout)\n</code></pre>\n\n<p>On the other hand, if you iterate through the <code>document_layout</code> backwards, then you don't have a look-ahead problem. Here's how it could look like:</p>\n\n<pre><code>def random_document(document_layout, type_, **kwargs):\n dict = {}\n iter = reversed(document_layout)\n for k in iter:\n if isinstance(k, list):\n dict[iter.next()] = random_document(k, type_, **kwargs)\n else:\n dict[k] = random_item(type_, **kwargs)\n return dict\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-10T11:23:25.563",
"Id": "49418",
"Score": "0",
"body": "You can remove `isinstance` and use duck-typing: `try: dict[k] = random_item(type_, **kwargs) except TypeError: dict[iter.next()] = random_document(k, type_, **kwargs)` which uses the fact that `list`s aren't hashable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T01:12:12.683",
"Id": "29601",
"ParentId": "29557",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29601",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T14:25:21.943",
"Id": "29557",
"Score": "3",
"Tags": [
"python",
"recursion",
"comparative-review",
"hash-map"
],
"Title": "Nested array-to-dict transformation"
}
|
29557
|
<p>I am quite new to <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="nofollow">Java</a>. I have data structured like this:</p>
<pre><code>tree 503(there is a null character here)040000 tree 0bfec80bc7b7aa0a50e0b373044929cb0aae278b build/
100755 blob e30876c61eb7712ad09b50593a30513d9b173805 build.xml
100755 blob 1574df4a2de5d2884f33a5d3e30ae3daa5affee1 manifest.mf
040000 tree fdab6a12a56a709212f105c9c8e31cd062d01e0a nbproject/
040000 tree 3c977009b6104310d7f3a66200f29bff8cda7576 src/
100755 blob de4bcf5c862c352531819e082204bb51ddabaa9c test_file
100755 blob 26af8cac3b104b4b6514621b1c512e353307a867 unicode.txt
</code></pre>
<p>I call each line of this an entry. To parse this data into an array of entries, I wrote this;</p>
<pre><code>class TreeEntry {
public String perms;
public String type;
public String hash;
public String name;
@Override
public String toString() {
return perms + " " + type + " " + hash + " " + name;
}
}
private static TreeEntry[] parseTree(String hash) {
String tree = readObject(hash);
if (!tree.startsWith("tree")) {
System.err.println("Given hash doesn't belong to a tree object");
return null;
}
int currentArrayCapacity = 4;
int currentEntries = 0;
TreeEntry[] entries = new TreeEntry[currentArrayCapacity];
// We are interested in data after null character
int nullCharacterPosition = 0;
while (tree.charAt(nullCharacterPosition) != '\0') {
nullCharacterPosition++;
}
tree = tree.substring(nullCharacterPosition + 1);
StringTokenizer st = new StringTokenizer(tree, "\n");
while (st.hasMoreElements()) {
TreeEntry e = new TreeEntry();
StringTokenizer st2 = new StringTokenizer((String)st.nextElement(), " ");
e.perms = (String) st2.nextElement();
e.type = (String) st2.nextElement();
e.hash = (String) st2.nextElement();
e.name = (String) st2.nextElement();
// There can be space in name
while (st2.hasMoreElements()) {
e.name += " " + (String) st2.nextElement();
}
currentEntries++;
// To increase capacity of the array
if (currentEntries > currentArrayCapacity) {
currentArrayCapacity = currentArrayCapacity * 2;
TreeEntry[] tmp = new TreeEntry[currentArrayCapacity];
System.arraycopy(entries, 0, tmp, 0, entries.length);
entries = tmp;
}
entries[currentEntries - 1] = e;
}
return entries;
}
</code></pre>
<p>How does it look as a Java code, and how does it look data structures and algorithms wise?</p>
|
[] |
[
{
"body": "<p>I'll first suggest you that the raw format that you use to store your data, use a different separator than a white-space. This will simplify the code since we are sure that we have unique separator.</p>\n\n<p>Your <code>TreeEntry</code> should encapsulate his fields in getter and setter. Public field in a class is not something that you want to do in a OOP program. You should always limit the scope of your variable. Your <code>TreeEntry</code> class should look like : </p>\n\n<pre><code>class TreeEntry {\n\n private String perms;\n private String type;\n private String hash;\n private String name;\n\n @Override\n public String toString() {\n return perms + \" \" + type + \" \" + hash + \" \" + name;\n }\n\n public String getPerms() {\n return perms;\n }\n\n public void setPerms(String perms) {\n this.perms = perms;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getHash() {\n return hash;\n }\n\n public void setHash(String hash) {\n this.hash = hash;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}\n</code></pre>\n\n<p>For the parsing part, I will use a different format than yours. I use the <code>;</code> character to separate each \"column\" of the data. The format would look like :</p>\n\n<pre><code>tree;503(null)040000;tree;0bfec80bc7b7aa0a50e0b373044929cb0aae278b;build/\n100755;blob;e30876c61eb7712ad09b50593a30513d9b173805;build.xml\n100755;blob;1574df4a2de5d2884f33a5d3e30ae3daa5affee1;manifest.mf\n040000;tree;fdab6a12a56a709212f105c9c8e31cd062d01e0a;nbproject/\n</code></pre>\n\n<p>I've changed a lot of things in the <code>parseTree()</code> method so I'll drop the new method and I'll explain later what are the changes and why.</p>\n\n<pre><code>private static List<TreeEntry> parseTree(String hash) {\n String tree = readObject(hash);\n\n if (!tree.startsWith(\"tree\")) {\n System.err.println(\"Given hash doesn't belong to a tree object\");\n return null;\n }\n\n List<TreeEntry> entries = new LinkedList<>();\n\n // // We are interested in data after null character\n int nullCharacterPosition = tree.indexOf(\"\\0\");\n tree = tree.substring(nullCharacterPosition + 1);\n\n String[] dataTree = tree.split(\"\\n\");\n\n for (String entry : dataTree) {\n TreeEntry e = new TreeEntry();\n String[] args = entry.split(\";\");\n e.setPerms(args[0]);\n e.setType(args[1]);\n e.setHash(args[2]);\n e.setName(args[3]);\n entries.add(e);\n }\n\n return entries;\n}\n</code></pre>\n\n<p>If you want to find the null character, you should use <code>indexOf</code>, this will do the loop for you and will return the index of the first character corresponding. Since I don't have an input with a null value, I've not tested my code to find the null character. So be sure to verify this part.</p>\n\n<p>I've also changed the type of <code>entries</code> to a <code>List</code>. I've choose a <code>LinkedList</code> since all the operation I'm doing is adding new entries, and you'll probably iterate over it later. This allow to focus on the task of parsing and I don't have to manage the array (I don't have to check the size before adding something).</p>\n\n<p>I've used the <code>spilt()</code> method instead of the <code>StringTokenizer</code>. I've find it easy to operate in conjunction with a <code>for-each</code> loop, and you don't seems to want to work with anything than <code>String</code>, so <code>split()</code> is perfect for that. I'll point you to this <a href=\"https://stackoverflow.com/q/691184/2115680\">question</a> for further information on why I would not use <code>StringTokenizer</code>, read the second answer.</p>\n\n<p>It seems rather odds to me that the parsing method is static. I don't know where the method is called, but I would have go with something like a factory or utility class to do the parsing job. </p>\n\n<p>PS: This is my first review, so if this is not a good format or there is some inaccuracy let me know.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T23:37:08.000",
"Id": "46783",
"Score": "0",
"body": "Thanks a lot, your review is very through. Especially, List usage, indexof and split usage thought me something new. I have doubts about getters and setters though. I wrote that class just to hold some data (like a struct in C) and public fields seemed pretty short and simple way to do it. The function is in a utility class as you guessed, so making it static made sense to me. Plus, it doesn't access any field of the class, so why not make it static, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T23:46:32.337",
"Id": "46784",
"Score": "0",
"body": "I'll agree with you for the static part. If it's a utility class I got no problem with that. You'll probably don't have the need to extend that class. If you're simply holding data, you can make the field private and use it in the class. That way you can encapsulate thing, but you still have access to the fields. Read a bit of this question http://stackoverflow.com/q/1801718/2115680"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T22:08:26.767",
"Id": "29570",
"ParentId": "29564",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29570",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T18:38:53.937",
"Id": "29564",
"Score": "3",
"Tags": [
"java",
"beginner",
"parsing",
"tree"
],
"Title": "Parsing structured text in Java"
}
|
29564
|
<p>I've been working on a jQuery plugin for pulling tweets since the v1 endpoints were all closed off and you need oAuth now. This is just the jQuery part but if you want to see the php behind it I'll be happy to post. But basically, I'd love suggestions, as this is one of the first real plugins i've made, i'm really looking for critique on patterns and efficiency. Is there anything I'm doing that can be shorten'd significantly? Is there a feature you think would be cool for me to include?</p>
<p>And just FYI, there is an oAuth/twitter library that authenticates everything first and pulls, and the php file my ajax call references holds the logic for all that and creating / serving the json, but it's not that exciting.</p>
<p>I'm going to post the plugin with the documentation comments I have in there, to see if it all makes sense to people who have never seen it. All opinions and comments welcome, I want to write better code!</p>
<pre><code>/*************************************
Invisible Tweets
Author : Shan Robertson
Website: http://invisibled.com
Version: 1.0
Updated: August 7th, 2013
Description:
This plugin allows you to simply display Twitter timelines & lists on your website.
It caches the twitter content in a json file & changing the cache name will
allow you to have as many instances of Invisible Tweets as you want.
Dependancies:
- jQuery
- invisibletweets.php (included)
- OAuth.php (included)
- twitteroauth.php (included)
- invisibletweets/cache folder (must be writable)
Options:
user : [string] - The desired Twitter username.
slug : [string] - The slug to your Twitter list.
cache : [string] - The cache name, if dealing with multiple feeds.
path_to_core : [string] - Path to the invisibletweets folder.
expire : [string] - Cache expire time, uses default PHP time syntax eg. 15 minutes, 10 seconds.
Warning: If expire time is shorter than 15 minutes, you may hit the rate limit.
type : [string] - Choose what feed to display. Displaying a 'list' requires the 'slug' option to be set to your list's slug.
Options: 'timeline' or 'list'
template : [string] - Comma delimited string of what elements to show and in what order.
Options: 'name, avatar, date, time, text, btn_tweet, btn_retweet, btn_favorite'
limit : [integer] - Number of tweets to return.
retweets : [boolean] - Show retweets.
Options: true/false
clear : [boolean] - Clears the cache.
Options: true/false
TO DO
- wordpress plugin version
*************************************/
;(function ( $, window, document, undefined ) {
/*************************************
Plugin Functions
*************************************/
/*************************************/
Plugin.prototype.init = function () {
var params = [ '?user=' + this.options.user,
'&limit=' + this.options.limit,
'&type=' + this.options.type,
'&slug=' + this.options.slug,
'&cache=' + this.options.cache,
'&expire=' + this.options.expire,
'&clear=' + this.options.clear,
'&retweets=' + this.options.retweets
].join('\n');
$.ajax({
url: this.options.path_to_core + 'invisibletweets.php' + params,
context: this,
dataType: 'json',
success: function(data){
// If the errors object is returned, show the error and exit the script
if(data.errors){
$(this.element).html("Fatal Error: " + data.errors[0].message);
return false;
}
// Variables
var scope = this;
var parent = this.element;
var tpl = "";
var tplArray = scope.options.template.replace(/[\s,]+/g, ',').split(',');
// Creates an empty template with all present data, in order.
$.each(tplArray, function(i, elm){
if(elm == 'name'){
tpl = tpl + '<div class="it_name"><a href="" target="_blank"></a></div>';
} else if(elm == 'avatar'){
tpl = tpl + '<div class="it_avatar"><a href="" target="_blank"><img src="" /></a></div>';
} else if(elm == 'date'){
tpl = tpl + '<div class="it_date"></div>';
} else if(elm == 'time'){
tpl = tpl + '<div class="it_time"></div>';
} else if(elm == 'text'){
tpl = tpl + '<div class="it_text"><p></p></div>';
} else if(elm == 'btn_tweet'){
tpl = tpl + '<a href="http://twitter.com/intent/tweet?in_reply_to=" target="_blank" class="it_btn_tweet">Tweet</a>';
} else if(elm == 'btn_retweet'){
tpl = tpl + '<a href="http://twitter.com/intent/retweet?tweet_id=" target="_blank" class="it_btn_retweet">Retweet</a>';
} else if(elm == 'btn_favorite'){
tpl = tpl + '<a href="http://twitter.com/intent/favorite?tweet_id=" target="_blank" class="it_btn_favorite">Favorite</a>';
}
});
//Populates the template with data
$.each(data, function(i, item){
// Variables
var text = scope.findLinks(item.text);
var date = scope.dateTime(item.created_at, 'date');
var time = scope.dateTime(item.created_at, 'time');
var profile_url = 'http://twitter.com/' + item.user.screen_name;
var thisTweet = ".it_tweet:eq("+i+") ";
// Creates a searchable object of the template
$(parent).append('<div class="it_tweet">' + tpl + '</div>');
//If in array, show, else don't show, for each item.
if(tplArray.indexOf('name') != -1){
$(thisTweet + ".it_name a").attr("href", profile_url).html(item.user.name);
}
if(tplArray.indexOf('avatar') != -1){
$(thisTweet + ".it_avatar").find('a').attr("href", profile_url).find('img').attr("src", item.user.profile_image_url);
}
if(tplArray.indexOf('date') != -1){
$(thisTweet + ".it_date").html(date);
}
if(tplArray.indexOf('time') != -1){
$(thisTweet + ".it_time").html(time);
}
if(tplArray.indexOf('text') != -1){
$(thisTweet + ".it_text p").html(text);
}
if(tplArray.indexOf('btn_tweet') != -1){
$(thisTweet + ".it_btn_tweet").attr("href", 'http://twitter.com/intent/tweet?in_reply_to=' + item.id);
}
if(tplArray.indexOf('btn_retweet') != -1){
$(thisTweet + ".it_btn_retweet").attr("href", 'http://twitter.com/intent/retweet?tweet_id=' + item.id);
}
if(tplArray.indexOf('btn_favorite') != -1){
$(thisTweet + ".it_btn_favorite").attr("href", 'http://twitter.com/intent/favorite?tweet_id=' + item.id);
}
}); //each
} //success
}); //ajax
}; //init
/*************************************/
Plugin.prototype.findLinks = function(tweet){
var text = tweet;
text = text.replace(/http:\/\/\S+/g, '<a href="$&" target="_blank">$&</a>');
text = text.replace(/\s(@)(\w+)/g, ' @<a href="http://twitter.com/$2" target="_blank">$2</a>');
text = text.replace(/\s(#)(\w+)/g, ' #<a href="http://twitter.com/search?q=%23$2" target="_blank">$2</a>');
return text;
}; //findLinks
/*************************************/
Plugin.prototype.dateTime = function(created_at, select){
var dateTime = created_at;
var strtime = dateTime.replace(/(\+\S+) (.*)/, '$2 $1')
var date = new Date(Date.parse(strtime)).toLocaleDateString();
var time = new Date(Date.parse(strtime)).toLocaleTimeString();
if(select == 'date'){
return date;
} else if(select == 'time'){
return time;
}
}; //dateTime
/*************************************
Plugin Setup
*************************************/
var pluginName = 'invisibleTweets',
// Options for the plugin
defaults = {
user : 'RobGronkowski', // Twitter username
limit : 10, // Number of tweets
type : 'timeline', // Feed select, can be timeline/list
slug : '', // For lists
cache : 'default', // The cache name if dealing with multiple feeds
expire : '15 minutes', // The time it takes the cache to expire
clear : false, // Clears the cache.
retweets : true, // Show retweets
path_to_core: 'js/vendor/invisibletweets/', // Path to the invisibletweets folder.
template : 'name, avatar, date, time, text, btn_tweet, btn_retweet, btn_favorite' // Elements to show and in what order
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
// A really lightweight plugin wrapper around the constructor, preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:56:27.087",
"Id": "71914",
"Score": "0",
"body": "The big `if else` could be an `switch case`: http://stackoverflow.com/questions/2922948/javascript-switch-vs-if-else-if-else"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:59:15.783",
"Id": "72143",
"Score": "0",
"body": "Agreed, do you know if there are any benefits to using a switch case? I normally do it in situations like this because it looks cleaner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:19:59.810",
"Id": "72157",
"Score": "0",
"body": "See the accepted answer I posted above."
}
] |
[
{
"body": "<p>A few minor notes:</p>\n\n<ol>\n<li><p>Comments like this:</p>\n\n<blockquote>\n<pre><code>// Creates an empty template with all present data, in order.\n$.each(tplArray, function(i, elm){\n</code></pre>\n</blockquote>\n\n<p>and this:</p>\n\n<blockquote>\n<pre><code>//Populates the template with data\n$.each(data, function(i, item){\n</code></pre>\n</blockquote>\n\n<p>could be great function names. It would also increase the abstraction level of the code which helps maintainers with a quick overview about what the code does (without the details). They still can check the details inside the functions if they're interested in. It usually requires less code to understand (so it's faster and easier), especially if they want to modify only a small part of it.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>, p67.)</p></li>\n<li><blockquote>\n<pre><code>var scope = this;\nvar parent = this.element;\nvar tpl = \"\";\nvar tplArray = scope.options.template.replace(/[\\s,]+/g, ',').split(',');\n</code></pre>\n</blockquote>\n\n<p>I've found this kind of indentation hard to maintain. If you have a new variable with a longer name you have to modify several other lines too to keep it nice. It could also cause unnecessary patch/merge conflicts.</p></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs and editors could show blocks.</p>\n\n<blockquote>\n<pre><code>}; //findLinks\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/53274/36726\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:07:47.570",
"Id": "44660",
"ParentId": "29565",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T18:43:39.477",
"Id": "29565",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"plugin",
"twitter"
],
"Title": "Plugin for pulling Tweets"
}
|
29565
|
<p>I wrote the code for an iterative pre-order traversal using stack for binary search tree. Below is the code for same. Please help me verify the correctness of the algorithm. Here <code>t.t</code> is the value of node <code>t</code>.</p>
<pre><code>static void preorder(TreeNode t)
{
MyConcurrentStack<TreeNode> s = new MyConcurrentStack<TreeNode>();
while(s.peek()!=null || t!=null)
{
if(t!=null)
{
System.out.print(t.t+":");
s.push(t);
t = t.left;
}
else
{
t = s.pop();
t = t.right;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few points that can be critizised.</p>\n\n<ol>\n<li><p>The method signature suggests that the architecture of the system isn't well-designed. Traversal of a Tree should likely be encapsulated in an Iterator class. In that case, the stack would be a private field of the iterator, and the actual code would use a foreach loop.</p>\n\n<pre><code>for (TreeNode node : tree)\n System.out.print(node.t + \":\");\n</code></pre>\n\n<p>(preorder iteration is a good default)</p></li>\n<li><p>Even if we let the design of your classes as they are, your implementation could be improved.</p></li>\n</ol>\n\n<p>Single-letter variable names should be avoided. True, there are only two variables in your method, but using <code>node</code> and <code>stack</code> would be so much less cryptic.</p>\n\n<p>The stack does not have to be concurrent, because it is not shared accross multiple threads. The vanilla <code>java.util.Stack</code> should work just fine. If you care about concurrency, you should rather worry about the tree nodes. What happens when a node was stored on the stack, but removed from the tree before the right child can be consumed by your code? Make sure the nodes aren't mutated until you visited them.</p>\n\n<p>The body of your loop does not have a single comment although the stack manipulation may not be totally obvious to everybody (incl. you).</p>\n\n<p>If you are optimizing for readability and not for space, I'd strongly suggest a recursive solution. This also makes writing <em>correct</em> code much easier:</p>\n\n<pre><code>static void preorder(TreeNode node) {\n if (node == null) return;\n\n System.out.println(node.t + \":\");\n\n preorder(node.left);\n preorder(node.right);\n}\n</code></pre>\n\n<p>(Not that your code was incorrect, this is just much easier to verify).</p>\n\n<p>Next, I would like to reorder the parts of your loop to make it more obvious what is happening:</p>\n\n<pre><code>while (true)\n{\n // check if we have to pop a value of the stack\n while (node == null) {\n if (stack.empty()) return;\n node = stack.pop().right;\n }\n\n System.out.print(node.t + \":\");\n\n stack.push(node); // store the node to continue the right path later\n node = node.left;\n}\n</code></pre>\n\n<p>Note: If we use the <code>java.util.Stack</code>, then <code>peek()</code> could throw an EmptyStackException. We should rather use the <code>empty()</code> method which returns a boolean.</p>\n\n<p>I think it would be more elegant to put the right childs on the stack, not the nodes which we already visited. We should also test whether these are null before adding them to the stack. This would keep the stack smaller:</p>\n\n<pre><code>while (true)\n{\n // check if we have to pop a value of the stack WITHOUT LOOPING:\n // It is guaranteed that there never is a null node on the stack.\n if (node == null) {\n if (stack.empty()) return;\n node = stack.pop();\n }\n\n System.out.print(node.t + \":\");\n\n // store the right node to continue there later\n if (node.right != null) stack.push(node.right);\n\n node = node.left;\n}\n</code></pre>\n\n<p>I am not too comfortable with a <code>while (true)</code> loop, but the alternatives would mean slight code duplication (e.g. in your original code, you have two <code>t!=null</code> tests.)</p>\n\n<p>Finally, you likely want to print a newline after this iteration. (In that case, the <code>return</code> should be a <code>break</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-01T00:09:07.747",
"Id": "167636",
"Score": "0",
"body": "Agree in general but will question `for (TreeNode node : tree)` your varible `tree` seem to suggest that user should pass some kind of collection of `nodes` however a Node itself is sufficient and rarely if ever you will accross a collection of nodes for traversal."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T09:18:52.177",
"Id": "29582",
"ParentId": "29568",
"Score": "4"
}
},
{
"body": "<p>Here is my latest implementation:</p>\n\n<blockquote>\n<pre><code>public class Tree<K> implements Iterable<K>\n{\n private TreeNode<K> root;\n static class TreeNode<K>\n {\n K k;\n TreeNode<K> left;\n TreeNode<K> right;\n public TreeNode(K k)\n {\n this.k = k;\n }\n }\n\n public void insert(K k)\n {\n Comparable cc = (Comparable)k;\n if(root == null)\n {\n root = new TreeNode<K>(k);\n }\n else\n {\n TreeNode temp = root;\n TreeNode parent = root;\n while(temp!=null)\n {\n parent = temp;\n Comparable c = (Comparable)temp.k;\n if(c.compareTo(cc) < 0)\n {\n temp =temp.right;\n }\n else\n {\n temp = temp.left;\n }\n }\n Comparable c = (Comparable)parent.k;\n if(c.compareTo(cc) > 0) \n {\n parent.left = new TreeNode(k);\n }\n else\n {\n parent.right = new TreeNode(k);\n }\n }\n }\n\n @Override\n public Iterator<K> iterator()\n {\n return new MyIterator<K>();\n }\n private class MyIterator<K> implements Iterator<K>\n {\n Stack<TreeNode> s = new Stack<TreeNode>();\n TreeNode<K> t = (TreeNode<K>) root;\n\n @Override\n public boolean hasNext()\n {\n if(s.peek()!=null || t!=null)\n {\n return true;\n }\n return false;\n }\n\n @Override\n public K next() \n {\n while(s.peek() !=null || t!=null)\n {\n if(t!=null)\n {\n s.push(t);\n t = t.left;\n }\n else\n {\n t = s.pop();\n TreeNode<K> temp = t;\n t = t.right;\n return temp.k;\n }\n }\n return null;\n }\n\n @Override\n public void remove() \n {\n\n }\n\n }\n}\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T11:08:19.903",
"Id": "46878",
"Score": "0",
"body": "In `insert()`, your comparisons should be consistent. You have `if(c.compareTo(cc) < 0)`, and later `if(c.compareTo(cc) > 0)`. Better to make them the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T11:26:30.143",
"Id": "46880",
"Score": "0",
"body": "You should [require K to implement Comparable<K>](http://stackoverflow.com/questions/1070703). Then you won't have to cast to `Comparable` everywhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-28T17:05:51.833",
"Id": "301468",
"Score": "0",
"body": "This does not constitute a good answer, as it is not attempting to review the original code. Please edit your answer to explain what you improved and why."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T09:49:05.437",
"Id": "29642",
"ParentId": "29568",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T20:25:48.943",
"Id": "29568",
"Score": "2",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Preorder traversal using stack"
}
|
29568
|
<p>This code works by taking my user input and correctly pulling the information I'm giving it.</p>
<p>I'm having difficulty understanding the implementation of methods in classes. I'm pretty sure I'm not doing this the correct way. Can anyone show me the way it <em>should</em> be done?</p>
<pre><code>class prog_setup:
def __init__(self):
"""Initiates the below modules/variables."""
self.get_starlist()
self.get_InputKey()
self.define_listsANDarrays()
self.determine_normalizationpoint()
self.create_fobs_fobserr()
#self.calculate_taumag()
self.search_DUSTYmodels()
self.calculate_chi2()
self.delete_null_components()
self.dust_whittet_sub()
def get_starlist(self):
"""Imports the list of stars that you would like information on."""
self.star_list=np.array([])
try:
get_star_list=raw_input('Input pathname of the list of stars to be studied: ')
incoming_stars=open(get_star_list,'rb')
for line in incoming_stars:
x=line.split()
self.star_list=np.append(self.star_list,x) #Appends the individual star-IDs to the empty array star_list.
print 'Stars imported successfully.'
except IOError:
print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
sys.exit()
self.indices_of_star_list=range(len(self.star_list))
def get_InputKey(self):
"""Imports the Input (.inp) file. Historically, InputUttenthaler.inp. Allows for definition
of parameters which are utilized later in the script."""
input_script=raw_input('Pathname of .inp file: ')
InputKey=[]
self.band=''
self.Ak_scalefactor=''
try:
with open(input_script) as input_key:
for line in input_key.readlines():
x=[item for item in line.split()]
InputKey.append(x)
if InputKey[0][0]=='1' or InputKey[0][0]=='2': #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2.
print 'Your .inp file was successfully imported'
else:
print 'Your .inp file import failed. Check the validity of your file.\n Program exiting now.'
sys.exit()
except IOError:
print 'The .inp file import was unsuccessful. Check that your file-path is valid.\n Program exiting now.'
sys.exit()
</code></pre>
<p>The entire code is longer; I just put in the first two methods to give an example of what my structure looks like.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:03:21.333",
"Id": "46785",
"Score": "0",
"body": "Your indentation really should be more than 1 space each. Having it at 1 makes it unreadable. It should be at a minimum of 3 in any structured language really. Though for Python, [it should be 4](http://www.python.org/dev/peps/pep-0008/#indentation)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:03:32.223",
"Id": "46786",
"Score": "1",
"body": "Hard to tell from the snippet you provide, but it looks like you're simply trying to put all of your main programme code in a series of methods in a class. These functions don't seem to have much connection to each other, so why put them together in a class rather than just have them as free-standing functions? A class is usually used to create objects of a certain type, but what kind of object would `prog_setup` be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:03:51.257",
"Id": "46787",
"Score": "0",
"body": "Having said all that, it might sometimes be useful to wrap a load of functions together in a class just to keep them separate from the rest of the code, and if that's all you are trying to do, this seems basically okay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:10:06.140",
"Id": "46788",
"Score": "0",
"body": "@Stuart Originally this was someone else's code that was **really** hard to follow. I don't know much about python so I thought I'd try to rewrite it using classes. Reading more I've come to realize that I probably don't need to use classes, but in my ignorance I thought I had to to use the functions this way. If I used them without a class what would need to change? And yes, I'm aware that my indentation is not up to standards. I'm using eclipse and it didn't copy/paste over to the site too well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T07:35:37.623",
"Id": "46796",
"Score": "0",
"body": "Wow, methods are more methods with no arguments and no return values. That's what you would call a \"stateful monster\". I wonder, Is this kind of OOP still encouraged?"
}
] |
[
{
"body": "<p>If you decide to implement this without using a class you can simply write:</p>\n\n<pre><code>def get_starlist():\n ...\ndef get_inputkey():\n ...\n\nif __name__ == \"__main__\":\n get_starlist()\n get_input_key()\n define_lists_and_arrays() \n determine_normalization_point()\n create_fobs_fobserr()\n search_DUSTY_models()\n calculate_chi2()\n delete_null_components()\n dust_whittet_sub()\n</code></pre>\n\n<p>But if you find that some of your functions are sharing data a lot you may want to attach them to a class, or pass instances of a class (objects) between the different functions. It's hard to say more without knowing what you're trying to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:31:48.533",
"Id": "46789",
"Score": "0",
"body": "Cool. The functions essentially work linearly; the second function takes info from the first function, third from second, etc. It's not completely linear but for the most part that's how I'd characterize the essence of what I've written (having not shown everything). I think I can figure it out from here. Thanks for the help and clarification."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:22:40.517",
"Id": "29574",
"ParentId": "29571",
"Score": "3"
}
},
{
"body": "<p>If your methods don't use any members write the as static methods</p>\n\n<pre><code>class ProgSetup(object):\n @staticmethod\n def getStarlist(x):\n pass\n</code></pre>\n\n<p>Some more tipps:</p>\n\n<ul>\n<li>all classes should inheritance from <code>object</code></li>\n<li>please use more spaces for identidation</li>\n<li>dont put <code>_</code> in your variable/methodnames except for constants like <code>THIS_IS_MY_CONSTANT</code></li>\n<li>write your varibale names out, don't write short function/variable names</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:52:52.897",
"Id": "46792",
"Score": "2",
"body": "Using _ in variable and method names is [standard in python](http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T15:18:59.383",
"Id": "46812",
"Score": "1",
"body": "@Quonux - please read [PEP8](http://www.python.org/dev/peps/pep-0008/). Using underscores to separate words *IS* the guideline for everything except for class names. So your `getStarlist` method should be `get_star_list`. As for the inherit from `object`, this is unnecessary since Python 3.0 but it is probably a good idea until the 2.x branches fall out of use."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T00:42:50.340",
"Id": "29575",
"ParentId": "29571",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29574",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T22:34:52.747",
"Id": "29571",
"Score": "4",
"Tags": [
"python"
],
"Title": "Pulling information from user input"
}
|
29571
|
<p>I am doing sentiment analysis on tweets. I have code that I developed from following an online tutorial (found <a href="http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/" rel="nofollow noreferrer">here</a>) and adding in some parts myself, which looks like this:</p>
<pre><code>#!/usr/bin/env python
import csv, string, HTMLParser, nltk, pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
test_file = 'Dataset/SmallSample.csv'
#test_file = 'Dataset/Dataset.csv'
csv_file = csv.DictReader(open(test_file, 'rb'), delimiter=',', quotechar='"')
pos_tweets = {}
neg_tweets = {}
for line in csv_file:
if line['Sentiment']=='1':
pos_tweets.update({(line['SentimentText'],"positive")})
else:
neg_tweets.update({(line['SentimentText'],"negative")})
tweets = []
labeltweets = []
for (text, sentiment) in pos_tweets.items() + neg_tweets.items():
text = HTMLParser.HTMLParser().unescape(text.decode('utf-8'))
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
cleanedText = [e.translate(remove_punctuation_map).lower() for e in text.split() if not e.startswith(('http', '@')) ]
shortenedText = [e for e in cleanedText if len(e) >= 3]
tweets.append((shortenedText, sentiment))
# Produces list of all words in text of tweets (including duplicates).
def get_words_in_tweets(tweets):
all_words = []
for (text, sentiment) in tweets:
all_words.extend(text)
return all_words
def get_word_features(wordlist):
# This line calculates the frequency distrubtion of all words in tweets
# e.g. word "love" appears 5 times, word "dog" appears 3 times etc.
wordlist = nltk.FreqDist(wordlist)
word_features = wordlist.keys()
# This prints out the list of all distinct words in the text in order
# of their number of occurrences.
return word_features
word_features = get_word_features(get_words_in_tweets(tweets))
def extract_features(document):
setOfDocument = set(document)
features = {}
for word in word_features:
features['contains(%s)' % word] = (word in setOfDocument)
return features
training_set = nltk.classify.apply_features(extract_features, tweets)
classifer = nltk.NaiveBayesClassifier.train(training_set)
</code></pre>
<p>The code imports a large csv file and creates two dictionaries out of it, depending on whether the tweet is positive or negative. It maps these dictionaries like so:</p>
<pre><code>("United won a !game today", "positive")
</code></pre>
<p>The for loop that follows this performs basic HTML stripping for unescaped syntax and removes all punctuation and words less than length of three, combining these into one large list, with this format:</p>
<pre><code>(["United", "won", "game", "today"], "positive")
</code></pre>
<p>It then creates a list of just the text words (ignoring the positive/negative sentiment) and uses the nltk FreqDist method to create a frequency distribution of all words used like this:</p>
<pre><code><FreqDist:
'this': 6,
'car': 2,
'concert': 2,
'feel': 2,
'morning': 2,
'not': 2,
'the': 2,
'view': 2,
'about': 1,
'amazing': 1,
...
>
</code></pre>
<p>and then removing the accompanying numbers, just leaving the "word features".</p>
<p>The method extract_features then compares the tweet input to a list of words, like this:</p>
<pre><code>Input: ['love', 'this', 'car']
Output:
{'contains(not)': False,
'contains(view)': False,
'contains(best)': False,
'contains(excited)': False,
'contains(morning)': False,
'contains(about)': False,
'contains(horrible)': False,
'contains(like)': False,
'contains(this)': True,
'contains(friend)': False,
'contains(concert)': False,
'contains(feel)': False,
'contains(love)': True,
'contains(looking)': False,
'contains(tired)': False,
'contains(forward)': False,
'contains(car)': True,
'contains(the)': False,
'contains(amazing)': False,
'contains(enemy)': False,
'contains(great)': False}
</code></pre>
<p>Finally, the line:</p>
<pre><code>training_set = nltk.classify.apply_features(extract_features, tweets)
</code></pre>
<p>is used to build this training set of data from all provided tweets, breaking them down like this:</p>
<pre><code>[({'contains(not)': False,
...
'contains(this)': True,
...
'contains(love)': True,
...
'contains(car)': True,
...
'contains(great)': False},
'positive'),
({'contains(not)': False,
'contains(view)': True,
...
'contains(this)': True,
...
'contains(amazing)': True,
...
'contains(enemy)': False,
'contains(great)': False},
'positive'),
...]
</code></pre>
<p>This information is finally fed in to the trainer, like so:</p>
<pre><code>classifier = nltk.NaiveBayesClassifier.train(training_set)
</code></pre>
<p>When I ran this on my sample dataset, it all worked perfectly, although a little inaccurately (training set only had 50 tweets). My REAL training set however has 1.5 million tweets. I'm finding that using the default trainer provided by Python is just far too slow.</p>
<p>Is this too large a dataset to be used with the default Python classifier? Does anybody have any suggestions or alternatives that could be used to do this operation? In all responses please bear in mind I could only accomplish this with a tutorial and am totally new to Python (am usually a Java coder).</p>
<p><a href="https://stackoverflow.com/questions/18154278/is-there-a-maximum-size-for-the-nltk-naive-bayes-classifer#18154932">Original SO post</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T00:57:56.253",
"Id": "57553",
"Score": "0",
"body": "What did you end up doing here?"
}
] |
[
{
"body": "<p>take a look at the answers in </p>\n\n<p><a href=\"https://stackoverflow.com/questions/13610074/is-there-a-rule-of-thumb-for-how-to-divide-a-dataset-into-training-and-validatio/13623707#13623707\">Is there a rule-of-thumb for how to divide a dataset into training and validation sets?</a></p>\n\n<blockquote>\n <p>\"If you have 100,000 instances, ... indeed you may choose to use less training data if your method is particularly computationally intensive).\"</p>\n</blockquote>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-08T09:34:44.257",
"Id": "34051",
"ParentId": "29573",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T23:28:17.073",
"Id": "29573",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"machine-learning",
"data-mining"
],
"Title": "Alternative to Python's Naive Bayes Classifier for Twitter Sentiment Mining"
}
|
29573
|
<p>I have an HTML menu with sub-menus and also sub-sub-menus. This code verifies each menu's trigger. If clicked, sub-menu opens. Sub-menus also have triggers that open sub-sub-menus and so on. A working example can be found <a href="http://bios-diagnostic.ro/meniu213/" rel="nofollow noreferrer">here</a>. This menu is a modified version of the menu found <a href="http://tympanus.net/Tutorials/GoogleNexusWebsiteMenu/" rel="nofollow noreferrer">here</a>, made by Mary Lou. I want this to be my mobile menu but I don't want to manually enter all the cases.</p>
<p>My code is very lengthy and repetitive. How can I simplify it?</p>
<pre><code>( function( window ) {
'use strict';
// http://stackoverflow.com/a/11381730/989439
function mobilecheck() {
var check = false;
(function(a){if(/(android|ipad|playbook|silk|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}
function gnMenu( el, options ) {
this.el = el;
this._init();
}
function gnSubMenu( el, options ) {
this.el = el;
this._init();
}
function gnSubMenu2( el, options ) {
this.el = el;
this._init();
}
gnMenu.prototype = {
_init : function() {
this.trigger = this.el.querySelector( '.gn-icon-menu' );
this.subtrigger = this.el.querySelector('.submenu' );
this.subtrigger2 = this.el.querySelector('.submenu2' );
this.menu = this.el.querySelector( '.menu-wrapper' );
this.submenu = this.el.querySelector( '.sub-menu-wrapper1' );
this.submenu2 = this.el.querySelector( '.sub-menu-wrapper2' );
this.isMenuOpen = false;
this.isSubMenuOpen = false;
this.isSubMenu2Open = false;
this.eventtype = mobilecheck() ? 'touchstart' : 'click';
this._initEvents();
var self = this;
this.bodyClickFn = function() {
self._closeMenu();
self._closeSubMenu();
self._closeSubMenu2();
this.removeEventListener( self.eventtype, self.bodyClickFn );
};
},
_initEvents : function() {
var self = this;
if( !mobilecheck() ) {
this.menu.addEventListener( 'mouseover', function(ev) {
self._openMenu();
document.addEventListener( self.eventtype, self.bodyClickFn );
} );
this.submenu.addEventListener( 'mouseover', function(ev) {
self._openSubMenu();
document.addEventListener( self.eventtype, self.bodyClickFn );
} );
this.submenu2.addEventListener( 'mouseover', function(ev) {
self._openSubMenu2();
document.addEventListener( self.eventtype, self.bodyClickFn );
} );
}
this.trigger.addEventListener( this.eventtype, function( ev ) {
ev.stopPropagation();
ev.preventDefault();
if( self.isMenuOpen ) {
self._closeMenu();
document.removeEventListener( self.eventtype, self.bodyClickFn );
}
else {
self._openMenu();
document.addEventListener( self.eventtype, self.bodyClickFn );
}
} );
this.subtrigger.addEventListener( this.eventtype, function( ev ) {
ev.stopPropagation();
ev.preventDefault();
if( self.isSubMenuOpen ) {
self._closeSubMenu();
document.removeEventListener( self.eventtype, self.bodyClickFn );
}
else {
self._openSubMenu();
document.addEventListener( self.eventtype, self.bodyClickFn );
}
} );
this.subtrigger2.addEventListener( this.eventtype, function( ev ) {
ev.stopPropagation();
ev.preventDefault();
if( self.isSubMenu2Open ) {
self._closeSubMenu2();
document.removeEventListener( self.eventtype, self.bodyClickFn );
}
else {
self._openSubMenu2();
document.addEventListener( self.eventtype, self.bodyClickFn );
}
} );
this.menu.addEventListener( this.eventtype, function(ev) { ev.stopPropagation(); } );
this.submenu.addEventListener( this.eventtype, function(ev) { ev.stopPropagation(); } );
this.submenu2.addEventListener( this.eventtype, function(ev) { ev.stopPropagation(); } );
},
_openMenu : function() {
if( this.isMenuOpen )
return;
classie.add( this.trigger, 'gn-selected' );
this.isMenuOpen = true;
classie.add( this.menu, 'gn-open-all' );
},
_closeMenu : function() {
if( !this.isMenuOpen )
return;
classie.remove( this.trigger, 'gn-selected' );
this.isMenuOpen = false;
classie.remove( this.menu, 'gn-open-all' );
},
_openSubMenu : function() {
if( this.isSubMenuOpen )
return;
classie.add( this.subtrigger, 'gn-selected' );
this.isSubMenuOpen = true;
classie.add( this.submenu, 'gn-open-all2' );
},
_closeSubMenu : function() {
if( !this.isSubMenuOpen )
return;
classie.remove( this.subtrigger, 'gn-selected' );
this.isSubMenuOpen = false;
classie.remove( this.submenu, 'gn-open-all2' );
},
_openSubMenu2 : function() {
if( this.isSubMenu2Open )
return;
classie.add( this.subtrigger2, 'gn-selected' );
this.isSubMenu2Open = true;
classie.add( this.submenu2, 'gn-open-all3' );
},
_closeSubMenu2 : function() {
if( !this.isSubMenu2Open )
return;
classie.remove( this.subtrigger2, 'gn-selected' );
this.isSubMenu2Open = false;
classie.remove( this.submenu2, 'gn-open-all3' );
}
};
// Add to global namespace
window.gnMenu = gnMenu;
} )( window );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T07:47:36.673",
"Id": "46797",
"Score": "2",
"body": "Well, you could **start with proper intendation**! After that, factor out common stuff. Functions are not special, so you could do `var gnSubMenu = gnMenu, gnSubMenu2 = gnMenu;` instead of defining three identical functions. Use loops for repetitive code (e.g. over the `addEventListener`). After that you can start with actual refactoring (e.g. choosing better names)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T13:21:29.013",
"Id": "110843",
"Score": "1",
"body": "@amon y u answer in comments?"
}
] |
[
{
"body": "<p>One thing that I saw right away, while I was editing your question to make it more noticeable, is that you have 3 functions that are the same, they just have different names.</p>\n\n<blockquote>\n<pre><code>function gnMenu( el, options ) {\n this.el = el;\n this._init();\n}\n\nfunction gnSubMenu( el, options ) {\n this.el = el;\n this._init();\n}\n\nfunction gnSubMenu2( el, options ) {\n this.el = el;\n this._init();\n}\n</code></pre>\n</blockquote>\n\n<p>You don't need to do this. It looks like they all take in the same parameters and do the same thing, so just use one function for the 3 of them.</p>\n\n<pre><code>function menu( el, options ) {\n this.el = el;\n this._init();\n}\n</code></pre>\n\n<p>One step to being DRYer already (<em>DRY = Don't Repeat Yourself</em>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-25T20:57:42.443",
"Id": "61029",
"ParentId": "29579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T07:05:04.423",
"Id": "29579",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "HTML menu with sub-menus"
}
|
29579
|
<p>I wrote a class to import a large XML file. It works great, but I feel like its ugly, and horribly inefficient although I do like how easy it is to follow what it does. </p>
<p>How can I improve this to make it better and to foster some better ruby writing ability?</p>
<pre><code>require "rexml/document"
class Xmltube
def self.convert_save(xml_data)
doc = REXML::Document.new xml_data.read
doc.elements.each("Meeting") do |meeting_element|
meeting = save_meeting(meeting_element)
save_races(meeting_element, meeting)
Rails.logger.info "all done"
end
end
def self.save_races(meeting_element, meeting)
meeting_element.elements.each("Races/Race") do |race_element|
race = save_race(race_element, meeting)
save_race_entrants(race_element, race)
end
end
def self.save_race_entrants(race_element, race)
race_element.elements.each("RaceEntries/RaceEntry") do |entry_element|
horse = save_horse(entry_element)
jockey = save_jockey(entry_element)
start = save_start(entry_element, horse, jockey, race)
save_sumaries(entry_element, start)
end
end
def self.save_track(meeting_element)
# there is only one track, but still, each? wtf.
t = {}
meeting_element.elements.each("Track") do |track|
t = {
:name => track.attributes["VenueName"],
:track_code => track.attributes["VenueCode"],
:condition => track.elements['TrackRating'].text,
:club_id => save_club(meeting_element.elements["Club"]).id
}
end
track = Track.where(:track_code => t[:track_code] ).first
if track
Track.update(track.id, t)
else
Track.create(t)
end
end
def self.save_meeting meeting_element
t = {
:meet_code => meeting_element.attributes['MeetCode'],
:stage => meeting_element.elements["MeetingStage"].text,
:phase => meeting_element.elements["MeetingPhase"].text,
:nominations_close_at => meeting_element.elements["NominationsClose"].text,
:acceptance_close_at => meeting_element.elements["AcceptanceClose"].text,
:riders_close_at => meeting_element.elements["RidersClose"].text,
:weights_published_at => meeting_element.elements["WeightsPublishing"].text,
:club_id => save_club(meeting_element.elements["Club"]).id ,
:track_id => save_track(meeting_element).id,
:tab_status => meeting_element.elements["TabStatus"].text,
:state => meeting_element.elements["StateDesc"].text,
:day_night => meeting_element.elements["DayNight"].text,
:number_of_races => meeting_element.elements["NumOfRaces"].text,
:meet_date => meeting_element.elements["MeetDate"].text,
}
meeting = Meeting.where(:meet_code => t[:meet_code] ).first
if meeting
Meeting.update(meeting.id, t)
else
Meeting.create(t)
end
end
############################################################
def self.save_sumaries entry_element, start
entry_element.elements.each('Form/ResultsSummaries/ResultsSummary') do | element |
s = {
:name => element.attributes['Name'],
:start_id => start.id,
:starts => element.attributes['Starts'],
:wins => element.attributes['Wins'],
:seconds => element.attributes['Seconds'],
:thirds => element.attributes['Thirds'],
:prize_money => element.attributes['PrizeMoney'],
}
sum = Summary.where(:name => s[:name] ).where(:start_id => s[:start_id]).first
if sum
Summary.update(sum.id, s)
else
Summary.create(s)
end
end
end
def self.save_start entry_element, horse, jockey, race
s = {
:horse_id => horse.id,
:jockey_id => jockey.id,
:race_id => race.id,
:silk => entry_element.elements["JockeySilksImage"].attributes["FileName_NoExt"],
:start_code => entry_element.attributes['RaceEntryCode'],
:handicap_weight => entry_element.elements['HandicapWeight'].text,
}
# Rails.logger.info entry_element['HandicapWeight'].text
start = Start.where(:start_code => s[:start_code] ).first
if start
Start.update(start.id, s)
else
Start.create(s)
end
end
def self.save_jockey entry_element
j={
:name => entry_element.elements['JockeyRaceEntry/Name'].text,
:jockey_code => entry_element.elements['JockeyRaceEntry'].attributes["JockeyCode"],
}
jockey = Jockey.where(:jockey_code => j[:jockey_code] ).first
if jockey
Jockey.update(jockey.id, j)
else
Jockey.create(j)
end
end
def self.save_horse entry_element
trainer = save_trainer entry_element
h= {
:name => entry_element.elements['Horse'].attributes["HorseName"],
:color => entry_element.elements['Horse'].attributes["Colour"],
:dob => entry_element.elements['Horse'].attributes["FoalDate"],
:sex => entry_element.elements['Horse'].attributes["Sex"],
:trainer_id => trainer.id,
:horse_code => entry_element.elements['Horse'].attributes["HorseCode"],
}
horse = Horse.where(:horse_code => h[:horse_code] ).first
if horse
Horse.update(horse.id, h)
else
Horse.create(h)
end
end
def self.save_trainer entry_element
t= {
:name => entry_element.elements['Trainer/Name'].text,
:trainer_code => entry_element.elements['Trainer'].attributes["TrainerCode"]
}
trainer = Trainer.where(:trainer_code => t[:trainer_code] ).first
if trainer
Trainer.update(trainer.id, t)
else
Trainer.create(t)
end
end
def self.save_club element
t = {}
t = {
:club_code => element.attributes['ClubCode'],
:title => element.attributes["Title"],
}
club = Club.where(:club_code => t[:club_code] ).first
if club
Club.update(club.id, t)
else
Club.create(t)
end
end
def self.save_race element, meeting
r = {
:name => element.elements['NameRaceFull'].text,
:occur => element.elements['RaceStartTime'].attributes["TimeAtVenue"],
:distance => element.elements['RaceDistance'].text,
:race_type => element.elements['RaceType'].text,
:track_id => meeting.track_id,
:race_code => element.attributes["RaceCode"],
:meeting_id => meeting.id
}
race = Race.where(:race_code => r[:race_code] ).first
if race
Race.update(race.id, r)
else
Race.create(r)
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><code>rexml/document</code>. I'd use <a href=\"http://nokogiri.org/\" rel=\"nofollow\">Nokogiri</a> without a second thought, but if you prefer <code>rexml</code> because it's comes in the standard library, that's ok.</li>\n<li><code>Rails.logger.info \"all done\"</code>. I wouldn't mix code with and without parens. I definetely would write them on method signatures.</li>\n<li><code>def self.save_races</code>. You may not need it right now, but as a rule of thumb methods return values. Here the saved races (since the method is called <code>save_races</code>).</li>\n<li><code>entry_element.elements['Horse'].attributes</code> used a lot of times: set a local variable.</li>\n<li><code>t = {}</code> followed by <code>t = something</code> inside a each? That's not good practice, should be written in a different way. If those <code>each</code> just want to take one element, put a <code>first</code> or something.</li>\n<li><p>The most important point: almost all those <code>save_xyz</code> methods contain this pattern:</p>\n\n<pre><code>sum = Summary.where(:name => s[:name] ).where(:start_id => s[:start_id]).first\nif sum\n Summary.update(sum.id, s) \nelse \n Summary.create(s) \nend \n</code></pre>\n\n<p>That should be abstracted with a method (in the app, or monkeypatched). You should be able to write something like (or similar, you get the idea):</p>\n\n<pre><code>Summary.create_or_update(attributes, :find => [:name, :start_id])\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T21:57:41.903",
"Id": "46823",
"Score": "0",
"body": "Thanks. Iv'e applied those learnings and its looking a bit better. Most of all, its much quicker with nokogiri. I had been reluctant to use it because it causes so many installation problems, but time to be brave : )"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T14:19:11.143",
"Id": "29588",
"ParentId": "29585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29588",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T09:52:03.840",
"Id": "29585",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "XML Import class - Style improvements & Efficiency"
}
|
29585
|
<p>My first question relates to the first Python module that I published on Python. This is a very small and simple module, the package contains only one class. This is a port of a Perl module <a href="https://metacpan.org/module/Locale%3a%3aWolowitz" rel="nofollow">Locale::Wolowitz</a> this is a module for managing translations, but uses the serialization format JSON or YAML. Below the code of my Python class, I will like to have an opinion on the code:</p>
<pre><code>import glob
import re
import os.path
from collections import defaultdict
class Pylocwolowitz(object):
'''Pylocwolitz is a very simple text localization system, meant to be used
by web applications (but can pretty much be used anywhere). Yes, another
localization system.'''
def __init__(self, path, format_deserializer='json'):
if format_deserializer not in ('json', 'yaml'):
raise ValueError('FormatNotSupported')
self.path = path
self.format_deserializer = format_deserializer
self.locales = defaultdict(dict)
self._find_file()
def _find_file(self):
'''Find all json files'''
listing = glob.glob(
os.path.join(self.path, '*.' + self.format_deserializer))
for infile in listing:
self._make_loc(infile)
def _make_loc(self, infile):
'''Store content of the file in a memory'''
lang = os.path.basename(infile).split('.')[0]
if self.format_deserializer == 'json':
import json
with open(infile) as fil:
data = json.load(fil)
else:
import yaml
with open(infile) as fil:
data = yaml.load(fil)
for key, value in data.items():
if isinstance(value, dict):
self.locales[key].update(value)
else:
self.locales[key].update({lang: value})
def loc(self, key, lang, values=None):
'''Return the string key, translated to the requested language (if such
a translation exists, otherwise no traslation occurs). Any other
parameters passed to the method are injected to the placeholders in the
string (if present).'''
if self.locales[key].get(lang) is None:
return key
ret = self.locales[key][lang] if key in self.locales else key
if values is None:
return ret
else:
return ret % values
</code></pre>
<p>I get an error with Python 3.2 on <a href="https://travis-ci.org/hobbestigrou/Pylocwolowitz/jobs/10004145" rel="nofollow">travis.ci</a> but the tests pass on Python 2.x and PyPy, if you have an idea let me know. I'm not sure, but I think as I read it was better to use format or template, rather than % with Python 3 is that I'm wrong.</p>
|
[] |
[
{
"body": "<pre><code>import glob\nimport re\nimport os.path\nfrom collections import defaultdict\n\n\nclass Pylocwolowitz(object):\n '''Pylocwolitz is a very simple text localization system, meant to be used\nby web applications (but can pretty much be used anywhere). Yes, another\nlocalization system.'''\n\ndef __init__(self, path, format_deserializer='json'):\n</code></pre>\n\n<p>Calling it format_deserializer suggests to me that it should be a function. Perhaps it should just be <code>format</code>?</p>\n\n<pre><code> if format_deserializer not in ('json', 'yaml'):\n raise ValueError('FormatNotSupported')\n\n self.path = path\n self.format_deserializer = format_deserializer\n self.locales = defaultdict(dict)\n self._find_file()\n\ndef _find_file(self):\n '''Find all json files'''\n</code></pre>\n\n<p>You are finding files, find a file. Consider changing the name.</p>\n\n<pre><code> listing = glob.glob(\n os.path.join(self.path, '*.' + self.format_deserializer))\n for infile in listing:\n</code></pre>\n\n<p>I'd do </p>\n\n<pre><code> path = os.path.join(self.path, '*.' + self.format_deserializer)\n for infile in glob.glob(path):\n</code></pre>\n\n<p>Which I think comes out a bit cleaner</p>\n\n<pre><code> self._make_loc(infile)\n\ndef _make_loc(self, infile):\n '''Store content of the file in a memory'''\n</code></pre>\n\n<p>Avoid abbreviations, I have no idea what loc is.</p>\n\n<pre><code> lang = os.path.basename(infile).split('.')[0]\n</code></pre>\n\n<p>There is a splitext function which you might find useful here. You also don't ue this until way latter. Perhaps you should determine it later.</p>\n\n<pre><code> if self.format_deserializer == 'json':\n import json\n with open(infile) as fil:\n data = json.load(fil)\n else:\n import yaml\n with open(infile) as fil:\n data = yaml.load(fil)\n</code></pre>\n\n<p>Instead, you could do</p>\n\n<pre><code> deseralizer = __import__(self.format_deserializer)\n with open(infile) as fil:\n data = deserializer.load(fil)\n</code></pre>\n\n<p>That would avoid doing the same thing twice.</p>\n\n<pre><code> for key, value in data.items():\n if isinstance(value, dict):\n self.locales[key].update(value)\n else:\n self.locales[key].update({lang: value})\n\ndef loc(self, key, lang, values=None):\n '''Return the string key, translated to the requested language (if such\n a translation exists, otherwise no traslation occurs). Any other\n parameters passed to the method are injected to the placeholders in the\n string (if present).'''\n\n if self.locales[key].get(lang) is None:\n return key\n</code></pre>\n\n<p>Do you actually want to skip formatting this case?</p>\n\n<pre><code> ret = self.locales[key][lang] if key in self.locales else key\n</code></pre>\n\n<p>Why are you checking if key is in self.locales? It will be because the previous statement will have put it in regardless. And if it's not there, the first statement would have already returned. Also, its more pythonic to try and fetch it and catch the exception like:</p>\n\n<pre><code> try:\n ret = self.locales[key][lang]\n except KeyError:\n ret = key\n</code></pre>\n\n<p>That way you only lookup the dictionary once. But we can actually do even better by using get with a default</p>\n\n<pre><code> ret = self.locales[key].get(lang, key)\n</code></pre>\n\n<p>That, I think, is a very slick approach.</p>\n\n<pre><code> if values is None:\n return ret\n else:\n return ret % values\n</code></pre>\n\n<p>Using .format would probably be preferred</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T02:50:05.360",
"Id": "46828",
"Score": "0",
"body": "Hi, Thank you very much for your answer, I'm very happy, I will improve it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T15:05:28.640",
"Id": "29590",
"ParentId": "29586",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T12:58:37.690",
"Id": "29586",
"Score": "7",
"Tags": [
"python",
"json",
"perl",
"i18n"
],
"Title": "Simple text localization system"
}
|
29586
|
<p>I am making a WordPress "framework" for myself. Looking at the <a href="http://d.pr/f/kqw8" rel="nofollow">functions.php file</a> file, is there redundant or bad code that could be changed or some code that could be good to add?</p>
<p>The functions.php should be a file that I could use in every web project with little or no change.</p>
<p>Is this code good to put in the functions.php file?</p>
<p>Code (block scrollable):</p>
<pre><code>/*
* Default theme setup
*/
function beeFramework_setup() {
// This theme styles the visual editor to resemble the theme style,
// specifically font, colors, icons, and column width.
add_editor_style( array( 'css/editor-style.css', 'fonts/genericons.css' ) );
// Adds RSS feed links to <head> for posts and comments.
add_theme_support( 'automatic-feed-links' );
// Switches default core markup for search form, comment form, and comments
// to output valid HTML5.
add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list' ) );
// This theme supports all available post formats by default.
// See http://codex.wordpress.org/Post_Formats
add_theme_support( 'post-formats', array(
'aside', 'audio', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video'
) );
// This theme uses wp_nav_menu() in one location.
//register_nav_menu( 'primary', __( 'Navigation Menu', 'twentythirteen' ) );
// This theme uses its own gallery styles.
add_filter( 'use_default_gallery_style', '__return_false' );
}
add_action( 'after_setup_theme', 'beeFramework_setup' );
/*
* Disable WordPress Update Notifications For All But Administrator
*/
add_action( 'after_setup_theme', 'remove_core_updates' );
function remove_core_updates()
{
if ( ! current_user_can( 'update_core' ) ) {
return;
}
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', '__return_null' );
add_filter( 'pre_site_transient_update_core', '__return_null' );
}
if ( !current_user_can('administrator') ) {
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
}
/*
* Load Styles and Scrips Front end
*/
function twentythirteen_scripts_styles() {
// Add Genericons font, used in the main stylesheet.
wp_enqueue_style( 'genericons', get_template_directory_uri() . '/fonts/genericons.css', array(), '2.09' );
// Loads our main stylesheet.
wp_enqueue_style( 'twentythirteen-style', get_stylesheet_uri(), array(), '2013-07-18' );
// Loads the Internet Explorer specific stylesheet.
wp_enqueue_style( 'twentythirteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentythirteen-style' ), '2013-07-18' );
wp_style_add_data( 'twentythirteen-ie', 'conditional', 'lt IE 9' );
}
add_action( 'wp_enqueue_scripts', 'twentythirteen_scripts_styles' );
/*
* Nice Title Text
*/
function bee_freame_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() )
return $title;
// Add the site name.
$title .= get_bloginfo( 'name' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title = "$title $sep $site_description";
// Add a page number if necessary.
if ( $paged >= 2 || $page >= 2 )
$title = "$title $sep " . sprintf( __( 'Page %s', 'twentythirteen' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'bee_freame_wp_title', 10, 2 );
/**
* Prints HTML with meta information for current post: categories, tags, permalink, author, and date.
*/
if ( ! function_exists( 'twentythirteen_entry_meta' ) ) :
function twentythirteen_entry_meta() {
if ( is_sticky() && is_home() && ! is_paged() )
echo '<span class="featured-post">' . __( 'Sticky', 'twentythirteen' ) . '</span>';
if ( ! has_post_format( 'link' ) && 'post' == get_post_type() )
twentythirteen_entry_date();
// Translators: used between list items, there is a space after the comma.
$categories_list = get_the_category_list( __( ', ', 'twentythirteen' ) );
if ( $categories_list ) {
echo '<span class="categories-links">' . $categories_list . '</span>';
}
// Translators: used between list items, there is a space after the comma.
$tag_list = get_the_tag_list( '', __( ', ', 'twentythirteen' ) );
if ( $tag_list ) {
echo '<span class="tags-links">' . $tag_list . '</span>';
}
// Post author
if ( 'post' == get_post_type() ) {
printf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>',
esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
esc_attr( sprintf( __( 'View all posts by %s', 'twentythirteen' ), get_the_author() ) ),
get_the_author()
);
}
}
endif;
if ( ! function_exists( 'twentythirteen_entry_date' ) ) :
/**
* Prints HTML with date information for current post.
*
* Create your own twentythirteen_entry_date() to override in a child theme.
*
* @since Twenty Thirteen 1.0
*
* @param boolean $echo Whether to echo the date. Default true.
* @return string The HTML-formatted post date.
*/
function twentythirteen_entry_date( $echo = true ) {
if ( has_post_format( array( 'chat', 'status' ) ) )
$format_prefix = _x( '%1$s on %2$s', '1: post format name. 2: date', 'twentythirteen' );
else
$format_prefix = '%2$s';
$date = sprintf( '<span class="date"><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a></span>',
esc_url( get_permalink() ),
esc_attr( sprintf( __( 'Permalink to %s', 'twentythirteen' ), the_title_attribute( 'echo=0' ) ) ),
esc_attr( get_the_date( 'c' ) ),
esc_html( sprintf( $format_prefix, get_post_format_string( get_post_format() ), get_the_date() ) )
);
if ( $echo )
echo $date;
return $date;
}
endif;
/**
* Returns the URL from the post.
*/
function twentythirteen_get_link_url() {
$content = get_the_content();
$has_url = get_url_in_content( $content );
return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}
/**
* Add postMessage support for site title and description for the Customizer.
*/
function twentythirteen_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
$wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage';
}
add_action( 'customize_register', 'twentythirteen_customize_register' );
</code></pre>
|
[] |
[
{
"body": "<p>The code seems pretty solid. I'll make some small observations:</p>\n\n<ol>\n<li><p>I'd remove <code>add_action( 'after_setup_theme', 'remove_core_updates' );</code> and add a call to the function <code>remove_core_updates()</code> at the end of <code>beeFramework_setup()</code>.</p></li>\n<li><p>The use of anonymous functions, <code>create_function</code>, prevents something like:</p>\n\n<pre><code># In your functions.php file\nadd_action( 'init', 'remove_version_check', 2 );\nfunction remove_version_check() {\n remove_action( 'init', 'wp_version_check' );\n}\n\n# Later in a child theme or plugin\nremove_action( 'init', 'remove_version_check', 2 );\n</code></pre></li>\n<li><p>The filter <code>pre_option_update_core</code> could be simply:</p>\n\n<pre><code>add_filter( 'pre_option_update_core', '__return_null' );\n</code></pre></li>\n<li><p>Make sure you know the difference between <a href=\"http://codex.wordpress.org/Function_Reference/get_template_directory_uri\" rel=\"nofollow\"><code>get_template_directory_uri()</code></a> and <a href=\"http://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\"><code>get_stylesheet_directory_uri()</code></a> and use them accordingly.</p></li>\n<li><p>Why would you check if Twenty Thirteen functions exists? Create good prefixes for your functions and drop the <code>function_exists</code> thing. I'd recommended using <a href=\"http://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow\">hooks</a> instead of <a href=\"http://codex.wordpress.org/Pluggable_Functions\" rel=\"nofollow\">pluggable functions</a>.</p></li>\n<li><p>And, finally, speaking of hooks, provide some of them so people can modify the theme behavior from a child theme or plugin:</p>\n\n<pre><code># In your functions.php file\n$post_formats = array( 'aside', 'audio', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video' );\nadd_theme_support( 'post-formats', apply_filters( 'my_framework_post_formats', $post_formats ) );\n\n# Later on a child theme or plugin we can reduce their number\nadd_filter( 'my_framework_post_formats', 'my_new_post_formats' );\nfunction my_new_post_formats( $formats ) {\n return array( 'audio', 'gallery', 'image' );\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-12T20:35:12.960",
"Id": "32608",
"ParentId": "29587",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T12:59:00.207",
"Id": "29587",
"Score": "3",
"Tags": [
"php",
"wordpress"
],
"Title": "WordPress Functions.php file"
}
|
29587
|
<p>I am new to C++ and to threading, so I'm sorry if my code is bad. I'm here to get it better and to learn. </p>
<p>Any kind of advice (both on C++ style, on Qt usage, or on threading handling) is welcome. Please feel free to comment anything, also if the question has to be reformulated.</p>
<p>I have this problem:</p>
<ul>
<li>one thread that grab frames from a video/web cam</li>
<li>some (let's say 3) threads that take the last grabbed frame, do some computer vision analysis, and display it back in the main gui. Each computation thread could have different computation time (because of computation-heavy algorithm like optical flow or similar)</li>
</ul>
<p>There are few important things I want to care about:</p>
<ol>
<li>the threads must run in parallel (that's why I used the threads)</li>
<li>threads takes only the last frame depending on their own job, so if a thread has some heavy optical flow computation, it will take only frames (let's say 1, 15, 21, 30). Instead, a light computation that does only frame differencing will take all frames 1, 2, 3, 4,..</li>
<li>I need a way to stop it and restart it. Let's say that I have 3 video to analyze, I want to do the first, wait for everything is finished, to the second, etc..</li>
</ol>
<p>I have done a little prototype that works with <code>int</code> as a shared resource, and not with a frame. I will use opencv, <code>cv::Mat</code> that are basically containers for <code>uchar</code> array where each <code>uchar</code> represents a pixel.</p>
<p>I think that this is a working prototype, but I'm very scared about threading. I've never done something with multithreading, I don't understand the problems well, and I don't know how to test it correctly.</p>
<p>I'm going to copy the files here, but the project is also on <a href="https://bitbucket.org/nkint/prodcons" rel="nofollow">bitbucket</a>.</p>
<p>P.S. If it's worth something, I'm using Qt 4.8 with QtCreator 2.8 under Mac OS/X 10.8, but should be super cross-compiling as I'm just using Qt objects.</p>
<p><strong>main.cpp:</strong></p>
<pre><code>#include <QApplication>
#include "mainwidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWidget w;
w.show();
return a.exec();
}
</code></pre>
<p><strong>mainwidget.h:</strong></p>
<pre><code>#ifndef MAINWIDGET_H
#define MAINWIDGET_H
#include <QWidget>
#include <QLabel>
#include <QCloseEvent>
#include <QKeyEvent>
#include <QVBoxLayout>
#include "resources.h"
#include "producer.h"
#include "consumer.h"
class MainWidget : public QWidget
{
Q_OBJECT
public:
//------------------------------------------------------------------ ctor dtor
explicit MainWidget(QWidget *parent = 0) : QWidget(parent) {
initGUI();
initProducer();
initConsumers();
}
~MainWidget()
{
}
//------------------------------------------------------------------ 1 prod, n cons
void initProducer()
{
producer = new Producer(&r);
connect(producer, SIGNAL(newFrame(int)),
this, SLOT(showProducer(int)));
connect(producer, SIGNAL(finished()),
producer, SLOT(deleteLater()));
producer->start();
}
void initConsumers()
{
consumerCounter = 0;
consumer1 = new Consumer(1, &r);
connect(consumer1, SIGNAL(newComputation(int)),
this, SLOT(showConsumer1(int)));
connect(consumer1, SIGNAL(finished()),
consumer1, SLOT(deleteLater()));
connect(consumer1, SIGNAL(destroyed()),
this, SLOT(incrementConsumerCounter()));
consumer2 = new Consumer(2, &r);
connect(consumer2, SIGNAL(newComputation(int)),
this, SLOT(showConsumer2(int)));
connect(consumer2, SIGNAL(finished()),
consumer2, SLOT(deleteLater()));
connect(consumer2, SIGNAL(destroyed()),
this, SLOT(incrementConsumerCounter()));
consumer3 = new Consumer(3, &r);
connect(consumer3, SIGNAL(newComputation(int)),
this, SLOT(showConsumer3(int)));
connect(consumer3, SIGNAL(finished()),
consumer3, SLOT(deleteLater()));
connect(consumer3, SIGNAL(destroyed()),
this, SLOT(incrementConsumerCounter()));
consumer1->start();
consumer2->start();
consumer3->start();
}
void stopProducer() {
producer->stopProduce();
}
void stopConsumers() {
consumer1->stopConsume();
consumer2->stopConsume();
consumer3->stopConsume();
}
void stopAll()
{
stopProducer();
stopConsumers();
qDebug() << "wake all!";
r.waitCondition.wakeAll();
}
//------------------------------------------------------------------ gui
void initGUI() {
QVBoxLayout *l = new QVBoxLayout;
this->producerLabel = new QLabel;
l->addWidget(producerLabel);
this->consumer1Label = new QLabel;
l->addWidget(consumer1Label);
this->consumer2Label = new QLabel;
l->addWidget(consumer2Label);
this->consumer3Label = new QLabel;
l->addWidget(consumer3Label);
this->setLayout(l);
}
void keyPressEvent(QKeyEvent* event) {
if(event->key() == Qt::Key_S) {
qDebug() << "pressed s, stop all";
stopAll();
}
if(event->key() == Qt::Key_R) {
qDebug() << "pressed r, restart all";
initProducer();
initConsumers();
}
}
void closeEvent(QCloseEvent * event)
{
emit shutdown();
this->close();
}
private:
QLabel *producerLabel;
QLabel *consumer1Label;
QLabel *consumer2Label;
QLabel *consumer3Label;
Resources r;
Producer *producer;
Consumer *consumer1;
Consumer *consumer2;
Consumer *consumer3;
int consumerCounter;
private slots:
void showProducer(int n) {
this->producerLabel->setText(QString("Producer: %1").arg(n));
}
void showConsumer1(int n) {
this->consumer1Label->setText(QString("Consumer1: %1").arg(n));
}
void showConsumer2(int n) {
this->consumer2Label->setText(QString("Consumer2: %1").arg(n));
}
void showConsumer3(int n) {
this->consumer3Label->setText(QString("Consumer3: %1").arg(n));
}
void incrementConsumerCounter() {
consumerCounter++;
if(consumerCounter==3) {
qDebug() << "..... could restart!";
initProducer();
initConsumers();
}
}
signals:
void shutdown();
};
#endif // MAINWIDGET_H
</code></pre>
<p><strong>resources.h:</strong></p>
<pre><code>#ifndef RESOURCES_H
#define RESOURCES_H
#include <QDebug>
#include <QReadWriteLock>
#include <QWaitCondition>
class Resources {
public:
Resources() {
qDebug() << "Resources > ctor";
lastFrame = 0;
}
~Resources() {
qDebug() << "Resources > dtor";
}
int lastFrame;
QReadWriteLock lastFrame_read;
QReadWriteLock lastFrame_write;
QWaitCondition waitCondition;
};
#endif // RESOURCES_H
</code></pre>
<p><strong>producer.h:</strong></p>
<pre><code>#ifndef PRODUCER_H
#define PRODUCER_H
#include <QDebug>
#include <QThread>
#include <QMutex>
#include <QReadWriteLock>
#include <QWaitCondition>
#include "resources.h"
class Producer : public QThread
{
Q_OBJECT
public:
explicit Producer(Resources *r, QObject *parent = 0) :
QThread(parent),
abort(false)
{
qDebug() << "producer > ctor";
frameCount = 0;
this->r = r;
}
~Producer() {
qDebug() << "Producer dtor";
stopProduce();
wait();
}
void stopProduce() {
abortMutex.lock();
abort = true;
abortMutex.unlock();
}
protected:
Resources *r;
int frameCount;
void produce()
{
frameCount++;
r->lastFrame = frameCount;
qDebug() << QString("Producing: %1").arg(frameCount);
emit newFrame(frameCount);
}
void run()
{
forever {
abortMutex.lock();
if(abort) {
abortMutex.unlock();
break;
} abortMutex.unlock();
r->lastFrame_read.lockForRead();
produce();
r->waitCondition.wakeAll();
r->lastFrame_read.unlock();
msleep(200);
}
emit finished();
}
private:
QMutex abortMutex;
bool abort;
signals:
void newFrame(int);
};
#endif // PRODUCER_H
</code></pre>
<p><strong>consumer.h:</strong></p>
<pre><code>#ifndef CONSUMER_H
#define CONSUMER_H
#include <QDebug>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QReadWriteLock>
#include <QString>
#include "resources.h"
class Consumer : public QThread
{
Q_OBJECT
public:
Consumer(int id, Resources *r, QObject *parent=0):
QThread(parent),
abort(false)
{
this->r = r;
this->id = id;
}
~Consumer() {
qDebug() << QString("Consumer %1 dtor").arg(id);
stopConsume();
wait();
}
void stopConsume() {
abortMutex.lock();
abort = true;
abortMutex.unlock();
}
protected:
Resources *r;
int id;
int consumeMessage(int val)
{
qDebug() << QString("#%1 Consuming : %2").arg(id).arg(val);
msleep(1000*id);
emit newComputation(val);
return val;
}
void run()
{
forever {
r->lastFrame_read.lockForRead();
consumeMessage(r->lastFrame);
r->lastFrame_read.unlock();
// I think that this check MUST be done here:
// between the consume and the wait
abortMutex.lock();
if(abort) {
abortMutex.unlock();
break;
} abortMutex.unlock();
qDebug() << QString("Consumer %1: going to sleep").arg(id);
r->waitCondition.wait(&r->lastFrame_read);
qDebug() << QString("Consumer %1: awake").arg(id);
}
emit finished();
}
private:
QMutex abortMutex;
bool abort;
signals:
void newComputation(int);
void finished();
};
#endif // CONSUMER_H
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:09:10.463",
"Id": "64430",
"Score": "1",
"body": "I'm afraid I don't have the familiarity with QT needed to give you good feedback, but I did want to say that this is very good beginner code. The names make sense, the code is not indented halfway across the screen, and the methods don't scroll off the screen. Well done, and I hope someone who knows more will be able to give you better feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:53:47.257",
"Id": "64597",
"Score": "0",
"body": "thank you for the feedback. Anything about the threading logics?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T17:25:35.230",
"Id": "64604",
"Score": "0",
"body": "I'm afraid not. I lack the knowledge of Qt needed for that."
}
] |
[
{
"body": "<p>First of all: your code is not bad; I agree with <a href=\"https://codereview.stackexchange.com/users/10084/wayne-conrad\">Wayne Conrad</a>.</p>\n\n<p>I have a minor remark about the connect statement. You are currently using Qt 4.8, so this is fine as it is. However with Qt 5 a <a href=\"https://wiki.qt.io/New_Signal_Slot_Syntax\" rel=\"nofollow\">new signal/slot syntax</a> was introduced.</p>\n\n<p><strong>Your question about threading:</strong> Don't be afraid of <code>QThread</code>, they're just threads too. The problem with <code>QThread</code> is only this: a lack of consistent documentation. You have probably looked up the <a href=\"http://doc.qt.io/qt-4.8/threads-starting.html\" rel=\"nofollow\">documentation of <code>QThread</code></a> and ended up subclassing <code>QThread</code>. There's nothing seriously wrong with this approach but if you want to use the event loop it becomes difficult. </p>\n\n<p>I ended up in exactly the same situation in one of my projects. Then I came across <a href=\"https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/\" rel=\"nofollow\">a very interesting post of Maya Posch</a>. You may also want to read <a href=\"http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/\" rel=\"nofollow\">Bradley T. Hughes' post</a> - one of the Qt core developers - where he admits the mistakes of the past (and even takes blame for it: i take my hat off to so much honesty). <a href=\"http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-1/\" rel=\"nofollow\">Debao's Blog</a> has a good overview of the QThread history and how to do it wrong and right. (<a href=\"http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-2/\" rel=\"nofollow\">Part 2 here</a>). He has a short conclusion:</p>\n\n<ul>\n<li><strong>Subclass QThread and reimplement its run() function</strong> is intuitive and there are still many perfectly valid reasons to subclass QThread, but when event loop is used in worker thread, it's not easy to do it in the right way.</li>\n<li><strong>Use worker objects by moving them to the thread</strong> is easy to use when event loop exists, as it has hidden the details of event loop and queued connection.</li>\n</ul>\n\n<p>To summarize, you would subclass from QObject instead of QThread:</p>\n\n<pre><code>class Producer : public QObject\n{\n Q_OBJECT\npublic:\n explicit Producer(Resources *r, QObject *parent = 0) \n // ...\n</code></pre>\n\n<p>and then create your producer this way:</p>\n\n<pre><code>QThread* producerthread = new QThread;\nProducer* producer = new Producer();\nproducer->moveToThread(producerthread);\nconnect(producer, SIGNAL(error(QString)), this, SLOT(errorString(QString)));\nconnect(producerthread, SIGNAL(started()), producer, SLOT(process()));\nconnect(producer, SIGNAL(finished()), producerthread, SLOT(quit()));\nconnect(producer, SIGNAL(finished()), producer, SLOT(deleteLater()));\nconnect(producerthread, SIGNAL(finished()), producerthread, SLOT(deleteLater()));\n\nconnect(producer, SIGNAL(newFrame(int)), this, SLOT(showProducer(int)));\n\nproducerthread->start();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-28T20:48:46.567",
"Id": "105952",
"ParentId": "29589",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T14:41:14.887",
"Id": "29589",
"Score": "6",
"Tags": [
"c++",
"beginner",
"multithreading",
"qt",
"producer-consumer"
],
"Title": "1 producer, n consumer with QThread"
}
|
29589
|
<p>I've put together the code below, which creates a new sheet in my workbook and applies dynamically-named ranges and page-formatting. </p>
<pre><code>Sub UniqueOverheads()
Set rOverheadsList = Range([B4], [B4].End(xlDown))
Set rOverheadsActuals = Range([C4], [C4].End(xlDown))
Set rOApr = Range([D4], [D4].End(xlDown))
Set rOMay = Range([E4], [E4].End(xlDown))
Set rOJun = Range([F4], [F4].End(xlDown))
Set rOJul = Range([G4], [G4].End(xlDown))
Set rOAug = Range([H4], [H4].End(xlDown))
Set rOSep = Range([I4], [I4].End(xlDown))
Set rOOct = Range([J4], [J4].End(xlDown))
Set rONov = Range([K4], [K4].End(xlDown))
Set rODec = Range([L4], [L4].End(xlDown))
Set rOJan = Range([M4], [M4].End(xlDown))
Set rOFeb = Range([N4], [N4].End(xlDown))
Set rOMar = Range([O4], [O4].End(xlDown))
Worksheets.Add(after:=Worksheets(4)).Name = "Overheads"
Range("B3").Select
ActiveCell.FormulaR1C1 = "Overheads Code"
With Selection.Interior
.ColorIndex = 37
.Pattern = xlSolid
End With
Selection.Font.Bold = True
Cells.Select
With Selection.Font
.Name = "Lucida Sans"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
ActiveWorkbook.Names.Add Name:="OverheadsList", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOverheadsList.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OverheadsActuals", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOverheadsActuals.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OApr", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOApr.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OMay", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOMay.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OJun", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOJun.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OJul", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOJul.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OAug", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOAug.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OSep", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOSep.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OOct", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOOct.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="ONov", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rONov.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="ODec", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rODec.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OJan", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOJan.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OFeb", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOFeb.Address(ReferenceStyle:=xlR1C1)
ActiveWorkbook.Names.Add Name:="OMar", RefersToR1C1:="=" & _
ActiveSheet.Name & "!" & rOMar.Address(ReferenceStyle:=xlR1C1)
End Sub
</code></pre>
<p>The code does work, but I'm a little concerned that it may be a little clunky and could be written smarter. I'm relatively new to VBA but I'm willing to learn. I'm wondering if someone, who is perhaps a more seasoned programmer than myself, could look at this. Please offer some guidance on how I may be able to write this a little better.</p>
|
[] |
[
{
"body": "<p>Try to avoid using <code>Select</code>. I have fixed that for you. </p>\n\n<p>This line: <code>Range(Cells(4, i + 2), Cells(Cells(Rows.Count, i + 2).End(xlUp).Row, i + 2)).Address(ReferenceStyle:=xlR1C1)</code></p>\n\n<p>may require you to add <code>Sheets(\"SheetName\")</code> separated by dot <code>.</code> before Range to specify the sheet you want the data to refer to.</p>\n\n<p>Also added <code>Columns.Autofit</code> at the end to automatically resize column widths upon completion</p>\n\n<pre><code>Sub UniqueOverheads()\n\n Worksheets.Add(after:=Worksheets(4)).Name = \"Overheads\"\n\n With Sheets(Sheets.Count).Range(\"B3\")\n .Value = \"Overheads Code\"\n .Interior.ColorIndex = 37\n .Interior.Pattern = xlSolid\n .Font.Bold = True\n End With\n With Sheets(Sheets.Count).Cells.Font\n .Name = \"Lucida Sans\"\n .Size = 10\n .Strikethrough = False\n .Superscript = False\n .Subscript = False\n .OutlineFont = False\n .Shadow = False\n .Underline = xlUnderlineStyleNone\n .ColorIndex = xlAutomatic\n End With\n\n Dim names As Variant\n names = Array(\"OverheadsList\", \"OverheadsActuals\", \"OApr\", \"OMay\", \"OJun\", \"OJul\", \"OAug\", \"OSep\", _\n \"OOct\", \"ONov\", \"ODec\", \"OJan\", \"OFeb\", \"OMar\")\n\n For i = LBound(names) To UBound(names)\n ActiveWorkbook.names.Add Name:=names(i), RefersToR1C1:=\"=\" & _\n ActiveSheet.Name & \"!\" & _\n Range(Cells(4, i + 2), Cells(Cells(Rows.Count, i + 2).End(xlUp).Row, i + 2)).Address(ReferenceStyle:=xlR1C1)\n Next i\n Columns.AutoFit\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T10:01:09.810",
"Id": "48239",
"Score": "0",
"body": "Hi @mehow, that's abosultely great. Thank you very much for taking the time to reply to my post and for the solution. Kind regards"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-27T14:43:37.990",
"Id": "30309",
"ParentId": "29593",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "30309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T17:17:52.547",
"Id": "29593",
"Score": "3",
"Tags": [
"vba"
],
"Title": "Dynamic ranges and page-formatting"
}
|
29593
|
<p>This is a whole class I wrote. I am on my third day learning Java, so I think I would benefit a lot from a general review. At first I thought whole class would be too large, but <a href="https://codereview.meta.stackexchange.com/questions/729/how-long-is-long-code">this</a> says it is ok.</p>
<pre><code>/**
* WikiCategory
*
* There is no copyright, do whatever you want with this.
* @author Yaşar Arabacı
* @date 10.08.2013
*/
package wikicategory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* Given a category like "Category:Psychology" and an endpoint like
* http://en.wikipedia.org/w/api.php this class will attempt to get all articles
* belonging to that category. it can write those to a file, or give you a
* JSONObject of all the articles.
*
* @author yasar
*/
public class WikiCategory {
private static final String EXPLANATION = "Export a category";
private String userAgent;
private String endPoint;
private String category;
private JSONObject pages;
private HashMap<String, String> params;
/**
* @param name Your name
* @param eMail your e-mail
* @param endPoint meadia wiki api endpoint e.g.
* http://en.wikipedia.org/w/api.php
* @param category The category you would like to get. e.g
* "Category:Psychology"
*/
public WikiCategory(String name, String eMail, String endPoint, String category) {
this(name, eMail, endPoint);
this.category = category;
this.params.put("gcmtitle", this.category);
}
/**
* please check
* {@link #WikiCategory(String, String, String, String) WikiCategory}
*/
public WikiCategory(String name, String eMail) {
this.params = new HashMap<>();
this.params.put("generator", "categorymembers");
this.params.put("gcmtype", "page");
this.params.put("prop", "revisions");
this.params.put("rvprop", "content");
// params.put("rvparse","1"); // to get html output
this.userAgent = String.format("%s -- Java %s, %s %s", EXPLANATION, System.getProperty("java.version"), name, eMail);
}
/**
* please check
* {@link #WikiCategory(String, String, String, String) WikiCategory}
*/
public WikiCategory(String name, String eMail, String endPoint) {
this(name, eMail);
this.endPoint = endPoint;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endPoint) {
this.endPoint = endPoint;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/* DEBUGGINGG PURPOSES ONLY
public static void main(String[] args) {
WikiCategory wk = new WikiCategory("Yaşar Arabacı", "yasar11732@gmail.com",
"http://en.wikipedia.org/w/api.php", "Category:Psychology");
wk.run();
wk.saveToFiles(".txt");
// System.out.println("function returned: " + pages);
} /**/
/**
* calls {@link #saveToFiles(File, String) saveToFiles} with targetDir set
* to current directory and suffix set to "".
*/
public void saveToFiles() {
saveToFiles(new File(System.getProperty("user.dir"), "wiki"), "");
}
/**
* calls {@link #saveToFiles(File, String) saveToFiles} with targetDir set
* to current directory/wiki and suffix set to fileSuffix.
*/
public void saveToFiles(String fileSuffix) {
saveToFiles(new File(System.getProperty("user.dir"), "wiki"), fileSuffix);
}
/**
* After calling {@link #run() run} you can call this function to save
* retrieved pages to files in disk
*
* @param targetDir where to save the files
* @param fileSuffix it will be used as file extension
*/
public void saveToFiles(File targetDir, String fileSuffix) {
// System.out.println(this.pages);
if (targetDir.exists() && !targetDir.isDirectory()) {
return;
}
if (!targetDir.exists() && !targetDir.mkdir()) {
return;
}
for (Iterator it = this.pages.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
JSONObject current = (JSONObject) this.pages.get(key);
File destFile = new File(targetDir, URLEncoder.encode(current.get("title").toString() + fileSuffix));
System.out.println("File will be" + destFile);
JSONArray revisions = (JSONArray) current.get("revisions");
JSONObject firstRev = (JSONObject) revisions.get(0);
try {
if (!destFile.exists() && !destFile.createNewFile()) {
System.out.println("Couldn't create target file:" + destFile);
return;
}
} catch (IOException ex) {
Logger.getLogger(WikiCategory.class.getName()).log(Level.SEVERE, null, ex);
return;
}
try {
PrintWriter writer = new PrintWriter(destFile, "UTF-8");
writer.print((String) firstRev.get("*"));
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(WikiCategory.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(WikiCategory.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private HashMap<String, String> getParams() {
return this.params;
}
public String getUserAgent() {
return this.userAgent;
}
private static String makeQueryString(HashMap<String, String> args) {
StringBuilder sb = new StringBuilder();
for (String key : args.keySet()) {
sb.append(URLEncoder.encode(key));
sb.append("=");
sb.append(URLEncoder.encode(args.get(key)));
sb.append("&");
}
/* there is an extra "&" at the end*/
if (sb.length() > 1) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
public JSONObject run() {
if (this.endPoint == null || this.category == null) {
System.err.println("endpoint or category is not set");
return null;
}
JSONObject query = get("query", this.getParams());
JSONObject currentPages = (JSONObject) ((JSONObject) query.get("query")).get("pages");
while (query.get("query-continue") != null) {
HashMap<String, String> nparams = new HashMap<>(this.params);
JSONObject queryContinue = (JSONObject) query.get("query-continue");
JSONObject categoryMembers = (JSONObject) queryContinue.get("categorymembers");
String gcmContinue = (String) categoryMembers.get("gcmcontinue");
nparams.put("gcmcontinue", gcmContinue);
query = get("query", nparams);
currentPages.putAll((JSONObject) ((JSONObject) query.get("query")).get("pages"));
}
this.pages = currentPages;
return this.pages;
}
private JSONObject get(String action, HashMap<String, String> queryArgs) {
queryArgs.put("action", action);
queryArgs.put("format", "json");
String queryString = makeQueryString(queryArgs);
String url = String.format("%s?%s", this.endPoint, queryString);
System.out.println(url);
try {
URL urlObj = new URL(url);
JSONParser parser = new JSONParser();
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", this.userAgent);
Object obj = parser.parse(new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF8")));
JSONObject jsonObject = (JSONObject) obj;
if (jsonObject.get("error") != null) {
System.err.println(jsonObject.get("error"));
return null;
} else {
return jsonObject;
}
} catch (IOException e) {
System.err.println("Couldn't establish http connection" + e.getMessage());
return null;
} catch (ParseException pe) {
System.err.println("Couldn't parse returned data as json:" + pe.getPosition());
return null;
}
}
}
</code></pre>
<p>Here you can find <a href="https://raw.github.com/yasar11732/wikicategory/master/wikicategory/WikiCategory.java" rel="nofollow noreferrer">whole file</a>. And this is <a href="https://github.com/yasar11732/wikicategory" rel="nofollow noreferrer">github repository</a>. And here you can find <a href="http://yasar11732.github.io/wikicategory/" rel="nofollow noreferrer">Javadoc</a> of it. I am open to any kind of criticism about anything. If you don't have time to read the whole thing, I am also open to partial review.</p>
|
[] |
[
{
"body": "<p><code>this.params</code> is superfluous; just use <code>params</code>.</p>\n\n<p>Use <code>modern</code> for loops, not with <code>iterator</code>.</p>\n\n<p>Use <code>entrySet</code> iterators to avoid map lookups in loops.</p>\n\n<p>Close the <code>printwriter</code> in a <code>finally</code> block, or use <code>try-with-resources</code>.</p>\n\n<p>Unless there is a need to, define your collection references as interfaces, not classes.</p>\n\n<p>Close your <code>HttpURLConnection</code> in a <code>finally</code> block.</p>\n\n<p>Tt's not internationalizable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T19:53:43.557",
"Id": "29596",
"ParentId": "29595",
"Score": "4"
}
},
{
"body": "<p>A few notes (in addition to other answers):</p>\n\n<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html#encode%28java.lang.String%29\" rel=\"nofollow noreferrer\"><code>URLEncoder.encode(String)</code></a> is depreciated. You should be using the other method in the URLEncoder class: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html#encode%28java.lang.String,%20java.lang.String%29\" rel=\"nofollow noreferrer\"><code>URLEncoder.encode(String, String)</code></a>. The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., <code>UTF-8</code>).</p>\n\n<hr>\n\n<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html\" rel=\"nofollow noreferrer\">Iterator</a> is a raw type (in the <code>for</code> loop). <a href=\"https://stackoverflow.com/questions/13169186/java-warning-references-to-generic-type-should-be-parameterized\">References to generic type Iterator should be parameterized.</a> Better yet, just use a <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html\" rel=\"nofollow noreferrer\"><code>for-each</code> loop</a> (as suggested in other answers).</p>\n\n<hr>\n\n<p>Your <code>if</code> statements:</p>\n\n<pre><code>if (targetDir.exists() && !targetDir.isDirectory())\n{\n return;\n}\n</code></pre>\n\n<p>Could be simplified to one line, since they are exit condition tests:</p>\n\n<pre><code>if (targetDir.exists() && !targetDir.isDirectory()) return;\n</code></pre>\n\n<p>It makes it more easy to read and takes up less space.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T22:35:49.697",
"Id": "29599",
"ParentId": "29595",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T19:41:45.167",
"Id": "29595",
"Score": "7",
"Tags": [
"java",
"beginner"
],
"Title": "WikiCategory class"
}
|
29595
|
<p>I am writing a board game program in Java. Slightly similar to chess or civilization in that each player has a set of units, and each unit has certain actions that it can take.</p>
<p>The base <code>GameAction</code> class has two methods: One which checks to make sure the action is allowed, and one to actually do the action. For example, <code>MoveAction</code>'s <code>checkValidity()</code> checks to see if the target is in range, and returns true if it is and false if it isn't, and then <code>doTask()</code> has the precondition that <code>checkValidity()</code> must return true for the same arguments... hopefully that makes sense.</p>
<p>However, these <code>GameAction</code> rules are implemented internally as stateless immutable classes so that every unit can use the same ones, to make parsing the config file easier and to make changing the actions that a given type can perform on the fly easier. For example, if I want to give all cavalry a new ability, all I have to do is change it in one place instead of finding every existing cavalry unit and adding it.</p>
<p>This leads to some serious code duplication though, between <code>checkValidity()</code> and <code>doTask()</code>... here is an example:</p>
<pre><code>package elipsis.aow.actions;
import elipsis.aow.Board;
import elipsis.aow.GameAction;
import elipsis.aow.HexCell;
import elipsis.aow.HexCoordinate;
import elipsis.aow.Player;
import elipsis.aow.Resource;
import elipsis.aow.Unit;
import elipsis.aow.UnitStack;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Causes a unit to be built (either creating a new one altogether, or just
* incrementing an existing unitstack by one, and then reflecting that creation
* in the owner's census data.
* @author scott
*/
public class BuildUnitAction extends GameAction {
private Unit toBuild;
public BuildUnitAction(Unit unit) {
super(String.format("Build %s", unit.getName()));
this.toBuild = unit;
}
/**
* Check for validity of the action.
*
* In the case of a build unit action:
* <p>The owner must have the requisite resources.</p>
* <p>The cells must be on top of or directly adjacent to the structure building.</p>
* <p>The target cell must contain either no unit or a unitstack owned by the
* current owner whose type is the same.</p>
* @param owner
* @param b
* @param begin
* @param end
* @return
*/
@Override
public boolean checkValidity(Player owner, Board b, HexCoordinate begin, HexCoordinate end) {
if (!owner.hasResourcesFor(toBuild.getBuildCosts())) {
return false;
}
HexCell start = b.getCell(begin);
HexCell stop = b.getCell(end);
if (!begin.equals(end) && !start.getAdjacent().contains(end)) {
return false;
}
UnitStack existent = stop.getUnit();
if (existent != null) {
if (!existent.getType().equals(toBuild) ||
!existent.getOwner().equals(owner)) {
return false;
}
}
return true;
}
@Override
public Set<HexCoordinate> doTask(Player owner, Board b, HexCoordinate begin, HexCoordinate end) {
Set<HexCoordinate> output = new HashSet<>(Arrays.asList(end));
HexCell hcStop = b.getCell(end);
UnitStack usOld = hcStop.getUnit();
Map<String, ActionFlags> logOld;
int strOld;
if (usOld == null) {
logOld = null;
strOld = 0;
} else {
logOld = usOld.getActionLog();
strOld = usOld.getStrength();
}
UnitStack usNew = new UnitStack(toBuild, strOld + 1, owner);
if (logOld != null) {
usNew.getActionLog().putAll(logOld);
}
hcStop.setUnit(usNew);
owner.changeArmySize(toBuild, 1);
// Find the cost and charge the owner.
Map<Resource, Integer> buildCost = toBuild.getBuildCosts();
owner.chargeBill(buildCost);
return output;
}
}
</code></pre>
<p>As you can see, both methods have to repeat the <code>getCell()</code> and so on.</p>
<p>Then the actions are called like this:</p>
<pre><code>// ....
if (gameAction.checkValidity(player, board, startCoords, endCoords)) {
Set<HexCoordinate> affected = gameAction.doTask(p, board, startCoords, endCoords);
hfField.notifyCellsChanged(affected);
pidPlayer.playerChanged(p);
}
// ....
</code></pre>
<p>I'm looking for advice on whether the way this is set up smells bad to anyone else, and if so, what are some things I can do to fix it, and if not, what I can do to reduce the duplication.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T00:08:47.220",
"Id": "46827",
"Score": "1",
"body": "It doesn't look excessively redundant to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:11:45.720",
"Id": "46907",
"Score": "0",
"body": "The most obvious candidate would be exceptions. Probably with a rollback method which is called in the catch case. Your thoughts about them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T19:44:48.097",
"Id": "46918",
"Score": "0",
"body": "I have nothing against exceptions at all. The way its designed now is that there is a contract: if checkValidity() returns true, then it is definitely safe to call doAction () with the same arguments. So doAction can assume that checkValidity returned true and thus doesn't need to do any sanity checking. So the hope is to prevent exceptions in that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T19:47:01.920",
"Id": "46919",
"Score": "0",
"body": "I guess this wasn't the best example to illustrate the problem though. Maybe the drawback of the design is just simply that both methods need to do the same setup stuff. Might be that there really is no easy answer without a total redesign. So be it I suppose"
}
] |
[
{
"body": "<p>I think that this type of setup should work fine. If you find yourself repeating multiple steps in various places in code, you could move that functionality to a utility class with static methods. As long as a unit of code can be considered stateless, you should be able to move it to a static method.</p>\n\n<p>Here is a simple example that may hint at what I'm talking about:\nSay you have some code you've been repeating in 4 different classes, such as checking a particular resource is above a certain point.</p>\n\n<pre><code>public class ResourceUtils {\n public static boolean resourceCheck(Resource r, float cost)\n {\n return r != null && r.getResourceLevel() >= cost;\n }\n}\n</code></pre>\n\n<p>Now you can call this from anywhere else in code:</p>\n\n<pre><code>float cost = 20.4f;\nif(ResourceUtils.resourceCheck(goldResource,cost))\n{\n ResourceUtils.transaction(goldResource,cost))\n buildUnit();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:16:50.087",
"Id": "29701",
"ParentId": "29597",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29701",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T21:23:36.823",
"Id": "29597",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"game",
"immutability"
],
"Title": "Removing redundancy from an immutable \"rules class\""
}
|
29597
|
<p>Many years ago, I wrote a script in Perl that was meant to create a cached metadata of MP3 files (in Apple's plist/XML format) which iTunes uses when you insert a CD/DVD full of MP3 files (the same would be true for AAC files, but I limited the scope of my project, due to lack of usable libraries back then).</p>
<p>Since my Perl is rusty, I would love to have some feedback and constructive criticism on how to make the script better, especially regarding readability.</p>
<p>Since the script is trivial, but long, I don't know how much I should put it here. The <a href="https://github.com/rbrito/scripts/blob/master/m3s" rel="nofollow">whole script</a> is in one of my github repositories, if you want to see it.</p>
<p>An abridged version of it is:</p>
<pre><code>#!/usr/bin/perl -W
# Copyright (C) 2009 Rogério Brito <rbrito@users.sf.net>
# This program is Free Software and is distributed under the terms of
# the GNU General Public License version 2 or, at your option, any
# latter version.
use strict 'vars';
use warnings;
use utf8;
use Encode qw(encode decode);
use MP3::Tag;
# ==============================================================================
# Auxiliary functions for generation of the output
sub pr_header {
print FH <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Current Version</key><integer>1</integer>
<key>Compatible Version</key><integer>1</integer>
<key>Application</key><string>m3s v0.0</string>
<key>Burner Info</key><string>$_[0]</string>
<key>Disc ID</key><string>$_[1]</string>
<key>Disc Name</key><string>$_[2]</string>
<key>tracks</key>
<array>
EOF
}
sub pr_footer { print FH "\t</array>\n</dict>\n</plist>\n"; }
# ==============================================================================
# Functions to generate the proper XML tags for iTunes.
sub pr_open_dict { print FH "\t\t<dict>\n"; }
sub pr_key { print FH "\t\t\t<key>", my_utf8_encode($_[0]), "</key>"; }
sub pr_string { print FH "<string>", my_utf8_encode($_[0]), "</string>\n"; }
sub pr_integer { print FH "<integer>", my_utf8_encode($_[0]), "</integer>\n"; }
sub pr_date { print FH "<date>", my_utf8_encode($_[0]), "</date>\n"; }
sub pr_boolean { print FH ($_[0])?"<true/>\n":"<false/>\n"; }
sub pr_close_dict { print FH "\t\t</dict>\n"; }
# ==============================================================================
# Auxiliary functions
sub gen_serial_no {
return sprintf("%04X%04X%04X%04X", rand(0xffff), rand(0xffff),
rand(0xffff), rand(0xffff));
}
sub escape_char { my $st = shift; $st =~ s/&/&#38;/g; return $st; }
sub my_utf8_encode { return escape_char(encode("utf8", $_[0])); }
sub recurse_dir {
my $dh;
opendir($dh, $_[0]) or die("Error opening dir $_[0]: $!\n");
my $par_name = $_[1];
my $file_no = 0;
my $dir_no = 0;
# grep {!/\.|\.\./}
foreach (sort readdir($dh)) { # for each entry
my $name = "$_[0]/$_";
if (-d $name and $_ ne "." and $_ ne "..") {
++$dir_no;
recurse_dir($name, $par_name?"$par_name:$dir_no":$dir_no, $dir_no);
} elsif ($_ ne "." and $_ ne "..") {
++$file_no;
my $filename = $_[0];
if (m!\.mp3$!i) {
generate_song_entry("$_[0]/$_",
$par_name?"$par_name:$file_no":$file_no,
$file_no);
}
}
}
closedir($dh) or die("Error closing dir $_[0]: $!\n");
}
# ==============================================================================
# Function to grab information from an MP3 file
sub generate_song_entry {
# initialize mp3 object
my $mp3 = new MP3::Tag $_[0];
# Perform the information gathering from the file:
my ($title, $track, $artist, $album, $comment, $year, $genre) = $mp3->autoinfo();
my ($track1, $track2, $disc1, $disc2) = ($mp3->track1(), $mp3->track2(),
$mp3->disk1(), $mp3->disk2());
my ($time, $bitrate, $frequency, $is_vbr, $size) = (int($mp3->total_secs()*1000),
$mp3->bitrate_kbps(),
$mp3->frequency_Hz(),
$mp3->is_vbr(),
$mp3->size_bytes());
# destroy object
$mp3->close();
# Now, we fill in the entry for this file
pr_open_dict();
if (defined($title)) { pr_key("Name"); pr_string($title); }
if (defined($artist)) { pr_key("Artist"); pr_string($artist); }
if (defined($album)) { pr_key("Album"); pr_string($album); }
if (defined($genre)) { pr_key("Genre"); pr_string($genre); }
if (defined($year)) { pr_key("Year"); pr_integer($year); }
if (defined($track1)) { pr_key("Track Number"); pr_integer($track1); }
if (defined($track2)) { pr_key("Track Count"); pr_integer($track2); }
if (defined($disc1)) { pr_key("Disc Number"); pr_integer($disc1); }
if (defined($disc2)) { pr_key("Disc Count"); pr_integer($disc2); }
if (defined($time)) { pr_key("Total Time"); pr_integer($time); }
if (defined($bitrate)) { pr_key("Bit Rate"); pr_integer($bitrate); }
if (defined($frequency)) { pr_key("Sample Rate"); pr_integer($frequency); }
if (defined($is_vbr)) { pr_key("Has Variable Bit Rate"); pr_boolean($is_vbr); }
if (defined($size)) { pr_key("Size"); pr_integer($size); };
if ((exists($mp3->{ID3v1}) or exists($mp3->{ID3v2}))) {
pr_key("Supports ID3 Tags"); pr_boolean("true");
}
# Compulsory filling
{ pr_key("Date"); pr_string(12345678); };
{ pr_key("Date Modified"); pr_date("2009-03-02T19:50:00Z"); };
{ pr_key("Numeric Path"); pr_string("$_[1]"); };
{ pr_key("File Extension"); pr_string("mp3"); };
pr_close_dict();
}
# ==============================================================================
# main program
my $root = defined($ARGV[0])?$ARGV[0]:".";
my $file = "$root/ContentsDB.xml";
my $title = defined($ARGV[1])?my_utf8_encode($ARGV[1]):"My MP3 CD-ROM";
my $burner = defined($ARGV[2])?my_utf8_encode($ARGV[2]):"DVD-ROM DRIVE";
my $serial = gen_serial_no();
open(FH, ">$file") or die("Error opening file $file: $!\n");
pr_header($burner, $serial, $title);
recurse_dir($root, "");
pr_footer();
close(FH) or die("Error closing file $file: $!\n");
</code></pre>
|
[] |
[
{
"body": "<p>I'd replace</p>\n\n<pre><code>foreach (sort readdir($dh)) { # for each entry\nmy $name = \"$_[0]/$_\";\nif (-d $name and $_ ne \".\" and $_ ne \"..\") {\n ...\n} elsif ($_ ne \".\" and $_ ne \"..\") {\n ...\n</code></pre>\n\n<p>with</p>\n\n<pre><code>foreach my $fn (sort readdir($dh)) { # for each entry\nnext if $fn =~ /^\\./;\nmy $name = \"$_[0]/$fn\";\nif (-d $name) {\n ...\n} else {\n ...\n</code></pre>\n\n<p>Two reasons:</p>\n\n<ol>\n<li><p>You want readability. So, lose generic <code>$_</code> and give it some names (I often use <code>$fn</code> as a temporary <b>f</b>ile<b>n</b>name, so that's readable to me; you may have different names).</p></li>\n<li><p>Every file/dir with name starting with <code>.</code> is considered hidden, so it's usually good practice to skip them all.</p></li>\n</ol>\n\n<p>Similar to the point 1 above, I'd do the same with <code>@_</code>. You can put at the beginning of each subroutine something like</p>\n\n<pre><code>my ($name1, $name2) = @_;\n</code></pre>\n\n<p>and then use <code>$name1$</code> and <code>$name2</code> instead of <code>$_[0]</code> and <code>$_[1]</code>. This makes it easier to see in your code what are <code>$_[$i]</code> and also makes it easier to see what arguments a certain subroutine is expecting.</p>\n\n<p>This one is probably more a matter of taste:</p>\n\n<pre><code>return sprintf(\"%04X%04X%04X%04X\", rand(0xffff), rand(0xffff),\n rand(0xffff), rand(0xffff));\n</code></pre>\n\n<p>can be replace by</p>\n\n<pre><code>return sprintf(\"%04X\"x4, map { rand(0xffff) } (0..3));\n</code></pre>\n\n<p>I prefer the second one, because its easier to discern how many 4-digit hex numbers are there, without counting <code>rand</code>-s or <code>%04X</code> substrings.</p>\n\n<p>Btw, this <code>rand()</code> will never give you 0xffff. If you want to include it, you need <code>rand(0x10000)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T22:05:37.290",
"Id": "46850",
"Score": "0",
"body": "thanks for the comments. I wrote that when I had not learnt about Python and I was using a lot of implicit naming in Perl (which makes it hard to follow one's own code). Regarding the random number generation, thanks for reminding me that the numbers are less than the upper limit. That's a bug in my code. Regarding the ugly `%04X` multiple times, it seems that I can substitute a pair of `%04X` with `%08X` and make the code slightly more readable. With `%016X` I wasn't successful, though..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T22:12:13.960",
"Id": "46851",
"Score": "1",
"body": "[This](http://stackoverflow.com/a/4506609/1667018) might be useful, especially if the code is to run on Win (check the last comment under the answer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T23:01:12.717",
"Id": "46853",
"Score": "0",
"body": "Thanks. I'm actually not worried about running under windows, but that was, at the time, my understanding of the limitations of `rand()`, which was why I opted for calling it many times. OTOH, I would like to keep the script with fewer external dependencies, which means that I may stick with the 4 calls to `rand()`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T08:50:11.540",
"Id": "29605",
"ParentId": "29602",
"Score": "1"
}
},
{
"body": "<p>Agree with what Vedran wrote. I'd also add some prototypes to go with that, so that perl can give you warnings or errors when you miss a parameter; e.g., something like</p>\n\n<pre><code>sub foo($$) {\n\n}\n</code></pre>\n\n<p>to specify that this sub takes two scalars as parameters.</p>\n\n<p>There are some limitations to what you can do with perl's prototypes like this, but it's still useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T21:55:49.170",
"Id": "46849",
"Score": "0",
"body": "yes, the prototype thing is good. Too bad that I don't know how to make them more descriptive (say, like C or Ruby or Python or...) BTW, nice seeing you here! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T11:42:39.733",
"Id": "29613",
"ParentId": "29602",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29605",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T01:18:45.570",
"Id": "29602",
"Score": "3",
"Tags": [
"xml",
"perl",
"cache"
],
"Title": "Perl script for generating iTunes xml Metadata for MP3 CDs/DVDs"
}
|
29602
|
<p>Given a graph in <code>[[sourcevertex,targetvertex],...]</code> format with all the directed edges of the graph I am trying to optimize the code here because it still hasn't stopped running I don't know if it will take days or hours, although it is somewhat working for small input sets. I think the masking/vertex renaming part of the code might be slowing things down, and possibly some inefficient use of various data types... any ideas on how I could make it more efficient?</p>
<p>It basically doesn't even get through the first DFS Loop (been waiting for a long time and wrote this up in the meantime).</p>
<pre><code>import re
import numpy as np
from numpy import copy
from operator import itemgetter
#scc function, given an edge table, find all the SCC's and sort from largest to smallest
def scc(myInputList, mylistlength):
global vertexStateTable
global t
global finishingTime
global vertexStateTable2
#put input list in numpy format
directedGraph = np.array(myInputList)
#define max source
maxSource = directedGraph[:,0].max()
#define max target
maxTarget = directedGraph[:,1].max()
#define max vertex
maxVertex = directedGraph.max()
#define a state table[] [seen vertices set]
vertexStateTable = set([])
#define the finishing time counter
t=0
#define the finishing time dictionary
finishingTime = {}
#dfs loop
for i in reversed(xrange(1, maxVertex+1)):
#check if it's in the vertex state table for vertices already seen
if i not in vertexStateTable:
DFSFinish(directedGraph, i)
print "Completed first round. Finishing Times."
#finishing time dictionary completed, now create equivalent
#create finished list in numpy format, replacing original list with state table finishing times from the first round
finishedDirectedGraph = maskDirectedGraph(directedGraph, finishingTime)
print "Masking Complete."
#set vertexStateTable for second pass
vertexStateTable2 = set([])
#initialize group counter
sccSizes = np.array([])
print "starting outer loop second round."
#dfs loop
for i in reversed(xrange(1,maxVertex + 1)):
#check if it's in the vertex state table, already seen
if i not in vertexStateTable2:
#initialize time
t=0
#DFSFinishingTimes(given list, max vertex, statetable)
DFSSCCFinder(finishedDirectedGraph, i)
#append groups, leader
if sccSizes.size ==0:
sccSizes=np.array([[i,t]])
else:
sccSizes = np.concatenate((sccSizes, [[i,t]]))
print "Completed SCC second round."
#resort scc table by number of members
sortedSCCTable = sorted(sccSizes, key=itemgetter(1), reverse=True)
#return final scc Table
return sortedSCCTable
#function to mask all the elements of the graph using key value pairs from dictionary
def maskDirectedGraph(myGraph, myDictionary):
newGraph = copy(myGraph)
for elem in newGraph:
count0 = 0
count1 = 0
for k, v in myDictionary.iteritems():
if count0+count1 == 2:
break
if elem[0]==k and count0==0:
elem[0]=v
count0+=1
if elem[1]==k and count1==0:
elem[1]=v
count1+=1
return newGraph
#DFSFinishingTimes, given graph and starting vertex(list, vertex i ), perform a DFX loop, update the dictionary table of finishing times
def DFSFinish(myDirectedGraph, myVertex):
#first initialize some variables
global vertexStateTable
global t
global finishingTime
#get usable edges
#find all instances of myvertex in column 2, return pair
wanted_set = set([myVertex]) # Much faster look up than with lists, for larger lists
@np.vectorize
def selected(elmt): return elmt in wanted_set # Or: selected = wanted_set.__contains__
outgoingConnectedEdges = myDirectedGraph[selected(myDirectedGraph[:, 1])]
if myVertex in vertexStateTable:
return
if outgoingConnectedEdges is None:
if myDirectedGraph[selected(myDirectedGraph[:, 0])] is None:
return
#initialize unexploredOutgoingConnectedEdges
unexploredOutgoingConnectedEdges = np.array([])
#get unexplored directed edges.
#loop through outgoing connected edges, keeping only those which are not on the list
for edge in outgoingConnectedEdges:
if edge[0] not in vertexStateTable:
if unexploredOutgoingConnectedEdges.size == 0:
unexploredOutgoingConnectedEdges=np.array([edge])
else:
unexploredOutgoingConnectedEdges = np.concatenate((unexploredOutgoingConnectedEdges, [edge]))
#add current vertex to vertexStateTable as seen.
if myVertex not in vertexStateTable:
vertexStateTable.add(myVertex)
#for each unexplored arc, recursively run the DFSFinish
for unexplored in unexploredOutgoingConnectedEdges:
DFSFinish(myDirectedGraph, unexplored[0])
t = t+1
finishingTime[myVertex] = t
#DFSSCCFinder, given graph with vertices renamed by finishing times, perform DFX loop, counting members instead of assigning finishingTimes
def DFSSCCFinder(myDirectedGraph, myVertex):
global vertexStateTable2
global t
#get usable edges
#find all instances of myvertex in column 1, return pair
wanted_set = set([myVertex]) # Much faster look up than with lists, for larger lists
@np.vectorize
def selected(elmt): return elmt in wanted_set # Or: selected = wanted_set.__contains__
outgoingConnectedEdges = myDirectedGraph[selected(myDirectedGraph[:, 0])]
if myVertex in vertexStateTable2:
return
if outgoingConnectedEdges is None:
if myDirectedGraph[selected(myDirectedGraph[:, 1])] is None:
return
#initialize unexploredOutgoingConnectedEdges
unexploredOutgoingConnectedEdges = np.array([])
#get unexplored directed edges.
#loop through outgoing connected edges, keeping only those which are not on the list
for edge in outgoingConnectedEdges:
if edge[1] not in vertexStateTable2:
if unexploredOutgoingConnectedEdges.size==0:
unexploredOutgoingConnectedEdges = np.array([edge])
else:
unexploredOutgoingConnectedEdges = np.concatenate((unexploredOutgoingConnectedEdges, [edge]))
#add current vertex to myStateTable as seen.
if myVertex not in vertexStateTable2:
vertexStateTable2.add(myVertex)
#for each unexplored arc, recursively run the DFSFinish
for unexplored in unexploredOutgoingConnectedEdges:
DFSSCCFinder(myDirectedGraph, unexplored[1])
#finished node, so increment finishing time counter
t = t+1
#main procedure
while 1==1:
masterInputList = []
try:
with open(raw_input("Text File: ")) as f:
for line in f:
masterInputList.append([int(x) for x in re.findall(r'\b\S+\b',line)])
#define length of unsorted list: listLength
masterListLength = len(masterInputList)
print "List Length = "
print masterListLength
stronglyConnectedComponents = scc(masterInputList, masterListLength)
#then print the sorted list
print "Sorted List of Strongly Connected Component Groups(10):"
iCount=0
for line in stronglyConnectedComponents:
print line
iCount+=1
if iCount>=10:
break
except IOError:
print "File Not Found"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:12:11.813",
"Id": "46963",
"Score": "0",
"body": "For intentionally infinite `while` loops, I recommend just using `while True:` as this is more common practice and seems more readable."
}
] |
[
{
"body": "<p>First, main procedures of an executable Python script should <strong>always</strong> use this at the very bottom of the script to define the main entry point of the program:</p>\n\n<pre><code>if __name__ == '__main__':\n main() # or whatever your main execution code is\n</code></pre>\n\n<p>See Guido van Rossum's well-known post about this topic: <a href=\"http://www.artima.com/weblogs/viewpost.jsp?thread=4829\" rel=\"nofollow\">http://www.artima.com/weblogs/viewpost.jsp?thread=4829</a></p>\n\n<p>Second, your <code>while 1==1</code> statement will always be true, and the <code>break</code> statement you have inside the <code>for</code> loop only exits the <code>for</code> loop...that is, your script will <strong>always</strong> run forever the way you have it set up unless there is an error besides <code>IOError</code> in the <code>try</code> block. If there is an <code>IOError</code>, it will just <code>print \"File Not Found\"</code> and loop over the <code>while</code> statement again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T04:46:12.480",
"Id": "47025",
"Score": "0",
"body": "thanks a lot for looking at it. Advice is noted. I was actually more focused on the performance of this thing... running through my data set, after a closer look, with a large graph, like a million nodes and a few million edges, it basically takes days to complete the calculation due to inefficiency within the recursion..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:04:13.630",
"Id": "29686",
"ParentId": "29603",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T04:27:13.977",
"Id": "29603",
"Score": "1",
"Tags": [
"python",
"algorithm",
"recursion",
"graph"
],
"Title": "Finding strongly connected components of directed graph, kosaraju"
}
|
29603
|
<p>If many threads Borrow() and Return() an instance of Packet from/to PacketPool could the Exception in Packet.Init() ever be thrown? Assuming only PacketPool ever called the Init() and UnInit() methods on a Packet.</p>
<pre><code>class PacketPool
{
private Stack<Packet> pool;
public PacketPool(int initalNum)
{
pool = new Stack<Packet>(initalNum);
for (int i = 0; i < initalNum; i++)
{
Packet p = new Packet();
pool.Push(p);
}
}
public Packet Borrow()
{
Packet p;
lock (pool)
{
if (pool.Count == 0)
{
p = new Packet();
}
else
{
p = pool.Pop();
}
}
p.Init();
return p;
}
public void Return(Packet p)
{
p.UnInit();
lock (pool)
{
pool.Push(p);
}
}
}
class Packet
{
bool isInitialized;
public void Init()
{
if(isInitialized)
throw new InvalidOperationException("Already initialized!");
isInitialized = true;
}
public void UnInit()
{
isInitialized = false;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>No, the exception in Packet.Init() will never be thrown. This is because although there may be multiple threads in Borrow(), the lock statement will ensure that each thread sees its own version of p.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T09:57:16.807",
"Id": "29608",
"ParentId": "29606",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>Assuming only <code>PacketPool</code> ever called the <code>Init()</code> and <code>UnInit()</code> methods on a <code>Packet</code>.</p>\n</blockquote>\n\n<p>I think that's not an assumption you should make. If the user of your code shouldn't call some methods, then don't let him do it, don't just assume that he won't.</p>\n\n<p>What you could do is to return a facade to <code>Packet</code> that doesn't contain the two methods, instead of returning <code>Packet</code> directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T12:54:50.910",
"Id": "46834",
"Score": "0",
"body": "Good point, currently I do have it in it's own namespace and could make the methods internal, though I will still have to be careful!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T21:53:47.187",
"Id": "46848",
"Score": "0",
"body": "@MarkMennell Having the methods internal in their own namespace won't stop a user calling them as classes within the assembly will still have access. My understanding is that those modifiers only work across assemblies themselves. Correct me if I'm wrong there though..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T00:26:00.320",
"Id": "46854",
"Score": "0",
"body": "The modifiers work across namespace - so even in the same assembly if you are not in the namespace you cannot access something marked internal. Anyway the namespace is in it's own assembly, a dll, so a user cannot alter the source code in there either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T06:27:18.047",
"Id": "46861",
"Score": "1",
"body": "@MarkMennell I think we must be thinking of something different. Going from this http://msdn.microsoft.com/en-us/library/ms173121.aspx internal means any class in the assembly (regardless of namespace can see it). Anyway, all to their own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T09:31:26.350",
"Id": "46869",
"Score": "1",
"body": "You are right, my bad!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T12:33:45.023",
"Id": "29614",
"ParentId": "29606",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T08:57:42.820",
"Id": "29606",
"Score": "1",
"Tags": [
"c#",
"thread-safety"
],
"Title": "Thread safe object pool, is this object pool thread safe?"
}
|
29606
|
<p>Here you can find my implementation of <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">sieve of Eratosthenes</a> in Java.</p>
<pre><code>/**
* Return an array of prime numbers up to upperLimit
* using sieve of Erastosthenes.
* @param upperLimit
* @return array of prime numbers up to upperLimit
*/
public static int[] sieve(int upperLimit) {
// for corner cases
if (upperLimit < 2) {
return new int[0];
}
if (upperLimit == 2) {
int[] result = {2};
return result;
}
//--
int arrLength = ((upperLimit - 3) / 2) + 1;
// This arrray will be used to perform the sieve
int[] temp = new int[arrLength];
// Counter for number of primes encountered
int numPrimes = 1; // because of 2
// populate temp array with with 3,5,7,...,upperLimit
for(int i=3; i <= upperLimit; i=i+2) {
temp[(i-3) / 2] = i;
}
// Perform sieve
for(int i=0; i < arrLength; i++ ) {
int num = temp[i];
if (num == 0) continue;
numPrimes++;
for (int k = i+num; k < arrLength; k=k+num) {
temp[k] = 0;
}
}
// Create result array
int[] result = new int[numPrimes];
result[0] = 2;
int currentIndex = 1;
for(int i: temp) {
if (i!=0) result[currentIndex++] = i;
}
return result;
}
</code></pre>
<p>How does it look?</p>
|
[] |
[
{
"body": "<p>A few notes:</p>\n\n<p>Right now you are using <code>int[]</code>s to represent the sieve. However, the <code>int</code> data type is internally stored as 32-bits, which is a waste of space.</p>\n\n<p>Use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html\"><code>java.util.BitSet</code></a> to represent the sieve. It provides a vector of bits that grows as needed. All bits start out as 0, and we can set and clear a bit at any index. It uses only one bit per entry. This requires slightly more computation per access for address computation and bit manipulation, but is much more compact, and utilizes the data cache more efficiently. For larger ranges of integers, we expect memory access time to dominate computation time, making this the ideal solution to represent the sieve.</p>\n\n<hr>\n\n<p>To save additional space and time, at the cost of some additional complexity, we can choose not to represent even integers in our sieve (since they are divisible by 2). Instead, the element at index <code>k</code> will indicate the primarily of the number <code>2k + 3</code>. We abstract this complexity away by wrapping <code>BitSet</code> in a class exposing special indexer methods.</p>\n\n<hr>\n\n<p>Right now you are using <code>i = i + 2</code>, which could be simplified to <code>i += 2</code>.</p>\n\n<hr>\n\n<p>Final code:</p>\n\n<pre><code>import java.util.BitSet;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class Sieve\n{\n private BitSet sieve;\n\n public Sieve(int size)\n {\n sieve = new BitSet((size + 1) / 2);\n }\n\n public boolean isComposite(int k)\n {\n assert k >= 3 && (k % 2) == 1;\n return sieve.get((k - 3) / 2);\n }\n\n public void setComposite(int k)\n {\n assert k >= 3 && (k % 2) == 1;\n sieve.set((k - 3) / 2);\n }\n\n public static List<Integer> sieveOfEratosthenes(int max)\n {\n Sieve sieve = new Sieve(max + 1); // +1 to include max itself\n for (int i = 3; i * i <= max; i += 2)\n {\n if (sieve.isComposite(i)) continue;\n\n // We increment by 2*i to skip even multiples of i\n for (int multiplei = i * i; multiplei <= max; multiplei += 2 * i)\n sieve.setComposite(multiplei);\n }\n\n List<Integer> primes = new ArrayList<Integer>();\n primes.add(2);\n for (int i = 3; i <= max; i += 2)\n if (!sieve.isComposite(i)) primes.add(i);\n return primes;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T16:43:57.613",
"Id": "29616",
"ParentId": "29609",
"Score": "10"
}
},
{
"body": "<p>Your method is complex and it has so many local variables. It will be harder for you when you will be de-bugging or reviewing your method.</p>\n\n<p><strong>Final Code</strong></p>\n\n<pre><code> /**\n * \n * @param upperLimit\n * @return a list of prime numbers from 0 to upperLimit inclusive\n * @throws IllegalArgumentException if upperLimit is less than 0 \n */\n public static List<Integer> generatePrimes(int upperLimit) {\n\n if(upperLimit < 0) \n throw new IllegalArgumentException(\"Negative size\");\n\n // at first all are numbers (0<=i<=n) not composite\n boolean[] isComposite = new boolean[upperLimit + 1]; \n for (int i = 2; i * i <= upperLimit; i++) {\n if (!isComposite [i]) {\n // populate all multiples as composite numbers\n for (int j = i; i * j <= upperLimit; j++) {\n isComposite [i*j] = true;\n }\n }\n }\n\n List<Integer> primeList = new ArrayList<>();\n\n // make a list of all non-composite numbers(prime numbers)\n int arrLength = isComposite.length;\n for(int index = 2; index < arrLength; index++) {\n if(!isComposite[index]) {\n primeList.add(new Integer(index));\n }\n }\n return primeList;\n }\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<pre><code> if (!isComposite [i]) {\n // populate all multiples as composite numbers\n for (int j = i; i * j <= upperLimit; j++) {\n isComposite [i*j] = true;\n }\n }\n</code></pre>\n\n<p>can be improved</p>\n\n<pre><code> if (!isComposite [i]) {\n for (int j = 2 * i; j <= upperLimit; j += i) {\n isComposite [j] = true;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T18:33:45.523",
"Id": "46839",
"Score": "2",
"body": "He kind of does check for negative numbers : the method will return an empty array. Since thre are no negative primes, this iactually correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T18:43:08.450",
"Id": "46840",
"Score": "0",
"body": "No! AFAIK as per convention wrong input method should throw an `IllegalArgumentException`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T19:02:09.443",
"Id": "46842",
"Score": "2",
"body": "It depeds on whether you consider negative input wrong. After all mathematically the set of primes wmaller than -8 *is* the empty set."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T18:11:47.487",
"Id": "29620",
"ParentId": "29609",
"Score": "3"
}
},
{
"body": "<p>I guess I'm confused as to why you would even bother building a list of the prime integers. A BitSet should be far more compact than a list of the integers and can be easily processed for a lot of things.</p>\n\n<p>To check for primeness just directly access that index and you know whether it's prime, or not. </p>\n\n<p>You can also print the list of primes from the BitSet using something similar to what you'd do with the array of integers. You'd just have to check each index for primeness before printing it (not so hard to do).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T23:13:24.190",
"Id": "56291",
"ParentId": "29609",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T10:11:34.443",
"Id": "29609",
"Score": "9",
"Tags": [
"java",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes in Java"
}
|
29609
|
<p>With the Zend coding convention in the back of my mind, <a href="https://github.com/Michal-sk/TargetSMS" rel="nofollow">I have set this up</a>.</p>
<p>It lets you communicate with the API of the vendor <code>TargetSMS</code>. They allow you to bill customers trough SMS. For now I've only spent time on the <code>NonSubscription</code> option.</p>
<p>I would just like to know if it's ok, or what could be better. I am mostly interested in knowing if the <code>TargetSms</code> object could use static methods. For example, I think the <code>isAllowedIp</code> method could be static, since I would like to use it even if the object is not initiated (I was told that's the idea behind static methods).</p>
<p><strong>TargetSMS object</strong></p>
<pre><code><?php
/**
* TargetSMS object with TargetSMS related methods.
*/
namespace TargetPay\Sms;
class TargetSms
{
/**
* The allowed IP of TargetSms.
* @var array
*/
protected $_targetSmsIp = array('89.184.168.65');
/**
* The ok response code for TargetSMS.
* @var number
*/
protected $_responseCode = 45000;
/**
* Check if the request is comming from TargetSMS.
* @param string $ip
* @return boolean
*/
public function isAllowedIp($ip = '')
{
if (in_array($ip, $this->_targetSmsIp)) {
return true;
}
return false;
}
/**
* Get the TargetSMS required responsecode.
* @return number
*/
public function getResponseCode()
{
return $this->_responseCode;
}
/**
* Add a new allowed ip address to the array with allowed ip addresses.
* @param string $ip
*/
public function addAllowedIp($ip = '')
{
$this->_targetSmsIp[] = $ip;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If you wanted to make <code>isAllowdIp</code> static (and there's nothing wrong with that, per se), you -indeed- don't need an instance of your class to call that method. But owing to there being no instance, you won't have access to any non-static properties of your class, either.<br/>\nTo get around that, you'd have to change:</p>\n\n<pre><code>protected $_targetSmsIp = array('89.184.168.65');\n</code></pre>\n\n<p>To </p>\n\n<pre><code>protected static $_targetSmsIp = array('89.184.168.65');\n</code></pre>\n\n<p>And change these method, too:</p>\n\n<pre><code>public static function isAllowedIp($ip)\n{//don't check empty strings, they're always invalid ips!\n return !!in_array($ip, self::$_targetSmsIp);\n}\npublic static function addAllowedIp($ip)\n{//don't allow '' defaults! adding empty strings aren't valid ips\n if (!filter_var($ip, FILTER_VALIDATE_IP))\n {//check what you're adding to the OK-list!\n throw new InvalidArgumentException($ip. ' is not a valid IP');\n }\n self::$_targetSmsIp[] = $ip;\n}\n</code></pre>\n\n<p>This, by itself isn't code that makes my eyes water, but it doesn't exactly sit well with me, either: It's hard to tell what the actual task of your class is: validate IP's/data? Is it the API connection layer?<Br/>\nI gather it's the latter. In which case, I'd define my methods to <em>only</em> accept objects of a given type. This object is where you can filter, check and validate all input... For example, the <code>IpObject</code>:</p>\n\n<pre><code>class IpObject\n{\n private $ip = null;\n private static $valideIps = array();\n public function __construct($ip = null)\n {\n if ($ip)\n {\n $this->setIp($ip);\n }\n }\n public function getIp()\n {\n return $this->ip;\n }\n public function setIp($ip)\n {\n if (!filter_var($ip, FILTER_VALIDATE_IP) || !in_array($ip, self::$validIps))\n {\n throw new InvalidArgumentException($ip.' is not valid');\n }\n $this->ip = $ip;\n return $this;\n }\n}\n</code></pre>\n\n<p>The major problem with your creating statics here is that, by changeing the allowed IP's for one instance, you're changing the allowed IP's accross the board: you can't black-list or OK ip's for instances of your object individually, so after a while it'll get quite tricky to work out which IP's are allowed and which aren't.</p>\n\n<p>All in all, an array in this object won't add <em>too</em> much overhead... not that you notice, and it will make life easier when testing/debugging.<Br/>\nInstead of using statics. having an instance at the ready is 99.99% of times the better option.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-06T09:08:41.463",
"Id": "30868",
"ParentId": "29610",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "30868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T10:26:19.000",
"Id": "29610",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"static"
],
"Title": "Could my object use static methods? Anything I need to do to make the code better?"
}
|
29610
|
<p>I have written a program, in which I have to find the number of occurrences (overlapping + non-overlapping) of a string in another string.</p>
<pre><code>// variable to keep track of word
int i=0;
for(vector<string>::iterator it = p.begin(); it!=p.end(); it++){
frequency[i]=0;
int start=0;
while(true){
start = s.find(*it, start);
if(start==-1){ // not found
break;
} else{
frequency[i]++;
start++;
}
}
i++;
}
</code></pre>
<p>I am finding the starting index <code>start</code> of the match, and then again searching for the string starting from 'start+1' this time, and so on. The length of the string <code>s</code>, in which searching has to be performed is 50,00,000. And total number of keywords (stored in vector <code>p</code> here) is 500 (each having length of 5000).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T12:35:38.157",
"Id": "46833",
"Score": "0",
"body": "What exactly are you looking to improve? Or are you looking for a general review?"
}
] |
[
{
"body": "<p>I don't like nested loops. They are generally unnecessry\nand are often confusing. So instead of your two loops, I would extrac the\ninner loop to a function, for example:</p>\n\n<pre><code>int key_search(const std::string& s, const std::string& key)\n{\n int count = 0;\n size_t pos=0;\n while ((pos = s.find(key, pos)) != std::string::npos) {\n ++count;\n ++pos;\n }\n return count;\n}\n</code></pre>\n\n<p>This searches the inputs string <code>s</code> for occurances of string <code>key</code> and returns\nthe number of matches. A few things are worth noting:</p>\n\n<ul>\n<li><p>The parameters are passed as const references - <code>const</code> because you don't change them and references for efficiency.</p></li>\n<li><p>I used <code>string::npos</code> as the idicator of failure from <code>string</code>s <code>find</code>\nmethod, instead of -1 (-1 would give a warning from the compiler if you have\nsign conversion warnings enabled).</p></li>\n<li><p>I didn't use a <code>while(true)</code> loop but instead used the return from <code>s.find</code>\ndirectly to control the loop.</p></li>\n<li><p>I pre-incremented variables instead of post-increment (++pos, not pos++)\nwhich can be more efficient (although with built in types it makes no\ndifference). </p></li>\n<li><p><code>pos</code> (your <code>start</code>) is of type <code>size_t</code>, not int. Or you could use <code>std::string::size_type</code>, which is the also <code>size_t</code>.</p></li>\n<li><p>It is normal to prefix your use of standard library things with <code>std::</code>, so\n<code>string</code> becomes <code>std::string</code> etc.</p></li>\n</ul>\n\n<p>The main loop now just needs to call <code>key_search</code></p>\n\n<pre><code>int i = 0;\nfor (auto it = keys.begin(); it != keys.end(); ++it){\n frequency[i] = key_search(s, *it);\n ++i;\n}\n</code></pre>\n\n<p>With C++11 you can use <code>auto</code> to simplify the iterator definition. You don't\nshow what <code>frequency</code> is, but I'm assuming it is an array (which are generally\nbest avoided in C++).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T14:37:10.377",
"Id": "29615",
"ParentId": "29611",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T10:47:51.407",
"Id": "29611",
"Score": "2",
"Tags": [
"c++",
"optimization",
"strings"
],
"Title": "Finding the number of occurrences of a string in another string"
}
|
29611
|
<p>Instead of using multiple setter functions within a class like </p>
<pre><code>public function setAction()
public function setMethod()
</code></pre>
<p>etc</p>
<p>I've been using a method from a base class that all other classes have access to.</p>
<pre><code>public function set_properties($properties) {
foreach ($properties as $key => $value) {
$this->$key = $value;
}
}
</code></pre>
<p>So I can just use it like so</p>
<pre><code>$Class->set_properties(array('action' => 'page.php', 'method' => 'get'));
</code></pre>
<p>Is this a bad practice that I'm getting into or is this an okay way of setting properties?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T17:07:10.690",
"Id": "46837",
"Score": "2",
"body": "You should still keep the possibility that a property will need a special setter (that does more than just setting the property). In your loop, you should check whether `$this` has a method called `'set' . ucfirst($key)` (so `setAction` if the key is `action`), you can use `method_exists()` for this, and if it does have it, invoke that instead of setting the property manually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T18:49:02.087",
"Id": "46841",
"Score": "0",
"body": "You could also generate the setters name and call it passing the property. Then you have the best of both worlds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T12:21:54.190",
"Id": "50913",
"Score": "0",
"body": "I would prefer having multiple setters to make things simple and clear."
}
] |
[
{
"body": "<p>Having individual setters has a couple of advantages:</p>\n\n<p>A dedicated setter allows you to put dedicated validations for these properties. You could obviously put them in the bulk setter as well, but that will make the bulk setter large and unwieldy very quickly. You want methods to do one dedicated thing instead. That keeps them maintainable.</p>\n\n<p>Dedicated setters clearly communicate which properties can be set. With a bulk setter, it needs documentation or a look at the source code to learn what I can legally set. I usually don't want to look at your class code. I just want to look at the public API and understand how I can use that class.</p>\n\n<p>That's not to say bulk setters are bad per se. If you know folks are likely to set two or more values after another because they naturally go together, you could allow for a <code>setFooAndBar($foo, $bar)</code> method. But as you can see, that's still much more explicit than a generic <code>set(array $data)</code>. Also one could argue that if you need to set arguments that naturally go together, you rather want them to be in an object of their own and pass that object then.</p>\n\n<p>On a side note: Your bulk setter will create properties on the fly for those keys that are not properties in the class. While you could consider that a feature, it makes debugging harder because a developer has to know the object's current state at runtime to know what properties it has.</p>\n\n<p>On another side note: a base class is usually a code smell. It tends to amass unrelated functionality and turn in a God object quickly. It also hampers reuse because all your classes will depend on it then.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T17:25:46.470",
"Id": "29619",
"ParentId": "29617",
"Score": "2"
}
},
{
"body": "<p>implementing a <code>setProperties</code> method is fine, because that's probably what you're doing in the <code>__construct</code> method anyway:</p>\n\n<pre><code>class Foo\n{\n private $bar = null;\n private $baz = null;\n public function __construct(array $properties)\n {\n foreach($properties as $k => $value)\n {\n $this->{$k} = $value;\n }\n }\n}\n</code></pre>\n\n<p>Which is, of course, absolutely fine. Personally, though, I'd still implement a setter/getter method for each individual property, though, for several reasons:</p>\n\n<ul>\n<li>More readable code. If someone is to use your class, and wants to set a distinct property to a given value, there's no need for him to write <code>setProperties(array('bar' => 'new value'));</code>. He can simply write <code>$instance->setBar('new value');</code> which is easier to understand, and less error prone if you ask me. (upon reviewing my answer, I actually noted I made a typo, and wrote <code>setProperties(array();</code> by mistake, missing the second closing <code>)</code>... case in point :-P)</li>\n<li>A setter means that property was predefined. <a href=\"https://stackoverflow.com/questions/17696289/pre-declare-all-private-local-variables/17696356#17696356\">Read my answer to this SO question</a> to get a better understanding as to why this is important. Bottom line: it's faster to get that property and set it, because the lookup is -in theory- an <em>O(1)</em> operation.</li>\n<li>Accidental typo's make for <em>O(n)</em> lookups, so they're almost always going to be slower. A typo like <code>setProperties(array('bat' => 'new value'));</code> won't throw up errors, but when, later on, you attemt a <code>getProperty('bar');</code> call, and it returns <code>null</code> you may find debugging is a bit of a nightmare, the more complex your code becomes.<br/>\nCompare that to <code>setBat('new Value');</code>, which will throw an error (method undefined)... you will, I think, agree that the latter scenario is a tad easier to debug.</li>\n<li>Types. I know PHP isn't all too strict with its types. A string can be converted to an int at runtime, should the need arrive. Though it <em>can</em> sometimes come in handy if you know what type a property, or var holds. Again, take data-models. If a model, representing a database record has a property <em>id</em>, that id is likely to be an integer. The setter, then, could contain a cast (<code>$this->id = (int) $idParameter;</code>). The example class below illustrates some other tricks you might consider using, like passing the <code>$_POST['password']</code>, which will be converted to a hash on the fly.</li>\n<li>Programming by interface. A number of classes might share one or two methods/properties. It could well be that this is the only bit of data a given method requires to work. Rather than leaving out the type-hints, and chekcing with <code>method_exists()</code> or <code>property_exists()</code>, or even worse: <code>@$instance->property</code>, you could implement an interface with getters and setters for those properties, and use a type-hint for that interface</li>\n<li>Access modifiers per property: This is might seem too obvious, but is important to keep in mind. When objects inherit from one another, they gain access to their parents/eachother's <code>__get</code> and <code>__set</code> methods. By using individual properties, you can use the access modifiers to hide certain properties, even from any child classes that might extend from your current classes, and with it any other classes that follow suit.</li>\n</ul>\n\n<p>On a personal note:<br/>\nsometimes, it's inevitable to use PHP's definition of object overloading (dynamic properties), but on the whole, I try to avoid it as much as possible. Not only because it's slower, but also because often, in case of Data models, the properties are mapped to a DB table. If you introduce a typo there, the DB field names don't match, and you might end up inserting incomplete data, or some other class might churn out faulty queries.<br/>\nThat's why I tend to write my data-models like so:</p>\n\n<pre><code>class User\n{\n const SALT = 'S0m3_5@lt_6035-@-L0n9=vv@y';\n private $id = null;\n private $name = null;\n private $hash = null;\n private $active = false;\n public function __construct(array $properties)\n {\n $this->setProperties($properties);\n }\n /**\n * Bulk insert method, uses setter\n **/\n public function setProperties(array $properties)\n {\n foreach($properties as $name => $value)\n {\n $this->__set($name, $value);\n }\n return $this;\n }\n /**\n * Magic setter, to allow `$instance->bar = 'foo';`\n * To behave like $instance->setBar('foo');\n **/\n public function __set($name, $value)\n {\n $name = 'set'.ucfirst(strtolower($name));\n if (!method_exists($this, $name))\n {//don't overload\n return null;//or throw error\n }\n return $this->{$name}($value);\n }\n /**\n * Magic getter, to allow $instance->bar;\n * To behave like $instance->getBar();\n **/\n public function __get($name)\n {\n $name = 'get'.ucfirst(strtolower($name));\n if (!method_exists($this, $name))\n {\n return null;//or throw error\n }\n return $this->{$name}();\n }\n /**\n * Property-specific setter\n **/\n public function setId($int)\n {\n $this->id = (int) $int;\n return $this;\n }\n /**\n * Property-specific getter\n **/\n public function getId()\n {\n return $this->id;\n }\n public function setHash($pwd, $isHash = false)\n {\n $isHash = !!$isHash;//make sure this is a bool\n if (!$isHash)\n {\n $pwd = sha1(self::SALT.$pwd);\n }\n $this->hash = $pwd;\n return $this;\n }\n public function setPassword($pwd)\n {\n return $this->setHash($pwd);\n }\n public function getHash()\n {\n return $this->hash;\n }\n}\n</code></pre>\n\n<p>As you can see, I've also implemented a <code>setPassword</code> method, even though these isn't a password method. This method serves as an alias for <code>setHash</code>, in case you pass the contents of the entire <code>$_POST</code> array to the constructor (when processing a register or login form, for example). This'll cause the setter to do its job, while at the same time, not creating any issues with overloading the class properties, and it doesn't require you to call <code>setHash($_POST['password']);</code> separatly.</p>\n\n<p>Like I said before: programming by interface:<br/>\nMethods like these aliases are also useful when you're implementing your own interfaces. For example: clients can have an email property, whereas co-workers might have an internal <em>office-link</em> address or something. Create a <code>Contactable</code> interface, and implement a <code>getEmail</code> and <code>setEmail</code> method in the <code>Coworker</code> class, that servers as an alias of the <code>getOfficeLink</code> and <code>setOfficeLink</code> methods respectively.</p>\n\n<pre><code>interface Contactable\n{\n public function getEmail();\n public function setEmail($email);\n}\n//Client class:\nclass Client implements Contactable\n{\n private $email = null;\n public function getEmail()\n {\n return $this->email;\n }\n public function setEmail($email)\n {\n if (!filter_var($email, FILTER_VALIDATE_EMAIL))\n {//sanitize email!\n $email = null;\n }\n $this->email = $email;\n }\n}\n//Coworker class:\nclass Client implements Contactable\n{\n private $officeLink = 1;\n public function setOfficeLink($link)\n {\n $link = (int) $link;\n if ($link > 1000 || $link < 1)\n {\n $link = 1;\n }\n $this->officeLink = 1;\n return $this;\n }\n public function getOfficeLink()\n {\n return $this->link;\n }\n public function getEmail()\n {\n return $this->getOfficeLink();\n }\n public function setEmail($email)\n {\n $this->setOfficeLink((int) $email);\n }\n}\n</code></pre>\n\n<p>As you see here, it would be impossible to move the email getters and setters to an abstract class, because the validation for the values differs too much (clients should provide a valid email, whereas coworkers require a number ranging from 1 to 999). An interface is ideal for the job here, because it ensures the methods exist, but the implementation depends almost entirely on the class which implements that interface. Anyway, you can now use type-hints by interface:</p>\n\n<pre><code>public function notifyPerson(Contactable $entity)\n{\n $daemon = $this->getMailer();\n $deamon->setMessage('Your request has been processed')\n ->from('noreply@eager-helpers.org')\n ->to($entity->getEmail())\n ->send();\n}\n</code></pre>\n\n<p>This, of course, assumes that the deamon has been programmed to recognize both emails and officeLink numbers. In any case, it's clean code, easy to read and doesn't require you to create a new instance of <code>Client</code>, and assign it a officeLink in email drag, just for one method call, which would make for messy code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-15T22:11:33.217",
"Id": "49880",
"Score": "0",
"body": "I found this inspiring for my answer http://programmers.stackexchange.com/questions/209962/avoiding-boilerplate-in-php-classes/211573#211573. I would appreciate some explanation why `return $this->{$name}($value)` is used instead of `$this->$name = $value` for the setter and `$this->{$name}()` instead of `$this->$name` for the getter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-16T06:59:57.877",
"Id": "49899",
"Score": "0",
"body": "@DmitriZaitsev: The reason _why_ I'm using the methods, and not accessing the properties directly is simply because the setters and getters may contain additional logic, validating the value (`setEmail`, for example calls `filter_var($email FILTER_VALIDATE_EMAIL)`). The getters are there to make sure I'm not accessing properties that don't have a public getter, so I can make sure I'm not exposing properties that I don't want to expose. It also allows me to use interfaces (an interface that defines the `getId` and `setId` methods for type-hinting can be useful)..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-16T16:04:39.327",
"Id": "49941",
"Score": "0",
"body": "That makes sense, appreciate it! The only thing makes me worry is returning `null` when you aim for chaining but you comment about throwing error, which is probably the right thing here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-17T06:23:38.883",
"Id": "50020",
"Score": "0",
"body": "@DmitriZaitsev: Only getters will return null if the value doesn't exist, like `$unsetVar` evaluates to null. Chainable getters would be illogical. Throwing an exception in setters is, IMHO, the right thing to do. If some code passes a wrong argument to the setter it should throw, because an invalid call to a setter is a bug, not the getter returning null, that's just the consequence of the invalid setter call. Ah well, bottom line: most of my objects implement some form of bulk/array-setter , but that just calls the setters. PS: would you mind awfully accepting one of the answers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-17T12:31:17.720",
"Id": "50056",
"Score": "0",
"body": "Thanks, that confirms my thoughts. I was confused by your function `__set($name, $value)` returning `null` - a misprint? PS. I wouldn't mind at all to accept your answer, if only I was the question asker, all I could do was to upvote :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-17T12:55:24.913",
"Id": "50060",
"Score": "0",
"body": "@DmitriZaitsev: Nips, should've checked who asked :-P... well, the `return null;` is a bad idea (throwing an excpetion is the right thing to do, of course), but some people are _scared_ of throwing exceptions, for some reason... I therefore return `null` to at least let you know someting's wrong (return `$this` would go by completely unnoticed). Still `throw` is the better option"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-17T13:26:06.673",
"Id": "50066",
"Score": "0",
"body": "Good to see again my thought was right. Concerning people 'scared' of exceptions, they may have read the (controversial) article http://www.joelonsoftware.com/articles/Wrong.html by Joel Spolsky, whose 1st part gives some great advices but the 2nd part - the only bad advice of him that I know. There have been extensive follow-up articles by many people disagreeing with that advice since then."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T11:26:56.937",
"Id": "29643",
"ParentId": "29617",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T17:00:44.300",
"Id": "29617",
"Score": "4",
"Tags": [
"php",
"object-oriented"
],
"Title": "Setting properties inside of a class"
}
|
29617
|
<p>This is the algorithm I am using to flip an image in-place. Though it works perfectly, I would like if any one can spot any potential problems or offer any points on improvement and optimizations.</p>
<pre><code>/**
* pixels_buffer - Pixels buffer to be operated
* width - Image width
* height - Image height
* bytes_per_pixel - Number of image components, ie: 3 for rgb, 4 rgba, etc...
**/
void flipVertically(unsigned char *pixels_buffer, const unsigned int width, const unsigned int height, const int bytes_per_pixel)
{
const unsigned int rows = height / 2; // Iterate only half the buffer to get a full flip
const unsigned int row_stride = width * bytes_per_pixel;
unsigned char* temp_row = (unsigned char*)malloc(row_stride);
int source_offset, target_offset;
for (int rowIndex = 0; rowIndex < rows; rowIndex++)
{
source_offset = rowIndex * row_stride;
target_offset = (height - rowIndex - 1) * row_stride;
memcpy(temp_row, pixels_buffer + source_offset, row_stride);
memcpy(pixels_buffer + source_offset, pixels_buffer + target_offset, row_stride);
memcpy(pixels_buffer + target_offset, temp_row, row_stride);
}
free(temp_row);
temp_row = NULL;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T22:17:57.377",
"Id": "46852",
"Score": "3",
"body": "You shouldn't cast the result from `malloc` in C."
}
] |
[
{
"body": "<p>Just some quick things:</p>\n\n<ul>\n<li><p><code>unsigned int width</code> doesn't need to be <code>const</code> since it's passed-by-value. But that's not really significant as the compiler will optimize away the <code>const</code> if needed.</p></li>\n<li><p>Prefer <a href=\"https://stackoverflow.com/questions/2550774/what-is-size-t-in-c\"><code>size_t</code></a> for types representing sizes. It's also useful for loop counters as you'll be able to loop through any size of data supported by your computer. However, you'll receive type-matching warnings if your counter and size types are not <em>both</em> signed or unsigned. In this case, using <code>int</code> (which is a <em>signed</em> type) will cause such warnings if the size type is <em>unsigned</em>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T19:21:04.050",
"Id": "29624",
"ParentId": "29618",
"Score": "3"
}
},
{
"body": "<pre><code>source_offset = rowIndex * row_stride;\ntarget_offset = (height - rowIndex - 1) * row_stride;\n\nmemcpy(temp_row, pixels_buffer + source_offset, row_stride);\nmemcpy(pixels_buffer + source_offset, pixels_buffer + target_offset, row_stride);\nmemcpy(pixels_buffer + target_offset, temp_row, row_stride);\n</code></pre>\n\n<p>could be written:</p>\n\n<ol>\n<li>with <code>const</code> variables</li>\n<li>without any duplicated evaluation of <code>pixels_buffer + [source/target]_offset</code></li>\n</ol>\n\n<p>doing something like:</p>\n\n<pre><code>unsigned char* source = pixels_buffer + rowIndex * row_stride;\nunsigned char* target = pixels_buffer + (height - rowIndex - 1) * row_stride;\nmemcpy(temp_row, source, row_stride);\nmemcpy(source, target, row_stride);\nmemcpy(target, temp_row, row_stride);\n</code></pre>\n\n<p>Also, a different way to do would be to initialize</p>\n\n<pre><code>source = pixels_buffer\n</code></pre>\n\n<p>and</p>\n\n<pre><code>target = pixels_buffer + (height - 1) * row_stride\n</code></pre>\n\n<p>and to increment/decrement them by <code>row_stride</code> at each iteration.</p>\n\n<p><strong>Edit:</strong> if you go for this option, you might be able to use this for the stopping condition of your loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T21:17:38.913",
"Id": "29626",
"ParentId": "29618",
"Score": "5"
}
},
{
"body": "<p>A few comments:</p>\n\n<ul>\n<li><p>you use signed/unsigned types inconsistently. Your <code>width</code> and <code>height</code> are\nunsigned, while all other integers are signed. If you are using unsigned\ntypes because the values can never be negative, then the same applies to all\nintegers in the function and, by that reasoning, they should all be unsigned\n(<code>size_t</code> is a common type used for sizes). There are arithmetic errors that\ncan occur with mixed signed and unsigned arithmetic, so you should turn on\nconversion warnings (eg <code>-Wconversion</code> for <code>gcc</code>).</p></li>\n<li><p>your naming is inconsistent. The function and the variable <code>rowIndex</code> use\n\"camel-case\", while the other variables don't.</p></li>\n<li><p>the return from <code>malloc</code> should not be cast in C (C++ requires casting).</p></li>\n<li><p><code>source_offset</code> and <code>target_offset</code> should be defined at the point of first\nuse (ie. within the loop). There is no performance penalty for defining a\nvariable within a loop in C.</p></li>\n<li><p>there is no check for success from <code>malloc</code></p></li>\n</ul>\n\n<p>Here is a slightly simplified version of the function</p>\n\n<pre><code>void flip_vertically(unsigned char *pixels, const size_t width, const size_t height, const size_t bytes_per_pixel)\n{\n const size_t stride = width * bytes_per_pixel;\n unsigned char *row = malloc(stride);\n unsigned char *low = pixels;\n unsigned char *high = &pixels[(height - 1) * stride];\n\n for (; low < high; low += stride, high -= stride) {\n memcpy(row, low, stride);\n memcpy(low, high, stride);\n memcpy(high, row, stride);\n }\n free(row);\n}\n</code></pre>\n\n<p>You can see that I have changed some types, shortened variable names (it is a\nshort function so short names are appropriate) and simplified the way buffer\noffsets are calculated to just addition/subtraction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T01:03:18.597",
"Id": "29632",
"ParentId": "29618",
"Score": "9"
}
},
{
"body": "<p>Just a quick addition to something these already great answers stated but somewhat glossed over. Originally this question had the C++ tag in it. I'm assuming because of this line:</p>\n\n<pre><code>unsigned char* temp_row = (unsigned char*) malloc(row_stride);\n</code></pre>\n\n<p>that you are compiling this C code as C++ code. <strong>Don't do that.</strong> While the languages seem very similar and the compiler you are using will probably allow it, it is a bad habit to form. One of the main reasons not to do this is that you won't get certain warnings that you would normally get by compiling this as C code, meaning right now there could be certain vulnerabilities and bugs in your application.</p>\n\n<p>I speak from personal experience.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T03:19:45.583",
"Id": "29633",
"ParentId": "29618",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29626",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T17:20:04.687",
"Id": "29618",
"Score": "7",
"Tags": [
"optimization",
"c",
"image"
],
"Title": "Image Flip algorithm in C"
}
|
29618
|
<p>I would like a review and recommendations for improvement of the code below. I want to allow an exception to be handled by the caller, so I am rethrowing it. But I have resources to close. So I have the resource closing code duplicated in both the try and the catch blocks. Is there a better way to do this?</p>
<pre><code>const string HTTPopotamus::GET(void) {
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
try {
hSession = this->open();
hConnect = this->connect(hSession);
hRequest = this->openRequest(hConnect);
this->sendRequest(hRequest);
this->receiveResponse(hRequest);
string strData = this->readData(hRequest);
/* Close any open resources. */
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
return strData;
} catch (const ExceptionCyclOps& e) {
/* Close any open resources. */
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
throw;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It seems that your code would benefit dramatically from use of <a href=\"http://en.wikipedia.org/wiki/RAII\" rel=\"nofollow\">RAII</a>. To illustrate, let's assume the existence of an <code>HTTPConnection</code> class that opens an appropriate connection in its constructor and closes it at destruction. The code would look more like the following:</p>\n\n<pre><code>const string HTTPopotamus::GET(void) {\n HTTPConnection conn(/*connection parameters here*/);\n\n conn.sendRequest(/*request parameters here*/);\n conn.waitForResponse(HTTP_REQUEST_TIMEOUT);\n\n return this->readData(hRequest);\n}\n</code></pre>\n\n<p>This approach is more elegant and clear and explains itself with no need for comments. Any exception thrown, such as exceptions that represent a failed connection or a timeout event would be propagated to the caller while the <code>HTTPConnection</code> object would still be destroyed properly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T22:44:55.153",
"Id": "29627",
"ParentId": "29621",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T18:17:22.717",
"Id": "29621",
"Score": "0",
"Tags": [
"c++",
"exception-handling"
],
"Title": "Dealing with resource closure when rethrowing an exception"
}
|
29621
|
<p>The interface and some of the implementation is take from Boost. However, it is intended to be transferable between projects by only copying one file. I have removed most of the policy classes in favor of more condensed code that requires less files to move around. Please tell me where my strengths are as well as where the code might fall apart.</p>
<p><strong>unique_ptr.h</strong> -- Interface and Some Implementation</p>
<pre><code>#ifndef UNIQUE_PTR_HPP_INCLUDED
#define UNIQUE_PTR_HPP_INCLUDED
namespace glext
{
template<class T>
struct deleter
{
static void release(T *p)
{
if (p) {
delete p;
p = 0;
}
}
};
template<class T>
struct array_deleter
{
static void release(T *p)
{
if (p) {
delete [] p;
p = 0;
}
}
};
template <class T, class D = glext::deleter<T> >
class unique_ptr
{
private:
T *_ptr;
template <class U, class D> unique_ptr(unique_ptr<U, D> &);
template <class U, class D> unique_ptr &operator=(unique_ptr<U, D> &);
public:
typedef T element_type;
typedef D deleter_type;
unique_ptr();
explicit unique_ptr(T *p);
~unique_ptr();
unique_ptr &operator=(unique_ptr u);
template <class U>
unique_ptr &operator=(unique_ptr<U, D> u);
T operator*() const;
T *operator->() const;
T *get() const;
T *release();
void reset(T *p = 0);
void swap(unique_ptr &u);
};
}
#include "unique_ptr.inl"
</code></pre>
<p><strong>unique_ptr.inl</strong> -- Implementation</p>
<pre><code>namespace glext
{
template <class T, class D>
unique_ptr<T, D>::unique_ptr() :
_ptr(0)
{}
template <class T, class D>
unique_ptr<T, D>::unique_ptr(T *p) :
_ptr(p)
{}
template <class T, class D>
unique_ptr<T, D>::~unique_ptr()
{
reset();
}
template <class T, class D>
unique_ptr<T, D> &unique_ptr<T, D>::operator=(unique_ptr<T, D> u)
{
reset(u.release());
return *this;
}
template <class T, class D>
template <class U>
unique_ptr<T, D> &unique_ptr<T, D>::operator=(unique_ptr<U, D> u)
{
reset(u.release());
return *this;
}
template <class T, class D>
T unique_ptr<T, D>::operator*() const
{
return *_ptr;
}
template <class T, class D>
T *unique_ptr<T, D>::operator->() const
{
return _ptr;
}
template <class T, class D>
T *unique_ptr<T, D>::get() const
{
return *_ptr;
}
template <class T, class D>
T *unique_ptr<T, D>::release()
{
T *tmp = _ptr;
_ptr = 0;
return tmp;
}
template <class T, class D>
void unique_ptr<T, D>::reset(T *p = 0)
{
if (_ptr != p) {
if (_ptr) {
unique_ptr<T, D>::deleter_type::release(_ptr);
_ptr = p;
}
}
}
template <class T, class D>
void swap(unique_ptr<T, D> &u)
{
std::swap(_ptr., u._ptr);
}
template <class T, class D>
inline void swap(unique_ptr<T, D> &x, unique_ptr<T, D> &y)
{
x.swap(y);
}
template <class T1, class D1, class T2, class D2>
bool operator==(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)
{
return x.get() == y.get();
}
template <class T1, class D1, class T2, class D2>
bool operator!=(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)
{
return x.get() != y.get();
}
template <class T1, class D1, class T2, class D2>
bool operator<(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)
{
return x.get() < y.get();
}
template <class T1, class D1, class T2, class D2>
bool operator<=(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)
{
return x.get() <= y.get();
}
template <class T1, class D1, class T2, class D2>
bool operator>(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)
{
return x.get() > y.get();
}
template <class T1, class D1, class T2, class D2>
bool operator>=(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)
{
return x.get() >= y.get();
}
}
</code></pre>
<p><strong>Sample usage</strong></p>
<pre><code>int main(int /*argc*/, char * /*argv*/[]) {
alloc_console();
glext::unique_ptr<int> uptr(new int(20));
glext::unique_ptr<int, glext::array_deleter<int> > uaptr(new int[20]);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T16:00:11.490",
"Id": "46902",
"Score": "3",
"body": "This is good for an excercise. But please do **NOT** do this for production code. There are just too many gotchs involved in writing a correct smart pointer. Check out Scott Myers; he has talked at length about his own personal attempt that was still not working in all situations after many years of code reviews and feedback from lots of very experienced people. Use the standard ones provided by the standard. They are highly tested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:45:18.047",
"Id": "46909",
"Score": "1",
"body": "@Loki Astari Point well taken, but C++ 99 only provides auto_ptr and most companies I have worked for still are not using C++-11. With that being said, I know that boost provides one which should handle most uses, but what if you want a less complex one to port from project to project without the overhead of coppying every necessary header boost requires to get the code to build? This is what I am interested in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T18:02:48.947",
"Id": "46912",
"Score": "1",
"body": "The use std::auto_ptr. Its not exactly that bad. And its better than what you have proposed (see my comments below). The only reason people don't like std::auto_ptr is the hidden move semantics on assignment (that apparently is not intuitive) which are fixed by `std::move` with the new std::unique_ptr. Why not install boost when you install the compiler. Its not as if that is uncommon. Why would you want to copy the header files around. You don't even need to build boost (the smart pointers are part of the header only libraries)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T20:48:50.567",
"Id": "46921",
"Score": "0",
"body": "Your comment on using auto_ptr is fine and all except gcc states \"The resulting rule is simple: Never ever use a container of auto_ptr objects. The standard says that “undefined” behavior is the result, but it is guaranteed to be messy.\" Which comes from http://gcc.gnu.org/onlinedocs/libstdc++/manual/auto_ptr.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T23:12:21.983",
"Id": "46932",
"Score": "0",
"body": "@Loki Astari Your comment on using auto_ptr is fine and all except gcc states \"The resulting rule is simple: Never ever use a container of auto_ptr objects. The standard says that “undefined” behavior is the result, but it is guaranteed to be messy.\" Which comes from http://gcc.gnu.org/onlinedocs/libstdc++/manual/auto_ptr.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T00:34:24.287",
"Id": "46936",
"Score": "0",
"body": "Sorry also forgot std::auto_ptr is not supported in the standard containers. But in reality you don't want containers of smart pointers. You want smart containers that understand they have ownership of the pointers. see `boost::ptr_vector<T>` etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T01:33:57.490",
"Id": "47494",
"Score": "1",
"body": "Just for what it's worth: there's a C++98 and a C++03, but no C++99."
}
] |
[
{
"body": "<p>Firstly, let's fix up some errors that exist in the code. </p>\n\n<ol>\n<li>You're missing an <code>#endif</code> at the end of your <code>unique_ptr.h</code> file. </li>\n<li>Both <code>template <class U, class D> unique_ptr(unique_ptr<U, D> &);</code> and <code>template <class U, class D> unique_ptr &operator=(unique_ptr<U, D> &);</code> don't require template redefinitions. They should both just be <code>unique_ptr(unique_ptr &);</code> and <code>unique_ptr& operator=(unique_ptr&);</code>.</li>\n<li>You need an <code>#include <algorithm></code> to use <code>std::swap</code>. You probably also want to change it to <code>using std::swap</code> within your <code>swap</code> function. It should be <code>unique_ptr<T, D>::swap</code>, not <code>swap</code>. You've also got an extra <code>.</code> after <code>_ptr</code> in this function.</li>\n<li>In your <code>reset</code> function in the <code>.inl</code> file, it's an error to redeclare the default parameter; that is, it should be <code>template <class T, class D> void unique_ptr<T, D>::reset(T *p)</code> (without the <code>= 0</code>).</li>\n</ol>\n\n<p>Some general comments:</p>\n\n<pre><code>if (p) {\n delete p;\n p = 0;\n}\n</code></pre>\n\n<p>The <code>if</code> is unnecessary. <code>delete</code> (and <code>delete[]</code>) already do a <code>NULL</code> check, and are a no-op if their argument is <code>NULL</code>.</p>\n\n<p>Variables starting with <code>_</code> are reserved for compiler usage. Switch to appending at the end of the variable name (<code>ptr_</code>) instead.</p>\n\n<p>Your <code>T operator*() const;</code> should be returning by <code>T&</code> instead.</p>\n\n<p>Your <code>get</code> function is trying to return a dereferenced pointer:</p>\n\n<pre><code>template <class T, class D>\nT *unique_ptr<T, D>::get() const\n{\n return *_ptr; // Should be return _ptr;\n}\n</code></pre>\n\n<p>There are likely other things I've missed. Also, it's worth pointing out that your use cases will be severely constrained without move semantics and move aware containers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T05:14:15.887",
"Id": "46857",
"Score": "0",
"body": "What I really want to know is how is the lack of move semantics going to affect me?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T05:50:48.367",
"Id": "46859",
"Score": "1",
"body": "For a really simple example, try creating a `std::vector<glext::unique_ptr<T>>` and see what happens."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T06:07:55.127",
"Id": "46860",
"Score": "0",
"body": "Aye I see that. That was an error forgot the copy constructor for unique_ptr<T, D>. unique_ptr<U, D> is not allowed according to boost, but one for unique_ptr<T, D> is with the usage of complex move semantics. I put in the copy constructor and used it with std::vector. All news were matched with delete on the same addresses. _CrtDumpMemoryLeaks() shows memory leaks in MSVC, but stepping through the code reveals to me there is none see above. What else am I missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T06:27:41.350",
"Id": "46862",
"Score": "0",
"body": "Your code, even with the fixes I talked about above, still doesn't compile for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T06:42:28.397",
"Id": "46863",
"Score": "0",
"body": "Hmm perhaps a bad copy and paste here. Code can be obtained at https://github.com/mehoggan/GLExtensions/tree/master/smart_ptrs/unique_ptr and the header with contains all the std headers I need is found at https://github.com/mehoggan/GLExtensions/blob/master under glext.h."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T04:52:50.697",
"Id": "29635",
"ParentId": "29629",
"Score": "7"
}
},
{
"body": "<p>Lets start here:</p>\n\n<pre><code>static void release(T *p) \n{\n if (p) { // No need to check for NULL\n // delete has no action when applied to a NULL pointer\n delete p;\n\n p = 0; // This is very dangerous.\n // It has no actual affect (as it is local)\n // but provides an illusionary sense of security.\n }\n}\n</code></pre>\n\n<p>Here you are forcing an unnecessary copy:</p>\n\n<pre><code>template <class T, class D>\nunique_ptr<T, D> &unique_ptr<T, D>::operator=(unique_ptr<T, D> u)\n // ^^^^^^^^^^^^^^^^^^\n // Pass by value forcing a copy\n // Why are you doing that.\n // If you have a reason it should be\n // documented.\n{\n reset(u.release());\n return *this;\n}\n</code></pre>\n\n<p>Destructors should be written so they do not throw exceptions:</p>\n\n<pre><code>template <class T, class D>\nunique_ptr<T, D>::~unique_ptr()\n{ \n reset(); // This calls delete which calls the destructor of T\n // Since you have no control over the type T you should take\n // precautions over what happens next.\n}\n</code></pre>\n\n<p>This can generate undefined behavior</p>\n\n<pre><code>template <class T, class D>\nT unique_ptr<T, D>::operator*() const\n{\n return *_ptr; // _ptr is NULL then this is UB\n // Is this really what you want. If so then it should\n // be explicitly documented.\n}\n</code></pre>\n\n<p>This is broken and does not work as expected if _ptr is NULL</p>\n\n<pre><code> template <class T, class D>\n void unique_ptr<T, D>::reset(T *p = 0)\n {\n if (_ptr != p) {\n if (_ptr) {\n unique_ptr<T, D>::deleter_type::release(_ptr);\n\n _ptr = p; // You are only assigning to _ptr if it is NOT NULL\n // Thus if _ptr is NULL you are leaking the `p`\n\n // Also most smart pointers gurantee that once you have\n // passed a pointer you take ownership and delete it.\n // If the above call to release() throws an exception you\n // are again leaking `p`. You must put in extra code to \n // make sure `p` is either deleted or assigned to `_ptr`\n // not matter what happens (even an exception).\n }\n }\n }\n</code></pre>\n\n<p>This should <strong>NEVER</strong> happen</p>\n\n<pre><code>bool operator==(const unique_ptr<T1, D1> &x, const unique_ptr<T2, D2> &y)\n{\n return x.get() == y.get();\n}\n</code></pre>\n\n<p>If two unique ptrs point at the same object then you are well and truly going to get screwed. The whole point of <code>unique ptr</code> is that they are <strong>unique</strong>.</p>\n\n<p>Comparing ptr via <code>operator <</code> is a fool's errand. Unless both pointers are in the same block of memory (ie they were allocated via the same new) they are not comparable the results are otherwise undefined.</p>\n\n<p>When doing comparisons via <code>unique ptr</code> you should be using the underlying object (<strong>NOT</strong> the pointers).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:58:01.790",
"Id": "29658",
"ParentId": "29629",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "29658",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-11T23:42:15.603",
"Id": "29629",
"Score": "5",
"Tags": [
"c++",
"pointers"
],
"Title": "Unique pointer implementation"
}
|
29629
|
<p>I am learning to use Java Swing and have made a simple animation that makes a small shape bounce around the predetermined borders of a panel. The program works well, but I am looking for feedback in terms of quality and any improvements or alternative methods that could be used in such an application.</p>
<pre><code>import javax.swing.*;
import java.awt.*;
final public class Tester {
JFrame frame;
DrawPanel drawPanel;
private int oneX = 7;
private int oneY = 7;
boolean up = false;
boolean down = true;
boolean left = false;
boolean right = true;
public static void main(String[] args) {
new Tester().go();
}
private void go() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(300, 300);
frame.setLocation(375, 55);
moveIt();
}
class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.RED);
g.fillRect(3, 3, this.getWidth()-6, this.getHeight()-6);
g.setColor(Color.WHITE);
g.fillRect(6, 6, this.getWidth()-12, this.getHeight()-12);
g.setColor(Color.BLACK);
g.fillRect(oneX, oneY, 6, 6);
}
}
private void moveIt() {
while(true){
if(oneX >= 283){
right = false;
left = true;
}
if(oneX <= 7){
right = true;
left = false;
}
if(oneY >= 259){
up = true;
down = false;
}
if(oneY <= 7){
up = false;
down = true;
}
if(up){
oneY--;
}
if(down){
oneY++;
}
if(left){
oneX--;
}
if(right){
oneX++;
}
try{
Thread.sleep(10);
} catch (Exception exc){}
frame.repaint();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-09T04:19:04.480",
"Id": "119463",
"Score": "0",
"body": "import.java.awt.BorderLayout should be more efficient"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-21T10:13:42.353",
"Id": "230106",
"Score": "0",
"body": "try using a switch instead of if/else sta"
}
] |
[
{
"body": "<h2>Things I would fix:</h2>\n\n<p>Don't do this:</p>\n\n<pre><code>import javax.swing.*;\nimport java.awt.*;\n</code></pre>\n\n<p>It could be problematic for the compiler to import a bunch of packages at once. If two packages provide the same type, both are imported, and the type is used in the class, a compile-time error occurs. This is described in <a href=\"http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#32799\" rel=\"nofollow noreferrer\">JLS 6.5.5.1</a>:</p>\n\n<blockquote>\n <p>Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.</p>\n</blockquote>\n\n<p>In addition, it also saves a bit of memory. And your IDE (if you use one), should have the ability to do this automatically.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it\">The serializable class <code>DrawPanel</code> does not declare a <code>static final serialVersionUID</code> field of type <code>long</code></a> (thanks to @GilbertLeBlanc for the link):</p>\n\n<pre><code>private static final long serialVersionUID = 1L;\n</code></pre>\n\n<hr>\n\n<p>Don't <strong>ever</strong> do this:</p>\n\n<pre><code>catch (Exception exc)\n{\n}\n</code></pre>\n\n<p>Say that you do get an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html\" rel=\"nofollow noreferrer\"><code>Exception</code></a> thrown at you. You aren't handling it right now in any way. At least print a stack trace to help you solve problems you may encounter in the future:</p>\n\n<pre><code>catch (Exception exc)\n{\n exc.printStackTrace();\n}\n</code></pre>\n\n<p>It was also mentioned in the comments to catch specific <code>Exceptions</code>. Here there is no real need to do that since only an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html\" rel=\"nofollow noreferrer\"><code>InterruptedException</code></a> is being thrown. When you do need to catch multiple <code>Exceptions</code>, <a href=\"https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception\">some people might tell you to do this</a>:</p>\n\n<pre><code>catch (IOException io)\n{\n io.printStackTrace()\n}\ncatch (InterruptedException ie)\n{\n ie.printStackTrace();\n}\n</code></pre>\n\n<p>But you could also do this:</p>\n\n<pre><code>catch (IOException | InterruptedException e)\n{\n e.printStackTrace();\n}\n</code></pre>\n\n<hr>\n\n<p>Right now there are some hard-coded values:</p>\n\n<pre><code>if(oneX >= 283)\nif(oneX <= 7)\n...\n</code></pre>\n\n<p>I would store those values in variables, and then I would make it so that it is more scalable. For example:</p>\n\n<pre><code>int xScale = 280;\nint yScale = xScale / 40;\n</code></pre>\n\n<p>That way, you only have to change one value in order to scale your different values. This is just an example, <em>and has not been implemented in my code</em>. I left this for you to do on your own.</p>\n\n<h2>Recommendations that are optional:</h2>\n\n<p>You have a lot of <code>if</code> statements with braces:</p>\n\n<pre><code>if(down)\n{\n oneY++;\n}\n</code></pre>\n\n<p>If you don't expand on them (which I don't see a need to), you can save some LOC:</p>\n\n<pre><code>if (down) oneY++;\n</code></pre>\n\n<hr>\n\n<p>Right now you are setting the location:</p>\n\n<pre><code>frame.setLocation(375, 55);\n</code></pre>\n\n<p>You don't have to do this, but I prefer the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setLocationByPlatform%28boolean%29\" rel=\"nofollow noreferrer\">OS to set the location</a>:</p>\n\n<pre><code>frame.setLocationByPlatform(true);\n</code></pre>\n\n<p>You could also set the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setLocationRelativeTo%28java.awt.Component%29\" rel=\"nofollow noreferrer\">frame to the center of the window</a>:</p>\n\n<pre><code>frame.setLocationRelativeTo(null);\n</code></pre>\n\n<p>But I never liked that too much. It makes your program seem like a pop-up, which I despise.</p>\n\n<hr>\n\n<p>I always do <code>frame.setVisible(true)</code> after I am completely finished setting up the frame.</p>\n\n<hr>\n\n<p>Right now your are doing this with your braces:</p>\n\n<pre><code>void someMethod(int someInt){\n // ...\n}\n</code></pre>\n\n<p>Since you are a beginner, I would recommend lining up your braces (I still do this, and I've been programming for a while):</p>\n\n<pre><code>void someMethod(int someInt)\n{\n // ...\n}\n</code></pre>\n\n<p>This is a matter of taste, and it is perfectly fine to stay with what you are doing right now.</p>\n\n<hr>\n\n<p>You might note that this:</p>\n\n<pre><code>public static void main(String... args)\n</code></pre>\n\n<p>Is a bit different than your usual:</p>\n\n<pre><code>public static void main(String[] args)\n</code></pre>\n\n<p>They both do the same thing, but one uses <a href=\"https://stackoverflow.com/questions/2925153/can-i-pass-an-array-as-arguments-to-a-method-with-variable-arguments-in-java/2926653#2926653\">variable arity parameters</a>.</p>\n\n<h2>Final code:</h2>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\nfinal public class Test\n{\n\n JFrame frame;\n DrawPanel drawPanel;\n\n private int oneX = 7;\n private int oneY = 7;\n\n boolean up = false;\n boolean down = true;\n boolean left = false;\n boolean right = true;\n\n public static void main(String... args)\n {\n new Test().go();\n }\n\n private void go()\n {\n frame = new JFrame(\"Test\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n drawPanel = new DrawPanel();\n\n frame.getContentPane().add(BorderLayout.CENTER, drawPanel);\n\n frame.setResizable(false);\n frame.setSize(300, 300);\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n moveIt();\n }\n\n class DrawPanel extends JPanel\n {\n private static final long serialVersionUID = 1L;\n\n public void paintComponent(Graphics g)\n {\n g.setColor(Color.BLUE);\n g.fillRect(0, 0, this.getWidth(), this.getHeight());\n g.setColor(Color.RED);\n g.fillRect(3, 3, this.getWidth() - 6, this.getHeight() - 6);\n g.setColor(Color.WHITE);\n g.fillRect(6, 6, this.getWidth() - 12, this.getHeight() - 12);\n g.setColor(Color.BLACK);\n g.fillRect(oneX, oneY, 6, 6);\n }\n }\n\n private void moveIt()\n {\n while (true)\n {\n if (oneX >= 283)\n {\n right = false;\n left = true;\n }\n if (oneX <= 7)\n {\n right = true;\n left = false;\n }\n if (oneY >= 259)\n {\n up = true;\n down = false;\n }\n if (oneY <= 7)\n {\n up = false;\n down = true;\n }\n if (up) oneY--;\n if (down) oneY++;\n if (left) oneX--;\n if (right) oneX++;\n try\n {\n Thread.sleep(10);\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n frame.repaint();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T09:39:57.010",
"Id": "46871",
"Score": "0",
"body": "Very helpful insights! Thank you for putting that much into the answer. I didn't even know about setting location based on OS and I'm going to try that to see how I like it. It seems more reasonable in a lot of ways what with people having different screen resolutions. My only question is what does: private static final long serialVersionUID = 1L; really do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T10:51:54.317",
"Id": "46876",
"Score": "0",
"body": "I just tried setting the location based on OS and I like that a LOT better! Thank you so much for showing me that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T12:21:02.380",
"Id": "46881",
"Score": "2",
"body": "@Jeremy Johnson: serialVersionUID; http://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T16:21:51.790",
"Id": "46904",
"Score": "0",
"body": "@GilbertLeBlanc appologies if I'm missing the point here, but doesn't that mean that the serialVersionUID is not indicated in a class that doesn't implement Serializable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T16:29:51.220",
"Id": "46905",
"Score": "0",
"body": "@Jeremy Johnson: A serialVersionID is not necessary unless the class, or a class you're extending, implements Serializable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:19:05.410",
"Id": "46908",
"Score": "0",
"body": "That's good info to keep in the hip pocket. Thanks for clarification with this. I really appreciate all the help that I can get."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:55:31.807",
"Id": "46911",
"Score": "0",
"body": "@JeremyJohnson I've updated my answer a bit further since you are a beginner. I've now split my answer into two sections, one of things I would definitely fix, one into recommendations that are optional. I've also added some additional notes. All the notes have been implemented into my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T18:07:39.870",
"Id": "46913",
"Score": "0",
"body": "@syb0rg He's placing the braces according to \"Java\" (Oracle) standard, nothing wrong with that. This is a matter of taste and IMHO has nothing to do with being a beginner. You should mention that, again IMHO. It's no big deal, but would be good to mention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T18:09:31.613",
"Id": "46914",
"Score": "0",
"body": "@Marc-Andre That's why it is in the section \"Recommendations that are optional\". It is up for him to decide, but in my mind, it makes coding easier. You are right that there is nothing wrong with it. I did make an edit to the question to state that it is a matter of taste."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T23:08:10.650",
"Id": "46931",
"Score": "0",
"body": "I appreciate any and all insights. I don't believe there is a such thing as useless information. Some might be more useful or more correct than others or may suit needs better in different circumstances, but it's always good to keep an extra way in the back of your mind just in case. Who knows, one of my professors this year might say that it HAS to be done this way or that. It's good to be flexible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:35:33.480",
"Id": "47007",
"Score": "0",
"body": "Correct me if I'm wrong here, but after reading through some more Java docs, I'm about 101% certain that there is no need to include a serialVersionUID in this answer (unless the class were to change to one that implements Serializable) since the number is just a reference for deserialization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:38:49.973",
"Id": "47008",
"Score": "0",
"body": "It only matters if you plan on storing and retrieving objects using serialization directly. It's always a good idea to include it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-26T22:50:05.757",
"Id": "410551",
"Score": "0",
"body": "Usually `InterruptedException` requires special handling, you should not place it in a multi-catch. https://www.ibm.com/developerworks/library/j-jtp05236/"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T04:25:38.777",
"Id": "29634",
"ParentId": "29630",
"Score": "25"
}
},
{
"body": "<p>Your code has a lot of magic numbers in it.</p>\n\n<pre><code>if(oneX >= 283){\n right = false;\n left = true;\n}\n</code></pre>\n\n<p>What is special about 283? What does it actually mean? If you define a constant that happens to have the value of 283, it will be much easier to update your code if the value needs to change.</p>\n\n<hr>\n\n<pre><code>try{\n Thread.sleep(10);\n} catch (Exception exc){}\n</code></pre>\n\n<p>Catching <code>Exception</code> is bad. You always want to catch the most specific exception you can to do what you need. In this case, <code>InterruptedException</code> would be the correct exception to catch. This is not a great example because there is only one exception that can be thrown. However, in the future, it will prevent you for accidentally handling and unexpected exception the wrong way.</p>\n\n<p>Additionally, you are not doing anything with the exception. In general, this is a bad practice. Exceptions are thrown for a reason and should not be ignored without some thought. If you know you don't care what the exception is cause by, add a comment to explain your reasoning to anyone who might see the code later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T09:35:01.910",
"Id": "46870",
"Score": "1",
"body": "I used 283 because the window is not resizable and the borders seem to make the shape meet the edge best with that number, I started with different numbers and kept changing them until it seemed to line up more accurately. I like the idea of defining something like: private int rightBorder = 283, though. Did not know that about exceptions, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T06:17:00.930",
"Id": "29638",
"ParentId": "29630",
"Score": "6"
}
},
{
"body": "<p>You get a good review from @syb0rg. I'm going to tell you something that will help you in the long run. If you create any application in Swing in future try to use <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater%28java.lang.Runnable%29\" rel=\"nofollow noreferrer\">SwingUtilities.invokeLater()</a> to prevent any <em>unnatural behavior</em>. So the code will be like this</p>\n\n<pre><code>public static void main(String[] args) \n{\n SwingUtilities.invokeLater(new Runnable() \n {\n public void run() \n {\n new Tester().go();\n }\n });\n}\n</code></pre>\n\n<p>Now you will ask \"Why should I use this?\". Here is a good answer from <a href=\"https://stackoverflow.com/questions/3551542/swingutilities-invokelater-why-is-it-neded\">StackOverflow</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T04:15:30.520",
"Id": "48458",
"Score": "2",
"body": "I learn something new today, +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T12:40:39.580",
"Id": "48523",
"Score": "0",
"body": "I imagine this is particularly useful in larger GUIs, yes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T12:54:30.510",
"Id": "48524",
"Score": "0",
"body": "@JeremyJohnson larger as well as for smaller cause you can't rely on your Swing app as all components are not thread safe. So why *take chance*? Take advantage of the API or you can implement you own thread safety from scratch, but I wouldn't go there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T13:03:37.513",
"Id": "48526",
"Score": "0",
"body": "@tintinmj I do usually use these animation GUIs in their own separate thread now when I'm working on a test that involves other operations, too. Especially if one of the other operations is sound."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T21:28:13.903",
"Id": "30457",
"ParentId": "29630",
"Score": "5"
}
},
{
"body": "<p>Instead of having all the direction <code>boolean</code>s, <code>up</code>, <code>left</code>, <code>right</code> and <code>down</code>, you can use <code>velocityX</code> and <code>velocityY</code> (which I will call <code>xV</code> and <code>yV</code> from now on). This will reduce the number of lines by quite a bit, because other than requiring only 2 variables rather than 4, you only have to check vertical and horizontal collision, and invert the velocity on impact. </p>\n\n<p>In the beginning, set <code>xV</code> and <code>yV</code> to 1 and place the ball somewhere on the field:</p>\n\n<pre><code>if (x < 0 || x >= width) xV *= -1;\n</code></pre>\n\n<p>Same goes for the y values of course. Then, in the update method:</p>\n\n<pre><code>x += xV; y += yV;\n</code></pre>\n\n<p>When the ball hits the right wall, the horizontal speed will change to -1, which means x will decrease each time.</p>\n\n<p>You can also change the starting values to 2 or 3 to make the ball go faster. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-29T22:03:06.380",
"Id": "180580",
"Score": "0",
"body": "Also, Java's window's width is 6px smaller than its screen and the height 29px, so you were right about the 283 (if the height is indeed 256px)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-29T21:59:14.693",
"Id": "98529",
"ParentId": "29630",
"Score": "4"
}
},
{
"body": "<p>You should not sleep on the event dispatch thread (EDT) as this blocks Swing from processing events, including painting events.</p>\n\n<p>You should use a javax.swing.Timer instead of a while loop:</p>\n\n<pre><code>Timer timer = new Timer(10, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n // update variables\n // do not sleep\n // only need to repaint the panel, not entire frame\n drawPanel.repaint();\n }\n });\ntimer.start();\n</code></pre>\n\n<p>Other notes:</p>\n\n<ul>\n<li>if do not use EXIT_ON_CLOSE, you should add a WindowListener to stop the timer when window closes</li>\n<li>you could only repaint the bounding box of the old and new location with repaint(x, y, width, height) for performance</li>\n<li>See also <a href=\"https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-11T09:14:57.020",
"Id": "160405",
"ParentId": "29630",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29634",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T00:27:02.480",
"Id": "29630",
"Score": "25",
"Tags": [
"java",
"swing",
"animation"
],
"Title": "Simple Java animation with Swing"
}
|
29630
|
<p>This is a quick question. I am reading a mass amount of JSON from a variety of text files. The JSONs are tweets, in this format:</p>
<pre><code>{"filter_level":"medium","retweeted_status":{"contributors":null,"text":"Daily Mail: Vincent Kompany says Manchester United are favourites http://t.co/NB2p1cqlRs #mufc","geo":null,"retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","entities":{"symbols":[],"urls":[{"expanded_url":"http://dailym.ai/15y9p6X","indices":[66,88],"display_url":"dailym.ai/15y9p6X","url":"http://t.co/NB2p1cqlRs"}],"hashtags":[{"text":"mufc","indices":[89,94]}],"user_mentions":[]},"in_reply_to_status_id_str":null,"id":364326884395323393,"source":"<a href=\"http://twitterfeed.com\" rel=\"nofollow\">twitterfeed<\/a>","in_reply_to_user_id_str":null,"favorited":false,"in_reply_to_status_id":null,"retweet_count":9,"created_at":"Mon Aug 15 10:07:52 +0000 2013","in_reply_to_user_id":null,"favorite_count":0,"id_str":"364326884395323393","place":null,"user":{"location":"Old Trafford, Manchester, M16 ","default_profile":false,"profile_background_tile":true,"statuses_count":20839,"lang":"en","profile_link_color":"BD0015","profile_banner_url":"https://pbs.twimg.com/profile_banners/16557902/1347990848","id":16557902,"following":null,"protected":false,"favourites_count":0,"profile_text_color":"333333","description":"Tweeting the latest Manchester United news from the BBC and a number of other sources. Unofficial. Created by @gavreilly.","verified":false,"contributors_enabled":false,"profile_sidebar_border_color":"FFFFFF","name":"BBC Manchester Utd","profile_background_color":"BD0015","created_at":"Thu Oct 02 11:24:52 +0000 2008","default_profile_image":false,"followers_count":56086,"profile_image_url_https":"https://si0.twimg.com/profile_images/61130289/manutd_normal.png","geo_enabled":true,"profile_background_image_url":"http://a0.twimg.com/profile_background_images/662809119/lj2ujpnj7iwwvvxxpoor.jpeg","profile_background_image_url_https":"https://si0.twimg.com/profile_background_images/662809119/lj2ujpnj7iwwvvxxpoor.jpeg","follow_request_sent":null,"url":"http://news.bbc.co.uk/sport2/hi/football/teams/m/man_utd/default.stm","utc_offset":3600,"time_zone":"London","notifications":null,"profile_use_background_image":true,"friends_count":54572,"profile_sidebar_fill_color":"FFC8C7","screen_name":"bbcmanutd","id_str":"16557902","profile_image_url":"http://a0.twimg.com/profile_images/61130289/manutd_normal.png","listed_count":789,"is_translator":false},"coordinates":null},"contributors":null,"text":"RT @bbcmanutd: Daily Mail: Vincent Kompany says Manchester United are favourites http://t.co/NB2p1cqlRs #mufc","geo":null,"retweeted":false,"in_reply_to_screen_name":null,"truncated":false,"lang":"en","entities":{"symbols":[],"urls":[],"hashtags":[{"text":"mufc","indices":[104,109]}],"user_mentions":[{"id":16557902,"name":"BBC Manchester Utd","indices":[3,13],"screen_name":"bbcmanutd","id_str":"16557902"}]},"in_reply_to_status_id_str":null,"id":364329399950540800,"source":"<a href=\"http://blackberry.com/twitter\" rel=\"nofollow\">Twitter for BlackBerry®<\/a>","in_reply_to_user_id_str":null,"favorited":false,"in_reply_to_status_id":null,"retweet_count":0,"created_at":"Mon Aug 15 10:17:52 +0000 2013","in_reply_to_user_id":null,"favorite_count":0,"id_str":"364329399950540800","place":null,"user":{"location":"","default_profile":false,"profile_background_tile":false,"statuses_count":3520,"lang":"en","profile_link_color":"2FC2EF","profile_banner_url":"https://pbs.twimg.com/profile_banners/561283874/1375643576","id":561283874,"following":null,"protected":false,"favourites_count":234,"profile_text_color":"666666","description":"A curious case. An enigma. ..","verified":false,"contributors_enabled":false,"profile_sidebar_border_color":"181A1E","name":"vi̲̅ƞci̲̅ thE EnIgma","profile_background_color":"1A1B1F","created_at":"Mon Apr 23 16:41:58 +0000 2012","default_profile_image":false,"followers_count":195,"profile_image_url_https":"https://si0.twimg.com/profile_images/378800000241332248/569425827c3cc3ad8ff44958bad5307a_normal.jpeg","geo_enabled":false,"profile_background_image_url":"http://a0.twimg.com/images/themes/theme9/bg.gif","profile_background_image_url_https":"https://si0.twimg.com/images/themes/theme9/bg.gif","follow_request_sent":null,"url":null,"utc_offset":7200,"time_zone":"Amsterdam","notifications":null,"profile_use_background_image":true,"friends_count":339,"profile_sidebar_fill_color":"252429","screen_name":"Dinnydavinci","id_str":"561283874","profile_image_url":"http://a0.twimg.com/profile_images/378800000241332248/569425827c3cc3ad8ff44958bad5307a_normal.jpeg","listed_count":0,"is_translator":false},"coordinates":null}
</code></pre>
<p>I am reading them with the following code:</p>
<pre><code>public void performAnalysis() {
File tweets;
String[] categories;
tweets = new File("//home//andrew//Python//Tweets//");
categories = tweets.list();
for (int i = 0; i < categories.length; ++i) {
String category = categories[i];
File file = new File(tweets, category);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String rawTweet = sc.nextLine().trim();
if (rawTweet.equals(""))
continue;
Tweet parsedTweet = new Gson().fromJson(rawTweet, Tweet.class);
System.out.println(parsedTweet.getText());
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>I have another class called Tweet, with one instance variable: text. The Google Gson library allows me to strip the field "text" from the JSON which I am importing.</p>
<p>My problem is regarding the if statement in the while loop. It seems to be necessary. I didn't realise I had whitespace after my JSONs, but the program crashes at the end of each file it reads if I don't include this.</p>
<p>Does anybody have any suggestions on how to check the text file for white space or get rid of it without this <code>if</code> statement? Maybe I'm totally wrong, but it just looks horrible to me - especially since I'm saving the line, trimming it, THEN checking if it's empty. I was going to check first, but I don't know how without using <code>sc.nextLine()</code> twice (thus skipping a line).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T13:21:56.160",
"Id": "46887",
"Score": "0",
"body": "Some suggestions not related to your question : you can use for-each instead of a normal for loop. And if I'm not mistaken, you don't need to create a new Gson object all the time (not too sure about that)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T15:22:33.840",
"Id": "46892",
"Score": "0",
"body": "Maybe the problem is when you're receiving or saving the JSON. Cause if the problem is a blank space at the end of the file when you receive it or save it you should fix the problem there and not in the parsing phase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T15:25:11.790",
"Id": "46893",
"Score": "0",
"body": "I am downloading the tweets using Flume and streaming them into Hadoop. After some operation, I output them as JSON by saving them to text directly as they are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T15:32:08.330",
"Id": "46898",
"Score": "1",
"body": "If you receive it with a blank space at the end and save it with the space, then you should trim it before saving, that would simplify the parsing. That is if the white space is at the end of the file."
}
] |
[
{
"body": "<p>You're skipping a line that contains spaces. That's what the trim() does, removes spaces from the beginning and the end of a line.</p>\n\n<p>There is this alternative:</p>\n\n<pre><code> if (!rawTweet.equals(\"\")) {\n Tweet parsedTweet = new Gson().fromJson(rawTweet, Tweet.class);\n System.out.println(parsedTweet.getText());\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T12:15:29.937",
"Id": "29648",
"ParentId": "29631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T00:32:34.380",
"Id": "29631",
"Score": "3",
"Tags": [
"java",
"json"
],
"Title": "Parsing JSON from file in Java"
}
|
29631
|
<p>I have an application with HTML, external JavaScript and a bit of jQuery on the page which is initializing specific stuff to that page. I try to keep most of the JavaScript in other files. However I'm unsure if stuff in the DOM Ready function should be split into a separate file as well which is specific to that page. I'm wondering the best way to structure this.</p>
<p>The code for the <code>calculator.html</code> page might look like this:</p>
<pre><code><!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="css/global.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/global.js"></script>
<script type="text/javascript" src="js/calculator.js"></script>
<script>
$(function() {
calc.initialize();
calc.loadPreviousState();
});
</script>
</head>
<body>
<!-- page HTML code here -->
</body>
</html>
</code></pre>
<p>The <code>global.js</code> files would be common JavaScript functions used on most pages. The <code>calc.js</code> file is only used by the <code>calculator.html</code> page and might have 20 odd functions in it. Assume that the two function calls inside the DOM Ready event need to be done on DOM load.</p>
<p>My question is, should I move this DOM Ready code into the top of the <code>calculator.js</code> file for clean code and readability? That way all the JavaScript would be contained in it's own file. For example here's the revised <code>calculator.js</code> file:</p>
<pre><code>$(function() {
calc.initialize();
calc.loadPreviousState();
});
var calc = {
initialize: function() {
// code here
return true;
},
loadPreviousState: function() {
// code here
return true;
}
};
</code></pre>
<p>What's best practice here?</p>
<p>Many thanks!</p>
|
[] |
[
{
"body": "<p>I don't know if it is <em>good practice</em>, but in my eyes it would be cleaner, since you have several JS-files at this point, to separate markup, layout and JS completely. So <code>$()</code> would reside in a .js-File.</p>\n\n<p>In some cases, when you only have a few lines of JS or -on the other hand- if you have to care for every millisecond to deliver a good page experience, it would make sense to embed JS in the html-file and retrieve the non-critical JS at later time dynamically.</p>\n\n<p>It depends on your usecase.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T21:21:20.487",
"Id": "46923",
"Score": "0",
"body": "Cool thanks, that's my current thinking as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T08:23:01.473",
"Id": "29641",
"ParentId": "29637",
"Score": "1"
}
},
{
"body": "<p>First of all, scripts should be placed at the bottom of the page, just before <code></body></code> for two main reasons:</p>\n\n<ol>\n<li>To ensure that the DOM is parsed before it is accessed.</li>\n<li>So that scripts will not block the loading of the page.</li>\n</ol>\n\n<p>In the first case, you need to ensure the scripts will not try to access the DOM prematurely or it will throw an error. A safe move is to place the scripts after the DOM is parsed (not necessarily ready).</p>\n\n<p>The second case is about scripts blocking the page. To avoid that, you place scripts after the page contents. That way, you will get a full page before any [potentially blocking] scripts get in the way.</p>\n\n<p>So move those scripts down.</p>\n\n<hr>\n\n<p>As for your script order problem, scripts are normally loaded and parsed sequentially. The usual order is</p>\n\n<ul>\n<li>Libraries</li>\n<li>Plugins</li>\n<li>Non-active scripts, like utility functions</li>\n<li>Your own scripts</li>\n</ul>\n\n<p>However...</p>\n\n<p>The handler for DOM ready <code>$(function(){...})</code> does not execute until the DOM is ready. That means all other scripts would have been loaded by the time it executes. So it does not matter if it comes before or after your utility library, your utility library would have been loaded, parsed and executed by the time the handler gets executed.</p>\n\n<p>But for the sake of readability, I'd place your scripts after the <code>calc</code>. That way, in one skim of your script, a fellow developer would know <code>calc</code> exists, rather than look for it somewhere in the bottom of your file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T21:19:45.620",
"Id": "46922",
"Score": "0",
"body": "Thanks, I probably didn't explain myself clearly enough. I'm particularly interested in should the DOM Ready code go in a separate file (for cleanliness and readability) or should it go in the HTML page? Bear in mind the code is specific just to this page and there is a JavaScript file for this page already. What are your thoughts on that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:41:33.830",
"Id": "46961",
"Score": "1",
"body": "@user2640336 I'd place it in an external script. Aside from the \"cleanliness and readability\", external scripts are cached, making it a slight performance benefit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T11:50:15.373",
"Id": "29645",
"ParentId": "29637",
"Score": "1"
}
},
{
"body": "<p>I normally keeps the dom ready statement in a separate js file so that the size of the initial render will be minimized as much as possible. </p>\n\n<p>The only time I may do otherwise if I have to pass some state data to any of the initialization methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T02:54:54.137",
"Id": "29671",
"ParentId": "29637",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29671",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T05:33:53.017",
"Id": "29637",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Should jQuery DOM Ready code be in the page with the HTML or separate JavaScript file?"
}
|
29637
|
<p>In a <a href="https://stackoverflow.com/questions/14495757/invalidoperationexception-in-release-since-net-4-0">former question on SO</a> I described a problem with a construct called 'EnumBase'.</p>
<p>As I sad there, I am not involved when basic implementation happened. So I'm not sure why the thinks are a they are. I only know that the code was written in times of .Net 2 and 3.5. The derived classes are useed as DataSources in ASP.Net and WinForm GUIs and also for Switch-Statements. </p>
<p>Here the shorted main code of a typical derivates class:</p>
<pre><code>public class Elements : EnumBase<int, Elements>
{
public static readonly Elements Element1 = Create("Number 0", 0);
public static readonly Elements Element2 = Create("Number 1", 1);
// This empty constuctor is the solution of the previous question
static Elements() {}
private static Elements Create(string text, int value)
{
return new Elements() { text = text, value = value };
}
public static String GetElement(int id)
{
return BaseItemList.Single(v => v.Value == id).Text;
}
}
</code></pre>
<p>And the EnumBase inself (the parameter <code>dosentMatter</code> in the empty constructor is no joke):</p>
<pre><code>[Serializable()]
public class EnumBase<T, E> : IEqualityComparer<E>
where E : EnumBase<T, E>
{
private static readonly List<E> list = new List<E>();
protected string text;
protected T value;
protected static IList<E> BaseItemList
{
get
{
return list.Distinct(new EnumBase<T, E>(false)).ToList();
}
}
protected EnumBase()
{
list.Add(this as E);
}
/// <summary>
/// Constructor for distinct to avoid empty elements in the list
/// </summary>
private EnumBase(bool dosentMatter) {}
public string Text
{
get { return text; }
}
public T Value
{
get { return value; }
}
#region IEqualityComparer<E> Member
// ...
#endregion
}
</code></pre>
<p>The switch statemaents are also not really nice (i'm not a friend of long switch an if-else-constructs, but bring polymorphism in the code is still a very very long way):</p>
<pre><code>Switch
Case Elements.Element1.value
...
Case Elements.Element2.value
...
</code></pre>
<p>As you see, you have to use <code>.value</code> every time, which is a nice source for bugs if you forgot it :-/</p>
<p>All in all living with EnumBase leaves every time a strange feeling. There is a lot of code which is to write in every derived class again and again. And a lot of things can go wrong if you create or use an EnumBase derived-class. One the other hand it works but this can be 'the' argument.</p>
<p><strong>From my point of view it would be nice if I can use more types form .Net-Framework instead of own programmed types. So the Question is, is there maybe something new in .net 4.0 (or even exists in .Net before 4.0) which make this implementation (in parts) obsolete?</strong></p>
<p>I would be grateful for any hint.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T09:22:23.987",
"Id": "46868",
"Score": "0",
"body": "What is your intent? Why do you need such class in the first place?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T10:18:42.777",
"Id": "46872",
"Score": "0",
"body": "The class was primarily designed as a \"extended\" enum with the possibility to use it as a data source for winform controls (especially combbox) and asp.net."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T10:50:33.447",
"Id": "46874",
"Score": "3",
"body": "ok, let me rephrase: what your class can do what can not be done by using some `IList<MyStandartDotNetEnum>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T11:20:35.533",
"Id": "46879",
"Score": "0",
"body": "This is a interesting question. In first moment I would say the static access to elements, but this would not be true. So I have to think about your point. Thanks for the moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T06:03:15.750",
"Id": "47821",
"Score": "0",
"body": "@Nik: The inner implementation is a list, so all stuff \"around\" seems to want make items use more comfortable/easy ... but in my eyes it do not really work. If you can post your comment as answer I will mark it as solution."
}
] |
[
{
"body": "<p>So, extending my comment... </p>\n\n<p>Enums are designed to represent a fixed number of states. This is their purpose. If that is what you need then nothing prevents you from using standart <code>enum</code>. If you want to specify items source as a collection of enum values - use <code>IEnumerable<MyStandartEnum></code>, for example:</p>\n\n<pre><code>//collection of all enum values\nvar allVlues = Enum.GetValues(typeof(MyStandartEnum)).Cast<MyStandartEnum>();\n//collection of elements which satisfy SomeCondition() (extension method)\nvar someValues = Enum.GetValues(typeof(MyStandartEnum)).Cast<MyStandartEnum>().Where(x => x.SomeCondition());\n</code></pre>\n\n<p>If you need some complicated logic added to enum, if you need to <em>extend</em> it, etc., that only means that enum is not the right abstraction in your case. Instead of trying to emulate <code>enum</code>'s behaviour in some wierd abstract class, you should build a proper class to represent your data and then use generic collections (or implement your own).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T07:41:26.067",
"Id": "48033",
"Score": "0",
"body": "Thanks for adding comment as answer. +1 for adding more informations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T07:06:50.720",
"Id": "30246",
"ParentId": "29640",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30246",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T08:16:53.227",
"Id": "29640",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"asp.net",
"winforms"
],
"Title": "Searching for a better implementation to EnumBase"
}
|
29640
|
<p>I'd like a general opinion on my piece of code (which does exactly what I want it to do). I feel like I'm using bad practices, like a DB query within a <code>foreach</code> loop, or grabbing the lowest value in a non-elegant way (sorting, then using the object with an index of 0). I'm also not sure on my usage of the DB queries inside my controller, instead of passing it to the model.</p>
<p>Note this is on Laravel v3:</p>
<pre><code>public function get_predict()
{
$champions = DB::table('champions')
->get(array('id','name','released','price_ip','price_rp'));
$now = strtotime(date('Y-m-d'));
foreach($champions as &$champion) {
$id = $champion->id;
$champion_sales = DB::table('sales')
->where('type','=','1')
->where('for','=',$id)
->get();
$champion->sales = $champion_sales;
foreach($champion->sales as &$sale) {
$dateout = strtotime($sale->date_out);
$sale->days_since = floor(($now - $dateout)/(60*60*24));
}
usort($champion->sales, function($b, $a) {
return strcmp($b->days_since, $a->days_since);
});
if(isset($champion->sales[0]->days_since)) {
$champion->most_recent = $champion->sales[0]->days_since;
$champion->last_sale = date('Y-m-d',strtotime($champion->sales[0]->date_out));
}
}
return View::make('champion.predict')->with('champions', $champions);
}
</code></pre>
|
[] |
[
{
"body": "<p>Right, one general opinion coming up:</p>\n\n<ul>\n<li><code>Static</code>'s, at least the way you're using them, are just globals in drag. Don't do that. If you need both the <code>View</code> and <code>DB</code> class(or at least some tables from it) in the object, of which you posted a method: either Inject, or lazy-load them. A call to a static method is bound to be slower, and, by the looks of things <code>DB::table</code> is sort-of a factory method. Why call it time and time again, if it's already created and returned the desired object once before. You can injected/lazy-loaded them, or just assign them to a property.</li>\n<li>Anonymous functions (lambda's or closures, whichever name you prefer) aren't my favorite addition to PHP. They feel, to me at least, like a typical PHP afterthought. In essence, they're just syntactic sugar. What they actually do is create an instance of the <code>Closure</code> class. I'm not sure on the internals, but I wouldn't be at all surprised if your code were to create instances of <code>Closure</code> on each iteration of the loop. This isn't that bad in a language like JavaScript, where function objects are <em>very</em> cheap, but in PHP, it'd be far cheaper to define a private method, and pass a callable array to <code>usort</code>. Something along the lines of <code>usort($champion->sales, array($this, 'privateSorterMethod');</code> will almost certainly be faster, especially since you can declare & assign the array outside of the loop. This gives you more control on when and where the array is constructed: not in the loop, if you don't put it there, that's for sure.</li>\n<li>Getting data from the database, and returning the view is doing 2 things, and thus a violation of the Single Responsibility Principle. build your <code>$champions</code> array, and return it back to the controller, or whatever called the <code>get_prediction</code> method. The controller is what should link the Model-layer to the view. That's its job: the controller gets the request, decides what the Model-layer needs to do, and sends the output of the model layer back to the view. The model layer should be unaware of the view and vice-versa.</li>\n<li>Performing that second query inside the loop is, in all likelihood, not the best way forward. Consider using <code>JOIN</code>, to get all data in one go.</li>\n<li>Maintainability: if I were to be assigned your project some time in the future, I'd have to check the actual DB's, to see what you're getting from the <code>sales</code> table. even if you're getting all fields, specify them.</li>\n<li>How are you getting your data? As (assoc-)array's? Objects (<code>Stdclass</code> or another object)? Personally, I prefer data models that are directly mapped to the tables. The properties of these data-models correspond to the field names, and they should have a getter and setter for each property. At least, that's what I'd do.</li>\n</ul>\n\n<p>Notes: Calling a static is slower than calling it once, and assigning its return value for re-use. Adding the <code>getTable</code> methods (see below) does mean added overhead (+1 method call), but the overhead will only be noticeable <em>once</em>.<br/>\nDropping the anonymous function means better performance, I've made a test-script, and it using a callable array is 50~100% faster. Caching enabled or not, it's the fastest way to go, still.<br/>\nFetching rows as data-models with predefined properties <em>is</em> faster than using single <code>stdClass</code> instances, at least: as far as property access is concerned. Basically because the lookup is done using a hashtable, to get the offset of the corresponding <code>zval*</code>. <a href=\"https://stackoverflow.com/questions/17696289/pre-declare-all-private-local-variables/17696356#17696356\">A bit more details here</a></p>\n\n<hr>\n\n<p>Just to clarify what I mean by Inject or lazy-load them:</p>\n\n<pre><code>class Foo\n{\n private $table = null;\n privte $view = null;//this is a bad idea anyway, but just as an example\n public function __construct(array $tables = array(), View $view = null)\n {//you can pass DB and or view instance to constructor\n $this->tables = $tables;\n $this->view = $view;\n }\n public function setTables(Table $inject)\n {//if you didn't pass to constructor, or need another DB instance for something:\n $this->table[$inject->getName()] = $inject;\n }\n public function setView(View $view)\n {//this is standard DI (dependency Injection)\n $this->view = $view;\n }\n //This is GUARANTEED to return an instance of DB\n //Unless a fatal error occurred.\n protected function getTable($name)\n {\n if (!isset($this->table[$name]))\n {//if table isn't set, load instance on the fly => lazy-loading\n $this->table[$name] = DB::table($name);//get the instance\n }\n return $this->table[$name];\n }\n private function sortCallback($a, $b)\n {\n return strcmp($b->days_since, $a->days_since);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T09:05:17.007",
"Id": "29677",
"ParentId": "29649",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29677",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T13:08:54.233",
"Id": "29649",
"Score": "0",
"Tags": [
"php",
"performance",
"sql",
"laravel"
],
"Title": "DB Query within foreach"
}
|
29649
|
<p>In a Rails application, I want to have a complex form with some dynamic behaviour. For example, I want to show a part of the form want I check a box or I want to have different values in a select box when I choose a radio button.</p>
<p>I do this with JQuery. My problem concern the archirecture. I created a form object and I create a init method which init every behaviour of every components like this :</p>
<pre><code> PaintingForm.prototype.init = function() {
var country_listener;
if ($('form.painting').size() === 1) {
this.form = $('form.painting').first();
this.initImageUploader();
this.initSubmit();
this.assignInputs();
this.initAutoComplete();
this.listenCategories();
country_listener = new CountryInputListener('#painting_country_id', '#painting_region_id');
return country_listener.init();
}
};
PaintingForm.prototype.initImageUploader = function() { //some code };
PaintingForm.prototype.initSubmit = function() { //some code };
PaintingForm.prototype.onSubmit = function() { //some code };
PaintingForm.prototype.assignInputs = function() { //some code };
PaintingForm.prototype.listenCategories = function() { //some code };
PaintingForm.prototype.onCategoryInputChange = function() { //some code };
PaintingForm.prototype.loadTechnics = function() { //some code };
PaintingForm.prototype.showDepthIfSculptureChoosen = function() { //some code };
PaintingForm.prototype.onLoadTechnicsSuccess = function() { //some code };
PaintingForm.prototype.initAutoComplete = function() { //some code };
</code></pre>
<p>I'm not satisfied. I think I can split the form like this :</p>
<pre><code>PaintingForm.prototype.init = function() {
var country_listener;
if ($('form.painting').size() === 1) {
this.form = $('form.painting').first();
(new PaintingForm.Category).init()
(new PaintingForm.AutoComplete).init()
(new PaintingForm.Depth).init()
(new CountryInputListener('#painting_country_id', '#painting_region_id')).init();
}
};
//other behaviour for the form
this.PaintingForm.Category = (function() {
//Behaviour for categories
})();
this.PaintingForm.Depth = (function() {
//Behaviour for depth
})();
this.PaintingForm.AutoComplete = (function() {
//Behaviour for autocomplete
})();
</code></pre>
<p>It's better but I'm not sure. There is a lot of interactions between fields. Should I create one object for every fields? Is there a solution with a framework like or angular? Do you have correct examples?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:28:51.637",
"Id": "46894",
"Score": "0",
"body": "You might want to edit to ask about CoffeeScript since you aren't writing JavaScript at all. Client side techniques can be similar, but your title should match what you are asking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:32:41.667",
"Id": "46895",
"Score": "0",
"body": "It edited my question to include this info. I think best practices, on this subject, are the same with JS/CoffeeScript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:03:58.857",
"Id": "46896",
"Score": "1",
"body": "Don't forget that Javascripters cannot read CoffeeScript but CoffeeScripters can read Javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T15:16:09.893",
"Id": "46897",
"Score": "0",
"body": "@Esailija, I converted all the code using [JS2Coffee](http://js2coffee.org/)"
}
] |
[
{
"body": "<p>For a single form, this is the exact reason Knockout.js was created - tutorials here: <a href=\"http://learn.knockoutjs.com/#/?tutorial=intro\" rel=\"nofollow\">http://learn.knockoutjs.com/#/?tutorial=intro</a></p>\n\n<p>Angular is more of a full blown \"SPA\" framework, Knockout is data-binding for JavaScript with things like this: <a href=\"http://knockoutjs.com/documentation/if-binding.html\" rel=\"nofollow\">http://knockoutjs.com/documentation/if-binding.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:52:07.487",
"Id": "47581",
"Score": "0",
"body": "I like your suggestion but.. I like unobstructive javascript. I use simple_form for rails and it's difficulte to customize the html generated. I will check deeper knockout to see it can make me happier than simple_form in the case. Thank!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T13:34:01.983",
"Id": "47652",
"Score": "0",
"body": "knockout is a great framework for complex forms and is easily integratable with rails or whatever you use which can generate html attributes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T08:29:41.367",
"Id": "29984",
"ParentId": "29651",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29984",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:20:46.237",
"Id": "29651",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Best practices to do complex forms with javascript?"
}
|
29651
|
<p>I have a simple encryption module that is used to "encrypt" a text file because it contains some passwords. I only need to encrypt it because I need those passwords in my program (they are used to send an automated bug-report email), but I don't want the end-user to be able to see them. </p>
<p>My "encryption" function is VERY simple and straightforward: it replaces each character in the file with a two-character sequence (either two numbers, two letters, or a number and a letter - these are mapped using a dictionary). The "decryption" function simply reverses the dictionary (<code>{v: k for k, v in _encrypt_key.items()}</code>), then reads the file two-characters at a time and replaces each pair with the corresponding letter. All of this works fine. The file just looks like a bunch of random numbers and letters, so it can't be "read" without the decryption algorithm by any normal end-user.</p>
<p>I used Cython to convert my encryption module (which is a basic Python, <code>.py</code> file), to a <code>.pyd</code> file, so the module itself cannot be read by a normal text-editor.</p>
<p>The problem occurs if the end-user has any Python experience.</p>
<p>For example, it is a very basic task to open the Python console, import the module, open the text file, and decrypt it using the module's "decrypt" function. To prevent this, I used the <code>__main__</code> module:</p>
<pre><code>import __main__ as main
if hasattr(main, '__file__'):
# define functions here
</code></pre>
<p>Now, it cannot be used interactively in a Python console, because the functions simply won't be defined if it is not being imported from an actual Python program.</p>
<p>To "secure" the key, I made the encryption key local to both functions (both the "encrypt" and "decrypt" functions have a copy of a different variable with the same data). Thus, the user cannot view the key directly.</p>
<p>Finally, I made sure that only certain modules can import it:</p>
<pre><code>import __main__ as main
if hasattr(main, '__file__'):
path = os.path.basename(main.__file__)
if path in # tuple of specific files:
# define functions here
</code></pre>
<p>The only loophole I can think of is if the main program itself is edited - other than the encryption module (which is packaged as a <code>.pyd</code>, so I'm not considering it as "open-source"), everything is open-source. If the end-user knows any Python, (s)he can simply open the main program and add a single line, which would show the passwords: <code>print(EXTRA_DATA)</code>.</p>
<p>I thought of one way to prevent this:</p>
<pre><code>from __future__ import print_function
print = lambda *args: None # prevent any printing, since my program itself doesn't require it
</code></pre>
<p>Of course, the user could always remove this, so it doesn't really fix it.</p>
<p>So, my overall questions are: Can I make this any more secure (make the data and module inaccessible by end-users), and can I prevent any way to print variables in my main program? I want to keep it as open-source if possible.</p>
|
[] |
[
{
"body": "<p><strong>Manual attack</strong></p>\n\n<p>First of all, your encryption scheme is very weak and easily exploitable. Given a few hundred characters of ciphertext, even a novice cryptanalyst can crack this cipher in less than 30 minutes with only pen and paper. I recommend you stick to industrial-strength ciphers.</p>\n\n<p><strong>Security by obscurity</strong></p>\n\n<p>The obfuscations you are talking about (making a <code>.pyd</code> file and so on) will do little if anything to stop a serious attacker. The closest analogy I can think of is putting your door mat over the key, instead of just leaving the key in plain sight outside your door. It doesn't work very well. Any true encryption scheme needs to adhere to <a href=\"http://en.wikipedia.org/wiki/Kerckhoffs%27_principle\" rel=\"noreferrer\">Kerchhoff's Principle</a>, which states that a cryptosystem must be secure even if all parts of it (apart from the encryption key) are known by the attacker.</p>\n\n<p><strong>Wrong approach</strong></p>\n\n<p>In other words, you are approaching the problem from the wrong angle. For example, obfuscating the files won't help, because if an attacker has access to the computer the program is run on, he/she can access the memory directly to view the cleartext and/or key. Even worse, the attacker may even have a keylogger running. You need to design an algorithm that is so secure that having a completely open-source program isn't a problem. That is exactly what the people behind e.g. <a href=\"http://www.gnupg.org/\" rel=\"noreferrer\">GPG</a> have done. However, securing such a program against a malicious user isn't practically possible.</p>\n\n<p>The problem is that cryptography is really, really hard. Some of the brightest people on the planet are continuously working to create new, unbreakable ciphers -- and still <a href=\"http://www.schneier.com/blog/archives/2005/08/the_md5_defense.html\" rel=\"noreferrer\">those</a> <a href=\"http://www.schneier.com/blog/archives/2005/02/sha1_broken.html\" rel=\"noreferrer\">ciphers</a> are <a href=\"http://en.wikipedia.org/wiki/Category%3aBroken_stream_ciphers\" rel=\"noreferrer\">often</a> <a href=\"http://en.wikipedia.org/wiki/Category%3aBroken_block_ciphers\" rel=\"noreferrer\">broken</a>.</p>\n\n<p><strong>What to do instead</strong></p>\n\n<p>I recommend reading about common cryptography principles and theory, and how basic ciphers are often broken. Don't bother with securing your program against a user - instead presume the program is running on a secure computer and make the <em>ciphertext</em> as secure as possible instead. Instead, write a cipher that is resistant to common techniques like frequency analysis and similar lexical attacks.</p>\n\n<p>Finally, if you want easy and completely uncrackable encryption, I recommend looking into <a href=\"http://en.wikipedia.org/wiki/One-time_pad\" rel=\"noreferrer\">one-time pads</a>. They are cryptographically secure, but they require a key that is at least as long as the plaintext.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:19:11.147",
"Id": "29654",
"ParentId": "29652",
"Score": "6"
}
},
{
"body": "<p>To be honest, you algorithms looks secure for 5 year old kids and younger, but smarter kids could guess your encoding scheme and decode text message by counting frequences of the letters/digits. (Looking random is not the same as be random)</p>\n\n<p>It's hard to tell how to make it make it more secure. The sure way is to use very long random key (ideally - as long as the message itself) and, for example, XOR your file with it.</p>\n\n<p>There are a lot of options in between, which is what cryptography is about.</p>\n\n<p>Python have a \"disassembler\", so having .pyc or .pyd file won't help.\nIt's the secret key you need to hide, not the algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T05:05:02.060",
"Id": "46946",
"Score": "2",
"body": "While it doesn't remove the underlying problem, Cython will produce C which is then compiled to native code. It's certainly possible to disassemble that as well, but it's nowhere near as easy as disassembling Python bytecode."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:21:23.627",
"Id": "29655",
"ParentId": "29652",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T16:04:19.453",
"Id": "29652",
"Score": "1",
"Tags": [
"python",
"security",
"cryptography",
"cython"
],
"Title": "Is my Encryption Module Secure?"
}
|
29652
|
<p>Coming from a Java kind of OOP, I miss a lot of things in JavaScript. I am working on a Node.Js project, and I would like to use an OO approach.</p>
<p>Looking around and asking in <a href="https://stackoverflow.com/questions/18188083/javascript-oop-in-nodejs-how">StackOverflow</a> I came up with this example scenario (<a href="http://jsfiddle.net/eS7LE/5/" rel="nofollow noreferrer">jsFiddle</a>). </p>
<pre><code>function inheritPrototype(childObject, parentObject) {
var copyOfParent = Object.create(parentObject.prototype)
copyOfParent.constructor = childObject
childObject.prototype = copyOfParent
}
//example
function Canvas (id) {
this.id = id
this.shapes = {} //instead of array?
console.log("Canvas constructor called "+id)
}
Canvas.prototype = {
constructor: Canvas
, getId: function() {
return this.id
}
, getShape: function(shapeId) {
return this.shapes[shapeId]
}
, getShapes: function() {
return this.shapes
}
, addShape: function (shape) {
this.shapes[shape.getId()] = shape
}
, removeShape: function (shapeId) {
var shape = this.shapes[shapeId]
if (shape)
delete this.shapes[shapeId]
return shape
}
}
function Shape(id) {
this.id = id
this.size = { width: 0, height: 0 }
console.log("Shape constructor called "+id)
}
Shape.prototype = {
constructor: Shape
, getId: function() {
return this.id
}
, getSize: function() {
return this.size
}
, setSize: function (size) {
this.size = size
}
}
//inheritance
function Square(id, otherSuff) {
Shape.prototype.constructor.apply( this, arguments );
this.stuff = otherSuff
console.log("Square constructor called "+id)
}
inheritPrototype(Square, Shape)
Square.prototype.getSize = function() { //override
return this.size.width
}
function ComplexShape(id) {
Shape.prototype.constructor.apply( this, arguments );
this.frame = null
console.log("ComplexShape constructor called "+id)
}
inheritPrototype(ComplexShape, Shape)
ComplexShape.prototype.getFrame = function() {
return this.frame
}
ComplexShape.prototype.setFrame = function(frame) {
this.frame = frame
}
function Frame(id) {
this.id = id
this.length = 0
}
Frame.prototype = {
constructor: Frame
, getId: function() {
return this.id
}
, getLength: function() {
return this.length
}
, setLength: function (length) {
this.length = length
}
}
/////run
var aCanvas = new Canvas("c1")
var anotherCanvas = new Canvas("c2")
console.log("aCanvas: "+ aCanvas.getId())
var aSquare = new Square("s1", {})
aSquare.setSize({ width: 100, height: 100})
console.log("square overridden size: "+aSquare.getSize())
var aComplexShape = new ComplexShape("supercomplex")
var aFrame = new Frame("f1")
aComplexShape.setFrame(aFrame)
console.log(aComplexShape.getFrame())
aCanvas.addShape(aSquare)
aCanvas.addShape(aComplexShape)
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)
anotherCanvas.addShape(aCanvas.removeShape("supercomplex"))
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)
console.log("Shapes in anotherCanvas: "+Object.keys(anotherCanvas.getShapes()).length)
console.log(aSquare instanceof Shape)
console.log(aComplexShape instanceof Shape)
</code></pre>
<p>Is this approach correct (best practices)? Should I do something differently? </p>
<p>The idea would be then to create a js file for each class and use <code>module.exports</code>.. in Node.Js I will also use Mongoose to store the objects into a database, I guess I will need a way to translate my objects into Mongoose Models and back..</p>
<p><strong>EDIT:</strong> how would one implement private methods used internally?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:02:45.257",
"Id": "46906",
"Score": "0",
"body": "Like I showed in my answer, you can prefix a method or field with an underscore to communicate that this is an internal method or field, and it should not be accessed directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T19:14:58.733",
"Id": "46916",
"Score": "0",
"body": "As per the SO question : There is nothing really specific about OO JS in node.js. There is just OO JS. Your question is about translating Java OOP techniques to JS, which is just not right. I think it better you spent the same time/energy in learning how JS's prototype-based model works, and how you can use it to your advantage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T19:19:35.063",
"Id": "46917",
"Score": "0",
"body": "@tomdemuyt But I am not. I just stated that I am coming from a Java background -- it is not my intention to use Java style OO in JS. \n\nHowever, I can only work with what I know: hence the question, how to do OO in JS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T23:33:40.940",
"Id": "46933",
"Score": "0",
"body": "@fusio btw can you specify what you miss from Java object model?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T23:46:35.177",
"Id": "46934",
"Score": "0",
"body": "I miss a clear and well defined structure (Class, Instance, Field, Method, inheritance, yada yada). Today I learned a lot about OO JS (until now I only used it \"functional\", with the exception of jquery I guess). When I think OO I imagine Java classes.. even after this I still miss having a Class with all its methods declared inside, with proper private methods/fields etc.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T00:04:30.617",
"Id": "46935",
"Score": "0",
"body": "@fusio in e.g. browser js you do need a wrapper IIFE where you will define everything \"about a Class\" inside somewhere :) But this will cause additional level of indentation for everything and is not needed in node js because node.js automatically adds the wrapper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T17:09:44.880",
"Id": "89088",
"Score": "0",
"body": "I know I'm a tad late to the game, but Mozilla Developer Network has a nice intro to OO JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript. After that, check out [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain)."
}
] |
[
{
"body": "<h2>Pretty good code.</h2>\n\n<p>From an OOP perspective, this is exactly right. From a formatting perspective, this is almost flawless. I hardly have anything to say about this code, but I see very little that I would change.</p>\n\n<p>The only issue that I see is an irregular formatting choice. These commas:</p>\n\n<pre><code>Shape.prototype = {\n constructor: Shape\n , getId: function() {\n return this.id\n }\n , getSize: function() {\n return this.size\n }\n , setSize: function (size) {\n this.size = size\n }\n}\n</code></pre>\n\n<p>should be like this:</p>\n\n<pre><code>Shape.prototype = {\n constructor: Shape,\n getId: function () {\n return this.id\n },\n getSize: function () {\n return this.size\n },\n setSize: function (size) {\n this.size = size\n }\n};\n</code></pre>\n\n<h2><a href=\"https://softwareengineering.stackexchange.com/questions/180585/are-there-any-oo-principles-that-are-practically-applicable-for-javascript\">Oh and you need to read this world-changing answer about OO practices in JS.</a></h2>\n\n<p>Be sure to press B while reading that, because if not, you'll evolve into a legendary OOP developer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-28T14:50:08.163",
"Id": "104570",
"Score": "0",
"body": "comma first style.. I am still undecided if I like it or not, working with the classic style atm ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-28T15:27:55.417",
"Id": "104586",
"Score": "0",
"body": "@fusio That is of course, perfectly ok. It's good to know the conventional practice though in case you decide to work on a group project."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T11:35:30.717",
"Id": "58116",
"ParentId": "29653",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T16:32:46.877",
"Id": "29653",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"inheritance",
"prototypal-class-design"
],
"Title": "Understanding OO JavaScript with a simple scenario"
}
|
29653
|
<p>I wrote <a href="https://github.com/yasar11732/HttpStatusCodes" rel="nofollow noreferrer">this small project</a> to practice threading in Java. At first, I planned to do it like <a href="https://stackoverflow.com/questions/18186336/what-type-of-queue-to-use-to-distribute-jobs-between-worker-threads">this</a>. But later, someone pointed me to <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executor.html" rel="nofollow noreferrer">Executor</a>. Then, I found <a href="http://www.baptiste-wicht.com/2010/09/java-concurrency-part-7-executors-and-thread-pools/" rel="nofollow noreferrer">this tutorial</a> and followed it through. Here is my code;</p>
<pre><code>/*
* HttpStatusCodes
*
* First version
*
* 2013-08-12
*
* This code is copyrighted under Creative Commons Attribution-ShareAlike 3.0 Unported
* Copyright (c) Yaşar Arabacı http://creativecommons.org/licenses/by-sa/3.0/deed.en
*/
package com.github.HttpStatusCodes;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A java class to fetch Http status of multiple urls in parallel.
* The HttpStatusCodes class aims to provide an easy way to get HTTP Status
* codes from a list of urls.
*
* @author Yaşar Arabacı <yasar11732@gmail.com>
*/
public class HttpStatusCodes {
private BufferedReader input;
private int numThreads;
/**
* When invoked from command line, HttpStatusCodes will read urls from the
* files whose names were passed in arguements and print results to
* standart output.
*
* @param args
*/
public static void main(String[] args) {
for (String arg : args) {
HttpStatusCodes app;
try {
app = new HttpStatusCodes(new FileReader(new File(arg)), 16);
} catch (FileNotFoundException e) {
System.err.println("File doesn't exist: " + e.getMessage());
continue;
}
HashMap<String, String> results = app.get();
for (String key : results.keySet()) {
System.out.println(key + " " + results.get(key));
}
}
}
/**
* Container for pairs of urls and statuses.
*/
private class UrlAndCode {
public String url;
public String statusCode;
public UrlAndCode(String url, String statusCode) {
this.url = url;
this.statusCode = statusCode;
}
}
/**
* This class gets executed in a seperate Thread to
* get status of a single url
*/
private class getStatus implements Callable<UrlAndCode> {
private String location;
private int timeout;
public getStatus(String location, int timeout) {
this.location = location;
this.timeout = timeout;
}
@Override
public UrlAndCode call() {
URL url;
// to fix Malformed urls
if (!location.startsWith("http")) {
location = "http://" + location;
}
// url can still be malformed
try {
url = new URL(location);
} catch (MalformedURLException e) {
return new UrlAndCode(location, e.getMessage());
}
HttpURLConnection con = null;
Integer statusCode;
try {
con = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
con.setConnectTimeout(timeout * 1000);
con.setRequestMethod("HEAD");
statusCode = new Integer(con.getResponseCode());
} catch (Exception e) {
/*
* Exception will be returned along with url, otherwise we can't
* know which Exception on which url. Otherwise, it will be hard to
* track Exceptions.
*/
return new UrlAndCode(location, e.getClass() + ":" + e.getMessage());
} finally {
if (con != null) {
con.disconnect();
}
}
return new UrlAndCode(location, statusCode.toString());
}
}
/**
*
* @param r Urls will be read from this Reader line by line
* @param i number of threads to use
*/
public HttpStatusCodes(Reader r, int i) {
input = new BufferedReader(r);
numThreads = i;
}
/**
* see {@link #HttpStatusCodes(Reader,int) HttpStatusCodes}. Timeout will
* default to 4 seconds.
*/
public HttpStatusCodes(Reader r) {
this(r, 4);
}
/**
* calls {@link #get(int) get} with default timeout of 2 seconds.
*/
public HashMap<String, String> get() {
return get(2);
}
/**
* When this method is invoked, urls will be distributed among worker threads
* to be connected. After all urls have been tried, this method will return.
* @param timeout How many seconds to wait before getting a response from connection.
* @return A HashMap of <String,String> keys hold urls, values hold status codes or error messages.
*/
public HashMap<String, String> get(int timeout) {
HashMap<String, String> results = new HashMap<>();
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
CompletionService<UrlAndCode> pool = new ExecutorCompletionService<>(threadPool);
String line;
int numWorks = 0;
try {
while ((line = input.readLine()) != null) {
pool.submit(new getStatus(line, timeout));
numWorks++;
}
} catch (IOException e) {
Logger.getLogger(HttpStatusCodes.class.getName()).log(Level.SEVERE, null, e);
threadPool.shutdown();
return null;
} finally {
try {
input.close();
} catch (IOException e) {
/*
* Closing the input stream is not critical for us, will log
* and continue
*/
Logger.getLogger(HttpStatusCodes.class.getName()).log(Level.SEVERE, null, e);
}
}
// Uncomment for debugging.
//System.out.println(numWorks + " jobs added.");
while (numWorks > 0) {
UrlAndCode result;
try {
result = pool.take().get();
} catch (InterruptedException | ExecutionException e) {
Logger.getLogger(HttpStatusCodes.class.getName()).log(Level.SEVERE, null, e);
threadPool.shutdown();
return null;
}
results.put(result.url, result.statusCode);
numWorks--;
// Uncomment for debugging
// System.out.println(numWorks + " jobs remaining.");
}
threadPool.shutdown();
return results;
}
}
</code></pre>
<p>You can also <a href="https://raw.github.com/yasar11732/HttpStatusCodes/master/src/com/github/HttpStatusCodes/HttpStatusCodes.java" rel="nofollow noreferrer">find the codes here</a>. I am looking for a general review.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T18:25:11.343",
"Id": "46915",
"Score": "3",
"body": "I'll suggest you to use the interface `Map`instead of the implementation `HashMap`. More information here http://stackoverflow.com/questions/147468/why-should-the-interface-for-a-java-class-be-prefered"
}
] |
[
{
"body": "<p>I'll talk about the code in general, not about the functionality.</p>\n\n<hr>\n\n<pre><code>package com.github.HttpStatusCodes;\n</code></pre>\n\n<p>Package names are used to identify the associated developer with the package. The problem here is that, unless you work for GitHub and write this under their umbrella, you should not use <code>com.github</code> for your packages even if they're hosted GitHub. This might lead to the wrong assumption that it is source code released by/from GitHub Inc..</p>\n\n<p>If you do not have a domain, please use your e-mail address like this:</p>\n\n<pre><code>package com.gmail.yasar.HttpStatusCodes\n</code></pre>\n\n<p>Or if you don't even want this, at least add your GitHub name to the package:</p>\n\n<pre><code>package com.github.yasar.HttpStatusCodes\n</code></pre>\n\n<hr>\n\n<pre><code>package com.github.HttpStatusCodes;\n...\npublic class HttpStatusCodes {\n</code></pre>\n\n<p>That's not a good way to name packages and classes. They should not have identical names, and the class name makes it sound like it's an Enum. A better naming would be something like (but still not perfect):</p>\n\n<pre><code>package com.github.yasar.HttpTools;\n...\npublic class HttpStatusChecker {\n</code></pre>\n\n<hr>\n\n<pre><code>private class getStatus implements Callable<UrlAndCode> {\n</code></pre>\n\n<p>Classes are normally UpperCamelCase...though, seems like a Typo.</p>\n\n<hr>\n\n<pre><code>public HashMap<String, String> get(int timeout) {\n</code></pre>\n\n<p>Get what? <code>get</code> is not a good name for a function. <code>getStatusCodes()</code>, <code>getWebsiteStatus()</code>, <code>checkWebsites()</code>, <code>doWebsiteChecking()</code>, <code>runCheck()</code> or something else would be a better name for this function. You should be able to derive from the name of the function it's...well, function.</p>\n\n<hr>\n\n<pre><code>public HttpStatusCodes(Reader r, int i) {\n</code></pre>\n\n<p>Quick! What is <code>i</code>?!</p>\n\n<p>Fortunately, we live in a time were length of variable names do not matter, please use descriptive, even if longer, names.</p>\n\n<pre><code>public HttpStatusCodes(Reader reader, int numberOfThreads) {\n</code></pre>\n\n<p>If that collides with private variables, you can use <code>this</code>:</p>\n\n<pre><code>public HttpStatusCodes(Reader reader, int numberOfThreads) {\n this.reader = reader;\n this.numberOfThreads = numberOfThreads;\n}\n</code></pre>\n\n<hr>\n\n<p>Also consider separating the Main-Method from this class.</p>\n\n<hr>\n\n<pre><code>public HashMap<String, String> get(int timeout) {\n HashMap<String, String> results = new HashMap<>();\n</code></pre>\n\n<p>You should always use the lowest common denominator for Objects, meaning always use the underlaying interface unless not possible.</p>\n\n<pre><code>public Map<String, String> get(int timeout) {\n Map<String, String> results = new HashMap<>();\n</code></pre>\n\n<p>That easies use of your methods and makes them more generic and flexible.</p>\n\n<hr>\n\n<pre><code>HttpURLConnection con = null;\nInteger statusCode;\ntry {\n // SNIP\n statusCode = new Integer(con.getResponseCode());\n} catch (Exception e) {\n // SNIP\n} finally {\n if (con != null) {\n con.disconnect();\n }\n}\nreturn new UrlAndCode(location, statusCode.toString());\n</code></pre>\n\n<p>You're saving a value and return it later for no reason. <code>finally</code> will be executed even if you return out of the block and is guaranteed to always run except if you call <code>System.exit(0)</code> or something really bad happens (cleaning crew unplugging or hitting the PC).</p>\n\n<pre><code>HttpURLConnection con = null;\ntry {\n // SNIP\n return new UrlAndCode(location, con.getResponseCode().toString());\n} catch (Exception e) {\n // SNIP\n} finally {\n if (con != null) {\n con.disconnect();\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>private class UrlAndCode {\n\n public String url;\n public String statusCode;\n\n public UrlAndCode(String url, String statusCode) {\n</code></pre>\n\n<p>HTTP Status codes are <em>always</em> integers. They're always handled as integers, so consider also keeping them as integers.</p>\n\n<pre><code>private class UrlAndCode {\n\n public String url;\n public int statusCode;\n\n public UrlAndCode(String url, int statusCode) {\n</code></pre>\n\n<p>I just saw that you're also using it to store error messages, in that case you should either introduce a field to the error, or rename the variable.</p>\n\n<pre><code>public String status;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:17:49.487",
"Id": "46972",
"Score": "0",
"body": "If you want, you could add my comment to your answer, I think it could go well with your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:31:33.743",
"Id": "46975",
"Score": "1",
"body": "@Marc-Andre: Will do, thanks. I also just notice a few other things."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:57:15.903",
"Id": "29684",
"ParentId": "29656",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:54:21.360",
"Id": "29656",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "Threading in Java"
}
|
29656
|
<p>I'm creating an unordered list element in Backbone via Underscore templating:</p>
<pre><code><ul id="FrontRack" style="
background-image: url({%= data.get('racks').at(0).get('imageUrls')[0] %});
height:{%= data.get('racks').at(0).get('pixelHeight') %}px;
width:{%= data.get('racks').at(0).get('pixelWidth') %}px;
">
<li>Hello World</li>
</ul>
</code></pre>
<p>I'm wondering two things:</p>
<ul>
<li>Is setting <code>style</code> still considered bad practice when creating elements through templating?</li>
<li>Should I be setting the style using jQuery after I generate the HTML from the template? This would be done inside of Backbone's render instead of inside of the template.</li>
</ul>
<p>Something like:</p>
<pre><code>render: function () {
this.$el.html(this.template(this.model.toJSON()));
this.$el('#FrontRack').css({ backgroundImage: ... }); // Example
return this;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:08:41.957",
"Id": "46957",
"Score": "1",
"body": "How many different height-width-image-combination to you have? Maybe you can put this in some css classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:36:45.923",
"Id": "46977",
"Score": "0",
"body": "The height/width is being pulled from a customer database. The customer uploads images which fit the dimensions of their racks. So, the height and width could be any size."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T21:15:58.093",
"Id": "47114",
"Score": "5",
"body": "If the images can be any size, it is impractical to use classes. So yes, it would be appropriate to use inline styles for truly dynamic content. Keep in mind that client side languages are slow (eg. you'll have to wait for the image to load to figure out its dimensions), so anything you can do serverside is going to have better performance from the user's perspective."
}
] |
[
{
"body": "<p>Interesting questions.</p>\n\n<ul>\n<li><p>Is setting 'style' still considered bad practice when creating elements through templating?</p>\n\n<p>Only if you cannot reasonably use css classes (which is your case)</p></li>\n<li><p>Should I be setting the style using jQuery after I generate the HTML from the template?</p>\n\n<p>Since you know the height and size prior to generating, you should make this part of the template</p></li>\n</ul>\n\n<p>Also, this : </p>\n\n<pre><code><ul id=\"FrontRack\" style=\"\n background-image: url({%= data.get('racks').at(0).get('imageUrls')[0] %});\n height:{%= data.get('racks').at(0).get('pixelHeight') %}px;\n width:{%= data.get('racks').at(0).get('pixelWidth') %}px;\n\">\n <li>Hello World</li>\n</ul>\n</code></pre>\n\n<p>Only accesses data under <code>data.get('racks').at(0)</code>, so that is what you should provide to the template ( as say, <code>data</code> ), then your template becomes</p>\n\n<pre><code><ul id=\"FrontRack\" style=\"\n background-image: url({%= data.get('imageUrls')[0] %});\n height:{%= data.get('pixelHeight') %}px;\n width:{%= data.get('pixelWidth') %}px; \">\n <li>Hello World</li>\n</ul>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T14:15:17.497",
"Id": "79601",
"Score": "0",
"body": "@SeanAnderson, glad to see you are still around and involved in CR. Thanks for accepting this answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T15:27:15.773",
"Id": "45514",
"ParentId": "29657",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "45514",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T17:54:43.407",
"Id": "29657",
"Score": "12",
"Tags": [
"javascript",
"css",
"template",
"backbone.js",
"underscore.js"
],
"Title": "Unordered list element via templating"
}
|
29657
|
<p>This function's job is to replace several text smilies, e.g. <code>:D</code>, <code>:)</code>, <code>:love</code> with the appropriate smiley image.
In my opinion my code has several issues, yet the main problem is that <em>a lot</em> of quite similar regexes are created dynamically: one for each different smilie replaced.
As you might expect, replacing smilies in a text is a job done kindly often, so this is indeed code that is executed a lot of time, therefore I think optimizing that makes sense.</p>
<p>Well, why didn't I just call <code>text.replace()</code>?
<strong>I don't want the smilies to be replaced if they are enclosed by backticks: `</strong></p>
<pre><code>var replaceTextSmilies = function() {
var smiliesShortcut = {};
smiliesShortcut[':)'] = 'smile.png';
/* adding much more */
var smiliesWordy = {};
smiliesWordy[':angry'] = 'angry.png';
/* adding much more */
function escapeRegExp(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
return function(text) {
Object.keys(smiliesWordy).forEach(function(entry) {
var image = '<img src="img/smilies/' + smiliesWordy[entry] + '"/>';
if(text.indexOf(entry) !== -1) {
var regex = new RegExp('('+ escapeRegExp(entry) +')(?=(?:(?:[^`]*`){2})*[^`]*$)', 'g');
text = text.replace(regex, image);
}
});
Object.keys(smiliesShortcut).forEach(function(entry) {
var image = '<img src="img/smilies/' + smiliesShortcut[entry] + '"/>';
if(text.indexOf(entry) !== -1) {
var regex = new RegExp('('+ escapeRegExp(entry) +')(?=(?:(?:[^`]*`){2})*[^`]*$)', 'g');
text = text.replace(regex, image);
}
});
return text;
};
}();
</code></pre>
|
[] |
[
{
"body": "<p>You can store the regex as part of the smily metadata.</p>\n\n<pre><code>var replaceTextSmilies = function() {\n var smiliesShortcut = {};\n smiliesShortcut[':)'] = {\n img : 'smile.png'\n };\n /* adding much more */\n\n var smiliesWordy = {};\n smiliesWordy[':angry'] = {\n img : 'angry.png'\n };\n /* adding much more */\n\n addRegex(smiliesShortcut);\n addRegex(smiliesWordy);\n\n function escapeRegExp(str) {\n return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, \"\\\\$1\");\n }\n\n function addRegex(smilies) {\n Object.keys(smilies).forEach(function(smily) {\n smilies[smily].regex = new RegExp('(' + escapeRegExp(smily) + ')(?=(?:(?:[^`]*`){2})*[^`]*$)', 'g');\n });\n }\n\n function replace(text, smilies) {\n Object.keys(smilies).forEach(function(entry) {\n var image = '<img src=\"img/smilies/' + smilies[entry].img + '\"/>';\n\n if (text.indexOf(entry) !== -1) {\n text = text.replace(smilies[entry].regex, image);\n }\n });\n return text;\n }\n\n return function(text) {\n text = replace(text, smiliesWordy);\n text = replace(text, smiliesShortcut);\n return text;\n };\n}();\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/arunpjohny/DVme2/\" rel=\"nofollow\">Fiddle</a></p>\n\n<p>Note: You can make it even better if you can manually create the regex and assign them instead of using <code>addRegex()</code> like</p>\n\n<pre><code> smiliesShortcut[':)'] = {\n img : 'smile.png',\n regex: /<the regex>/\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T11:09:28.620",
"Id": "46953",
"Score": "0",
"body": "Thank you, any other comments on the code? :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T03:26:12.763",
"Id": "29673",
"ParentId": "29660",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T18:13:08.277",
"Id": "29660",
"Score": "0",
"Tags": [
"javascript",
"optimization",
"regex"
],
"Title": "Avoiding dynamic RegEx creation in JavaScript"
}
|
29660
|
<p>So we have a RESTful webservice that implements CRUD operations for a model, like this one:</p>
<pre><code>class MyModel {
private long id;
private String name;
// other fields
private boolean completed;
private boolean active;
// getter and setters
}
</code></pre>
<p>In this webservice there is also a path like <code>/service/{id}/complete</code> that updates just the field <code>completed</code> to true. This indicates a final step for the creation.</p>
<p>The <em>save</em> and the <em>complete</em> operation are pretty simple and similar (they both end up calling a <code>saveOrUpdate</code> ). Where they differ is the validation. The <em>complete</em> validation is stricter.</p>
<p>The one before me declared an interface:</p>
<pre><code>interface Validator<T> {
void validate(T t);
}
</code></pre>
<p>And then to check that all mandatory fields where there before setting the <code>complete</code> attribute to <code>true</code> we have something like (writing in pseudocode):</p>
<pre><code>MandatoryFieldsValidator implements Validator<MyModel> {
list = {'id', 'active'}
public void validate(MyModel model) {
foreach(element in list) {
if(myModel.get(element) is null) throw ValidationException(element + " is mandatory");
}
}
}
</code></pre>
<p>So then I needed another type of validator and started doing something like this because I needed specific controls over the <code>name</code> field:</p>
<pre><code>NameValidator implements Validator<MyModel> {
public void validate(MyModel model) {
if(model.name is null or empty)
throw ValidationException(element + " is mandatory");
if(model.name.startswith("something"))
throw ValidationException("something not valid prefix");
if(model.name.length > 10)
throw ValidationException("too long");
}
}
</code></pre>
<p>The controller had an attribute of type Validator that instantiated a <code>MandatoryFieldsValidator</code> so I added another attribute of the same type instantiating a <code>NameValidator</code>.</p>
<p>Now what I don't like about this:</p>
<ul>
<li>The fact that I need to add a new attribute to the class as soon as I have a new validator to use;</li>
<li>The fact that I'm repeating checks in different validators because even if <code>name</code> is not included in the <code>MandatoryFieldValidator</code> I'm applying the same logic inside <code>NameValidator</code> (<em>is null or empty</em>);</li>
<li>I will also add a new type of model and a <code>MandatoryFieldValidator<NewModel></code> with the same type of control logic is a non-sense.</li>
</ul>
<p>Can you give me some advice? I'm looking into a general pattern to organize this kind of validation but I'm using Java so if you have some Java specific solution is ok.</p>
|
[] |
[
{
"body": "<p>You could use the composite pattern to create a tree of <code>Validator</code> instances. Each node would validate its with its own <code>Validator</code> before delegating to children (if any). This way children don't need to check again what was already validated in parent nodes</p>\n\n<pre><code>public class ValidatorTree<T> implements Validator<T> {\n\n private Validator<? super T> node;\n private List<Validator<? super T>> children;\n\n // constructor etc. snipped for brevity\n\n @Override\n public void validate(T t) {\n node.validate(t);\n for (Validator<? super T> child : children) {\n child.validate(t);\n }\n }\n}\n</code></pre>\n\n<p>This way you can bundle several validators into one (so only one root validator needs to be referenced). And validation order is guaranteed, so no need to perform duplicate checks.</p>\n\n<p><strong>Edit</strong> <em>(in response to comment)</em></p>\n\n<p>A Validator for Model1 may very well be different from a Validator for Model2. If Validators are to be reused for different models you can define interfaces that define the common parts to be validated.</p>\n\n<p>e.g.</p>\n\n<pre><code>public interface Named {\n\n String getName();\n}\n</code></pre>\n\n<p>and a matching NameNotNullValidator : </p>\n\n<pre><code>public class NameNotNullValidator implements Validator<Named> {\n @Override\n public void validate(Named named) {\n if (named.getName() == null) {\n throw new ValidationException(/* appropriate message here */);\n }\n }\n}\n</code></pre>\n\n<p>And this Validator can be reused in validator trees for all models that implement <code>Named</code>. Note that I adapted the generics in <code>ValidatorTree</code> for this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:26:31.657",
"Id": "46988",
"Score": "0",
"body": "Ok but that doesn't resolve my problem when it comes to <T>. With this solution I still need, for example, two mandatoryFieldValidators one for each <T> I introduce. I'm probably missing something in the reasoning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:43:53.927",
"Id": "47009",
"Score": "0",
"body": "Edited response"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T07:21:12.977",
"Id": "47028",
"Score": "0",
"body": "Ok. Question: if in a model I have two field that needs a \"notNullValidator\" what should I do? Right now I see two solution: add a method getOtherField in the Named interface or add a new interface OtherField with method getOtherField and then I have to add a second Validator<OtherField> with the same logic of NameNotNullValidator. Is my reasoning wrong? Because in the first case I'll have an Interface with the same field of the model, in the second case I'll have logic replicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T09:29:18.277",
"Id": "47035",
"Score": "0",
"body": "I thought the Validators worked on the model, not on the fields. i.e. T is a model class. Of course these can use reusable field validating components, I'm just not sure whether they have to implement the `Validator` interface."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:53:33.580",
"Id": "29689",
"ParentId": "29662",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29689",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T19:25:59.463",
"Id": "29662",
"Score": "2",
"Tags": [
"java",
"validation"
],
"Title": "Different types of model validation"
}
|
29662
|
<p>I have such a method that performs a long query search against some data.</p>
<pre><code>Task<List<SearchResult>> Search(string query){ ... }
</code></pre>
<p>I have tried various way to create an IObservable form of it but failed. At the end after some google help I wrote such a method.</p>
<pre><code>private IObservable<SearchResult[]> Search(string query)
{
return Observable.Create((IObserver<SearchResult[]> observer)=>
{
List<SearchResult> result = new List<SearchResult>();
foreach (TestsGroupMeta group in Engine.Groups)
{
string name = group.ToString();
if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
{
result.Add(new SearchResult{ Name = name, Type = "Group"});
}
foreach (TestMethodMeta method in group.Methods)
{
name = method.ToString();
if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
{
result.Add(new SearchResult {Name = name, Type = "Method"});
}
}
}
observer.OnNext(result.ToArray());
observer.OnCompleted();
return () => {};
});
}
</code></pre>
<p>Is such a method correctly written? If not, what would be correct?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-06T01:31:44.427",
"Id": "118703",
"Score": "0",
"body": "Why do you want to use IObservable<T> rather than Task<T>?"
}
] |
[
{
"body": "<p>using the <code>TaskObservableExtensions</code> from <code>System.Reactive.Threading.Tasks</code> (in the <a href=\"https://www.nuget.org/packages/Rx-Linq/\" rel=\"nofollow\" title=\"NuGet\">Rx Linq DLL</a>) it is easy:</p>\n\n<pre><code>IObservable<List<SearchResult>> observable = Search(queryString).ToObservable()\n</code></pre>\n\n<p>I'd consider <a href=\"https://github.com/Reactive-Extensions/Rx.NET/blob/master/Rx.NET/Source/System.Reactive.Linq/Reactive/Threading/Tasks/TaskObservableExtensions.cs#L76\" rel=\"nofollow\" title=\"GitHub\">the code there</a> to be \"correctly written\" (I'm in no way linked to the code nor its authors.)</p>\n\n<p>If you want to rewrite your <code>Search</code> method to work directly with <code>Observable</code>s I'd recommend using their full power:</p>\n\n<pre><code>private IObservable<SearchResult> Search(string query)\n {\n return Observable.Create<SearchResult>(\n (observer, cancellationToken) => Task.Factory.StartNew(\n () =>\n {\n foreach (TestsGroupMeta group in Engine.Groups)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n break;\n }\n\n string name = group.ToString();\n if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)\n {\n observer.OnNext(new SearchResult { Name = name, Type = \"Group\" });\n }\n\n foreach (TestMethodMeta method in group.Methods)\n {\n name = method.ToString();\n if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)\n {\n observer.OnNext(new SearchResult { Name = name, Type = \"Method\" });\n }\n }\n }\n\n observer.OnCompleted();\n },\n cancellationToken,\n TaskCreationOptions.LongRunning,\n TaskScheduler.Default));\n }\n</code></pre>\n\n<p>An observer is now able to process <code>SearchResults</code> as soon as they are found (as opposed to wait for the completion of the computation yielding all results at once) and can unsubscribe anytime which in turn will cause a cancellation of the result computation. If some function still needs all <code>SearchResults</code>at once there's always <code>Observable.ToEnumerable</code> and friends. In addition, possible parallelization is now obvious (e.g. using <a href=\"https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach(v=vs.110).aspx\" rel=\"nofollow\">Parallel.ForEach</a>) but still not trivial (hinted at by the inclusion of TaskCreationOptions and TaskScheduler, sensible options for Parallel.ForEach not included). Also clients must then be prepared to consume 'out-of-order' search results.</p>\n\n<p>Potential further improvements:</p>\n\n<ul>\n<li>check for cancellation at more / more appropriate places</li>\n<li>split Task/Observable logic and searching</li>\n<li>handle (now asynchronous) errors (e.g. by <code>try</code>ing the <code>foreach</code> and calling <code>observer.OnError</code>)</li>\n<li>specify culture for<code>ToString</code></li>\n<li>employ a more 'functional' style by leveraging <code>SelectMany</code> (suits my personal taste)</li>\n</ul>\n\n<p>Otherwise you could at least use <code>Observable.Start</code> which gets rid of the otherwise unused observer:</p>\n\n<pre><code>private IObservable<SearchResult[]> Search(string query)\n{\n return Observable.Start(() =>\n {\n List<SearchResult> result = new List<SearchResult>();\n foreach (TestsGroupMeta group in Engine.Groups)\n {\n string name = group.ToString();\n if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)\n {\n result.Add(new SearchResult { Name = name, Type = \"Group\" });\n }\n\n foreach (TestMethodMeta method in group.Methods)\n {\n name = method.ToString();\n if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)\n {\n result.Add(new SearchResult { Name = name, Type = \"Method\" });\n }\n }\n }\n return result;\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-24T12:26:22.670",
"Id": "78490",
"ParentId": "29663",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T20:24:31.927",
"Id": "29663",
"Score": "5",
"Tags": [
"c#",
".net",
"system.reactive"
],
"Title": "Create an IObservable from a method"
}
|
29663
|
<p>How can I refactor this code to avoid switch-cases? Is there a way of changing commands without adding new case and make it dynamically...I want the solution not to depend on the amount of cases. For example, if I have 1000 commands..I should obviously write them all as cases?
I hope my problem is clear.</p>
<pre><code>static void Main(string[] args)
{
ConsoleHelp ch1 = new ConsoleHelp();
Plus pl = new Plus();
Minus mn = new Minus();
Divide dv = new Divide();
Multiply mlt = new Multiply();
Sinus sin = new Sinus();
Tangent tan = new Tangent();
Square sq = new Square();
Degree dg = new Degree();
Percent pr = new Percent();
while (true)
{
Console.Write("command> ");
string com = Console.ReadLine();
if (com != null)
{
switch (com.ToLower())
{
case "?":
ch1.Helpper();
break;
case "plus":
pl.Sum();
break;
case "minus":
mn.Minusvalue();
break;
case "divide":
dv.Dividevalue();
break;
case "multiply":
mlt.Multvalue();
break;
case "sinus":
sin.Sinusvalue();
break;
case "tangent":
tan.Tangentvalue();
break;
case "square":
sq.Squarevalue();
break;
case "degree":
dg.Degvalue();
break;
case "percent":
pr.Pervalue();
break;
case "c":
Environment.Exit(0);
break;
default:
Console.WriteLine("The command is not supported. Enter one of the valid commands.");
break;
}
}
}
Console.ReadLine();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T20:40:25.417",
"Id": "46920",
"Score": "4",
"body": "Not sure what the classes do but you could register all the functions in a dictionary<string, object> and simply call _action[com.ToLower()].Execute() (Make all your actions implement an interface that has Execute method)."
}
] |
[
{
"body": "<p>Here you go:</p>\n\n<pre><code>static void Main(string[] args)\n{\n ConsoleHelp ch1 = new ConsoleHelp();\n Plus pl = new Plus();\n Minus mn = new Minus();\n Divide dv = new Divide();\n Multiply mlt = new Multiply();\n Sinus sin = new Sinus();\n Tangent tan = new Tangent();\n Square sq = new Square();\n Degree dg = new Degree();\n Percent pr = new Percent();\n System.Collections.Generic.IDictionary<string, Action> actions = new System.Collections.Generic.Dictionary<string, Action>(StringComparer.OrdinalIgnoreCase)\n {\n { \"?\", ch1.Helpper },\n { \"plus\", pl.Sum },\n { \"minus\", mn.Minusvalue },\n { \"divide\", dv.Dividevalue },\n { \"multiply\", mlt.Multvalue },\n { \"sinus\", sin.Sinusvalue },\n { \"tangent\", tan.Tangentvalue },\n { \"square\", sq.Squarevalue },\n { \"degree\", dg.Degvalue },\n { \"percent\", pr.Pervalue },\n { \"c\", Exit },\n };\n\n while (true)\n {\n Console.Write(\"command> \");\n string com = Console.ReadLine();\n if (com != null)\n {\n Action action;\n\n if (actions.TryGetValue(com, out action))\n {\n action.Invoke();\n }\n else\n {\n Console.WriteLine(\"The command is not supported. Enter one of the valid commands.\");\n break;\n }\n }\n }\n Console.ReadLine();\n}\n\nstatic void Exit()\n{\n Environment.Exit(0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T21:35:23.140",
"Id": "46924",
"Score": "0",
"body": "This being a strict answer to your question - removing the `switch` - there are much better, more object-oriented ways to accomplish what I think you want. Seeing the operations classes (such as `Plus`) would help to refactor into something much more maintainable and extensible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T22:42:46.660",
"Id": "46927",
"Score": "0",
"body": "You could simplify this even more by inlining all those locals: `{ \"?\", new ConsoleHelp().Helpper }, { \"plus\", new Plus().Sum }, …`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T04:28:07.053",
"Id": "46943",
"Score": "1",
"body": "This answer is bad prctice, imho. It does not really solve the problem. Instead of writing 1000 `case` statements you will hardcode a 1000-element `Dictionary`, which is essentially the same thing (and the same source of errors, typos, etc). When it comes to classes, it is almost always possible to extract a common interface/baseclass to avoid, and that is what should be used (as already suggested by Josh)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:41:43.087",
"Id": "46962",
"Score": "1",
"body": "Hence, my very first comment."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T21:31:44.033",
"Id": "29665",
"ParentId": "29664",
"Score": "1"
}
},
{
"body": "<p>You can create your own Attribute to decorate all of your classes (e.g., Plus, ConsoleHelp, Minus, Divide, and even Exit). In the sample below, the attribute is called <code>SystemCommandAttribute</code>. It would require to specify what the name of the command would be as a constructor parameter (what the user would have to type on the command line). </p>\n\n<p>The next step would be to have each of your command classes implement the same interface. In the example code I used the name <code>ISystemCommand</code>. That interface should have a single method: <code>Execute()</code>. That way we know what to call when we want to invoke the command.</p>\n\n<p>Then you can use reflection to search for all classes that have that attribute and load them into a dictionary of <code>string</code> to <code>ISystemCommand</code>. The <code>GetCommandsFromAssemblies()</code> method handles instantiating each instance of <code>ISystemCommand</code> for you. </p>\n\n<p>From there you can use the dictionary instead of the switch statement. </p>\n\n<pre><code>public class Program\n{\n static void Main(string[] args)\n {\n Dictionary<string, ISystemCommand> commandToType = GetCommandsFromAssemblies();\n RunCommandLoop(commandToType);\n }\n\n /// <summary>\n /// Loop over all types currently loaded in the AppDomain looking for ISystemCommand\n /// </summary>\n /// <returns>A dictionary from command name to instance of command</returns>\n private static Dictionary<string, ISystemCommand> GetCommandsFromAssemblies()\n {\n var typesWithMyAttribute =\n from a in AppDomain.CurrentDomain.GetAssemblies()\n from t in a.GetTypes()\n let attributes = t.GetCustomAttributes(typeof(SystemCommandAttribute), true)\n where attributes != null && attributes.Length > 0\n select new\n {\n Instance = (ISystemCommand)Activator.CreateInstance(t),\n CommandName = attributes.Cast<SystemCommandAttribute>().Single().CommandName\n };\n\n Dictionary<string, ISystemCommand> commandToType = typesWithMyAttribute.ToDictionary(t => t.CommandName, t => t.Instance);\n\n return commandToType;\n }\n\n private static void RunCommandLoop(Dictionary<string, ISystemCommand> actions)\n {\n while (true)\n {\n Console.Write(\"command> \");\n string com = Console.ReadLine();\n if (com != null)\n {\n ISystemCommand action;\n\n if (actions.TryGetValue(com, out action))\n {\n action.Execute();\n }\n else\n {\n Console.WriteLine(\"The command is not supported. Enter one of the valid commands.\");\n break;\n }\n }\n }\n Console.ReadLine();\n }\n}\n\npublic interface ISystemCommand\n{\n void Execute();\n}\n\npublic class SystemCommandAttribute : Attribute\n{\n public SystemCommandAttribute(string commandName)\n {\n CommandName = commandName;\n }\n\n public string CommandName { get; set; }\n}\n\n[SystemCommand(\"plus\")]\npublic class Plus : ISystemCommand\n{\n public void Execute()\n {\n Sum();\n }\n\n private void Sum()\n {\n // your existing Sum logic here\n Console.WriteLine(\"Sum called\");\n }\n}\n\n\n[SystemCommand(\"?\")]\npublic class ConsoleHelp : ISystemCommand\n{\n public void Execute()\n {\n Helper();\n }\n\n private void Helper()\n {\n // your existing Helper logic here\n Console.WriteLine(\"Helper called\");\n }\n}\n\n[SystemCommand(\"c\")]\npublic class ExitCommand : ISystemCommand\n{\n public void Execute()\n {\n Environment.Exit(0);\n }\n}\n</code></pre>\n\n<p>To add a new command in the future, all you would need to do would be to </p>\n\n<ol>\n<li>create your command class</li>\n<li>Inherit from ISystmeCommand</li>\n<li>Add the SystmCommandAttribute</li>\n</ol>\n\n<p>Your main program would not need to change at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T22:47:29.917",
"Id": "46928",
"Score": "1",
"body": "Instead of `First()`, I prefer to use `Single()` most of the time, to make sure accidental duplicate errors are caught early. And using similar logic, it's better to use `Cast()` instead of `OfType()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T00:46:29.287",
"Id": "46937",
"Score": "0",
"body": "good point @svick. I've updated the sample to use `Single()` and `Cast()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T04:38:26.993",
"Id": "46944",
"Score": "1",
"body": "There is also an important restriction: command classes should implement a default constructor (probably there should be a custom exception thrown?). This, ofc, can be avoided by using a dependency injection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:20:54.107",
"Id": "46959",
"Score": "2",
"body": "Also, in case it's not obvious, this suggestion is an implementation of the Command Pattern - http://www.dofactory.com/Patterns/PatternCommand.aspx"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T22:21:29.213",
"Id": "29667",
"ParentId": "29664",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T20:34:28.423",
"Id": "29664",
"Score": "5",
"Tags": [
"c#"
],
"Title": "how to avoid switch-case"
}
|
29664
|
<p>I was working through getting myself past the creation of a generic method, that converts a <code>List<T></code> or <code>List<List<T>></code>, to <code>T[]</code> or <code>T[][]</code> respectively. Well, let's just consider a maximum dimension of 2 for now.</p>
<h2><code>List<T></code> to <code>T[]</code> is quite straight-forward:</h2>
<pre><code>public static <T> T[] listToArray(List<T> list, Class<T> clazz) {
/**** Null Checks removed for brevity ****/
T[] arr = (T[]) Array.newInstance(clazz, list.size());
for (int i = 0; i < list.size(); ++i) {
arr[i] = list.get(i);
}
return arr;
}
</code></pre>
<p>Now I can call this method as:</p>
<pre><code>List<String> list = new ArrayList<>(Arrays.asList("rohit", "jain"));
String[] arr = listToArray(list, String.class);
</code></pre>
<hr />
<h2><code>List<List<T>></code> to <code>T[][]</code> is what gives problems:</h2>
<p>Now, here's the problem. Consider the code:</p>
<pre><code>public static <T> T[][] multiListToArray(List<List<T>> listOfList, Class<T> clazz) {
// Here I don't know what size to give for 2<sup>nd</sup> dimension
// T[][] arr = (T[][]) Array.newInstance(clazz, listOfList.size(), ?);
// So, I tried this. But this of course is not type safe
// T[][] arr = (T[][]) new Object[listOfList.size()][];
/* Only alternative I had was to iterate over the listOfList to get the
maximum out of all the column sizes, which I can give as 2<sup>nd</sup>
dimension later on.
*/
int maxCol = 0;
for (List<T> row: listOfList) {
if (row.size() > maxCol) {
maxCol = row.size();
}
}
// Now I can pass `maxCol` as 2<sup>nd</sup> dimension
T[][] arr = (T[][]) Array.newInstance(clazz, listOfList.size(), maxCol);
for (int i = 0; i < listOfList.size(); ++i) {
List<T> row = listOfList.get(i);
arr[i] = listOfList.get(i).toArray((T[])Array.newInstance(clazz, row.size()));
}
return arr;
}
</code></pre>
<p>Now, this is what I want to avoid - double iteration of <code>List<List<T>></code> to be able to create the array. Is there any possibility?</p>
|
[] |
[
{
"body": "<p>Since you are creating new instance of arrays in your second loop, you don't need to know the size of the \"inner list\". Your \"outer array\" has to be as big as the \"outer list\". In a second phase, you instanciate the \"inner arrays\".</p>\n\n<p>There's a simple way do this:</p>\n\n<pre><code>public <T> T[][] multiListToArray(final List<List<T>> listOfList, final Class<T> classz) {\n final T[][] array = (T[][]) Array.newInstance(classz, listOfList.size(), 0);\n\n for (int i = 0; i < listOfList.size(); i++) {\n array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));\n }\n\n return array;\n}\n</code></pre>\n\n<p>More over, as you can see in the code above, you can provide a 0-length array to <code>toArray(T[])</code> method.</p>\n\n<p>This piece of code:</p>\n\n<pre><code>final List<List<String>> test = new ArrayList<List<String>>();\ntest.add(new ArrayList<String>(Arrays.asList(\"a\", \"b\", \"c\")));\ntest.add(new ArrayList<String>(Arrays.asList(\"d\", \"e\", \"f\", \"g\")));\ntest.add(new ArrayList<String>(Arrays.asList(\"h\", \"i\")));\n\nfor (final String[] innerArray : multiListToArray(test, String.class)) {\n System.out.println(Arrays.toString(innerArray));\n}\n</code></pre>\n\n<p>Will produce this output:</p>\n\n<blockquote>\n <p>[a, b, c]<br />\n [d, e, f, g]<br />\n [h, i]</p>\n</blockquote>\n\n<p><strong>EDIT:</strong> There is <a href=\"http://ideone.com/9dxEId\" rel=\"nofollow\">an Ideone example</a>.</p>\n\n<p><strong>EDIT 2:</strong> Code and Ideone updated to comply with OP needs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:35:35.483",
"Id": "46964",
"Score": "0",
"body": "Ah! Thanks for the 1st part. Yeah, I missed that point, that I can give 0 size for column initially. And regarding giving `0` size for array inside `for` loop, I would prefer to pass the size of the list, so that array don't need to be re-created in the method. Anyways thanks for your answer. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:52:50.413",
"Id": "46965",
"Score": "0",
"body": "So you could replace `array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, 0));` with `array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));` ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:20:52.853",
"Id": "29681",
"ParentId": "29666",
"Score": "4"
}
},
{
"body": "<p>\"Is there any possibility?\"</p>\n\n<p>Seems to be the <em>only</em> possibility...</p>\n\n<pre><code>/// A generic method to convert a list of lists to a two dimensional array\n//\n<T> T[][] makeArray ( List<List<T>> list ) { int i = 0;\n T[][] makeArray = (T[][]) Array.newInstance(list.get(0).get(0).getClass(),list.size(),0);\n for( List<T> tt : list )\n makeArray[i++] = (T[]) tt.toArray();\n return makeArray;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T10:24:32.430",
"Id": "29834",
"ParentId": "29666",
"Score": "0"
}
},
{
"body": "<p>you could always reuse your existing listToArrayMethod to solve your problem</p>\n\n<pre><code>public static <T> T[][] multiListToArray(List<List<T>> listOfList, Class<T> clazz) {\n\n //unsure if this line will work but it should\n Class<List<T>> listClass = (Class<List<T>>) listOfList.get(0).getClass();\n\n List<T>[] arrayOfLists = listToArray(listOfList, listClass);\n T[][] array = (T[][]) Array.newInstance(clazz, arrayOfLists.length);\n for (int i = 0; i < arrayOfLists.length; i++) {\n List<T> arrayOfList = arrayOfLists[i];\n array[i] = listToArray(arrayOfList, clazz);\n }\n return array;\n}\n</code></pre>\n\n<p>basically this works because we just have a list of list so we convert that to an array of list then we convert each of those to an array and place those inside our new array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:28:53.310",
"Id": "29869",
"ParentId": "29666",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29681",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T21:45:07.453",
"Id": "29666",
"Score": "3",
"Tags": [
"java",
"array",
"generics"
],
"Title": "Better way to write generic method to convert List<List<T>> to T[][]"
}
|
29666
|
<p>I am doing some console test program, and I have some normal math operations. Example of part of my code:</p>
<pre><code>if (flagMultiplyDivide.Equals(true))
{
if (currentOperator.Equals('*'))
{
currentNumberDouble = multiplyNumbers(currentNumberString, temporaryNumberString);
if (operatorOnHold.Equals('+'))
{
total += currentNumberDouble;
}
else if (operatorOnHold.Equals('-'))
{
total -= currentNumberDouble;
}
else
{
total = currentNumberDouble;
}
flagMultiplyDivide = false;
}
else if (currentOperator.Equals('/'))
{
currentNumberDouble = divideNumbers(temporaryNumberString, currentNumberString);
if (operatorOnHold.Equals('+'))
{
total += currentNumberDouble;
}
else if (operatorOnHold.Equals('-'))
{
total -= currentNumberDouble;
}
else
{
total = currentNumberDouble;
}
}
}
else if (currentOperator.Equals('+'))
{
if (!numberOnHold.Equals(""))
{
total += Convert.ToDouble(currentNumberString) + Convert.ToDouble(numberOnHold);
}
else
{
total += Convert.ToDouble(currentNumberString);
}
}
else if (currentOperator.Equals('-'))
{
if (!numberOnHold.Equals(""))
{
total -= Convert.ToDouble(currentNumberString) - Convert.ToDouble(numberOnHold);
}
else
{
total -= Convert.ToDouble(currentNumberString);
}
}
return total;
</code></pre>
<p>Since it is logical program, I have a lot of conditional statements, and it is easy to lose in code. What is the best practice to code conditional statements in my case? How would you improve my part of code?</p>
<p>What am I doing wrong? I never have a problem to make a working code, but I really want to learn best practice, really. That's why I am here.</p>
|
[] |
[
{
"body": "<ol>\n<li>Extract repeated code into separate methods.</li>\n<li>Use <code>==</code> to compare values, C# is not Java, most of the time, you don't need <code>Equals()</code>. And in the case of <code>bool</code>s, you don't need to compare them at all.</li>\n<li>Don't forget to handle invalid input.</li>\n<li>It's probably better to use <code>string.Empty</code> instead of <code>\"\"</code>, to make it clear that you didn't just forget to fill the right value in and you really meant the empty string.</li>\n<li>Consider <em>not</em> using braces everywhere. It can make your code more readable.</li>\n</ol>\n\n<p>(This code assumes all variables are fields; if that's not suitable to you, you will need to add some parameters and return values to the methods.)</p>\n\n<pre><code>void MultiplyOrDidide(bool multiply)\n{\n if (multiply)\n currentNumberDouble = multiplyNumbers(currentNumberString, temporaryNumberString);\n else\n currentNumberDouble = divideNumbers(temporaryNumberString, currentNumberString);\n\n if (operatorOnHold == '+')\n total += currentNumberDouble;\n else if (operatorOnHold == '-')\n total -= currentNumberDouble;\n else\n total = currentNumberDouble;\n\n flagMultiplyDivide = false; \n}\n\nvoid AddOrSubtract(bool add)\n{\n double current = Convert.ToDouble(currentNumberString);\n double onHold = 0;\n if (numberOnHold != string.Empty)\n onHold = Convert.ToDouble(numberOnHold);\n\n if (add)\n total += current + onHold;\n else\n total -= current - onHold;\n}\n\n…\n\nif (flagMultiplyDivide)\n{\n if (currentOperator == '*')\n MultiplyOrDidide(multiply: true);\n else if (currentOperator == '/')\n MultiplyOrDidide(multiply: false);\n else\n throw new InvalidOperationException();\n}\nelse if (currentOperator == '+')\n{\n AddOrSubtract(add: true);\n}\nelse if (currentOperator == '-')\n{\n AddOrSubtract(add: false);\n}\nelse\n{\n throw new InvalidOperationException();\n}\n\nreturn total;\n</code></pre>\n\n<p>Also, the code around <code>-</code> (and <code>+</code>) seems suspicious to me. Shouldn't you check <code>operatorOnHold</code> there too?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T02:55:52.067",
"Id": "46938",
"Score": "0",
"body": "Always putting braces around if body reduces the probability of a bug, or am I brainwashed? You may have found a \"local maximum\", but I would ask a question - is there a better overall approach? Evaluating arithmetic expressions seems so short and easy in LISP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T04:50:57.397",
"Id": "46945",
"Score": "1",
"body": "5. In my company, for example, one of the code styling rules forbids you from _not_ using braces after `if` statements except for cases when it is followed by `throw` or `return` (ironically for exactly the same reason - it improves readbility). And i agree with this policy. So, i guess, its a matter of taste."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T08:01:13.543",
"Id": "46948",
"Score": "0",
"body": "@Nik I really don't think adding unnecessary braces improves readability. It does make it harder to write certain kind of bugs, but *I think* those are not common enough to justify the decrease in readability. But that's certainly debatable, which is why I said “consider” and not “do it”."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T08:04:31.650",
"Id": "46949",
"Score": "0",
"body": "@Leonid I think that probability is too low to justify the decrease in readability. Especially if there are not complete beginners in C-like languages on your team and you use good IDE that automatically formats your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T08:08:46.857",
"Id": "46950",
"Score": "0",
"body": "@Leonid If you're talking about something like [`(eval (read-from-string s))`](http://stackoverflow.com/a/7612090/41071), then 1. that works only when the expression is already a LISP expression and you want to evaluate it according to the rules of LISP 2. is probably a huge security hole. If you really wanted to do something similar in .Net, you could use something like IronPython or (when it's released) Roslyn C# scripting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T11:58:34.680",
"Id": "46956",
"Score": "0",
"body": "The debate on whether or not to use braces everywhere is older than most of us and doesn't have a right answer. My personal policy is to use braces any time the entire statement (including condition and body) can't be (legibly) written on a single line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:40:04.613",
"Id": "46978",
"Score": "1",
"body": "+1. Answers the question; and does error trapping!. Svick is right about braces causing significant clutter in this example. Alternatively we could just keep stuff on the same line: `if (add) { total += current + onHold; }`. It is, in the final analysis, a judgement call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T12:34:28.360",
"Id": "47138",
"Score": "0",
"body": "Thanks for an explanation. I thought .equals() is more \"safe\" as we used it in Java in school, as you mentioned. \"Also, the code around - (and +) seems suspicious to me. Shouldn't you check operatorOnHold there too?\" Operator on hold is actually the one I put it if operation is + or -, because I have to respect operation order rule(multiply/divide). In case next operator is * or / i have to save operatoronhold(+,-) to use it after * or / calculation. My logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:17:37.387",
"Id": "47535",
"Score": "0",
"body": "Want to ask, did you just extracted those methods, assuming variables are class's properties or fields? like total?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T17:06:17.823",
"Id": "47546",
"Score": "0",
"body": "@JohnMathilda Yeah, I did, because that made the code simplest. And like I said, if that's not your case, you will need to modify the code."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T00:06:55.850",
"Id": "29669",
"ParentId": "29668",
"Score": "6"
}
},
{
"body": "<p>I see two main issues with your code:</p>\n\n<ol>\n<li><p>You are writing what looks like a simple expression evaluator. This is something what most will call <em>reinventing the wheel</em> (i.e. a waste of time). There are multiple libraries (both managed and unmanaged) which do just that. <a href=\"http://flee.codeplex.com/\">Flee</a> beeing one such example (i used it successfully in the past).</p></li>\n<li><p>Even if you do need to write something like that for some reason (studying?), i think your approach is wrong. Imho, you have one mess of a code because you are not separating parsing from actual evaluation. What you should do is you should first parse the expression into binary tree (represented by <code>Expression</code> class or your own binary tree implementation) getting rid of all the strings in your code. And the when you are done - you should evaluate this tree. There is an awesome article on <a href=\"http://www.codeproject.com/Articles/18880/State-of-the-Art-Expression-Evaluation\">CodeProject</a> on this subject, which is most likely an overkill in your case, but still a good source of design ideas for your application.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T12:30:50.563",
"Id": "47137",
"Score": "0",
"body": "I mustn't use the library, I had to write my own thing. This second example(ANTLR) you pasted me, is really overkill to understand for my brains at the moment. But it is cool thing to know. As I said I am kind of still student, and I am not that experienced in code design. I deliver working application, but I still have a lot to learn in terms of design. I found out this website that i really like and will learn from it: sourcemaking.com"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T05:14:11.930",
"Id": "29675",
"ParentId": "29668",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T22:58:58.663",
"Id": "29668",
"Score": "5",
"Tags": [
"c#"
],
"Title": "What are best practices for writing conditional statements?"
}
|
29668
|
<p>I am really just looking to make sure I am not making any weird mistakes that could hurt me in the long run or if something seems odd in the way I imagine it to work. This code does work for the way I use it and may lack other more advanced things that I may use in the future but have not implemented yet. I left in my phpdoc code to maybe make some sense of weird things. Any feedback is appreciated. </p>
<p>Note: I am constantly reading up on things and try to cover everything in each of the stack sites but I might have overlooked some very basic resources due to be newer to the stack family.</p>
<pre><code>/**
* Class Main Mysql Database
*/
class mydb {
/**
* Connect to DB
*/
public function __construct() {
// Connect to Database
$this->mydb = new mysqli('host', 'database', 'user', 'pass');
if ($this->mydb->connect_errno) { // Error on connection failure
echo "Failed to connect to MySQL in Construct: (" . $this->mydb->connect_errno . ") " . $this->mydb->connect_error;
}
} /** End construct */
/**
* Choose items from the database (SELECT Statement with WHERE equals and like options)
* Designed to be slim and rely more on PHP than mysql for result formating
* @param string $select
* @param string $from
* @param string $config
* @param array $options
* @return array
*/
public function choose ($select, $from, $config = NULL, $options = NULL) {
if ($config === NULL) {
$stmt = "SELECT {$select} FROM {$from}";
} elseif ($config === 'EQUALS') {
$stmt = "SELECT {$select} FROM {$from} WHERE {$options['where_comp']} = '{$options['where_value']}'";
} elseif ($config === 'LIKE') {
$stmt = "SELECT {$select} FROM {$from} WHERE {$options['where_comp']} LIKE '{$options['where_value']}'";
} /** End if $config */
if (!($result = $this->mydb->query($stmt))) {
echo 'Query Error: ' . $result->error . '<br/>';
} else {
while ($row = $result->fetch_assoc()) {
$payload[] = $row;
}
return $payload;
} /** End if mydb->query */
} /** End choose method */
/** Put items into the database (INSERT INTO $table ($col) VALUES ($set)
* This method was designed to do basic inserts without complicating it and filter when $clean is required
* @param string $table
* @param string $col
* @param array $set
* @param string $clean
* */
public function put ($table, $col, $set, $clean = NULL) {
if ($clean) {
$set = "'" . implode("','",filter_var_array($set,FILTER_SANITIZE_STRING)) . "'";
$stmt = "INSERT INTO {$table} ({$col}) VALUES ({$set})";
} else {
$set = "'" . implode("','",$set) . "'";
$stmt = "INSERT INTO {$table} ({$col}) VALUES ({$set})";
} /** End form $stmt */
if (!($putResult = $this->mydb->query($stmt))) {
echo 'Insert Error: ' . $this->mydb->error . '<br/>';
} else {
return $putResult;
}
} /** End put method */
/** Change items in the database (UPDATE $table SET item=value WHERE condition)
* This method was designed to do basic updates without complicating it and filter when $clean is required
* @param string $table
* @param array $set
* @param array $where
* @param string $clean
* */
public function change ($table, $set, $where, $clean = NULL) {
if ($clean) {
foreach ($set as $key => $value) {
$value = filter_var($value, FILTER_SANITIZE_STRING);
$setArray[] = "{$key}='{$value}'";
}
$set = implode(',',$setArray);
$stmt = 'UPDATE ' . $table . ' SET ' . $set . ' WHERE ' . $where['target'] . ' = ' . $where['match'];
} else {
foreach ($set as $key => $value) {
$setArray[] = "{$key}='{$value}'";
}
$set = implode(',',$setArray);
$stmt = 'UPDATE ' . $table . ' SET ' . $set . ' WHERE ' . $where['target'] . ' = ' . $where['match'];
} /** End form $stmt */
if (!($putResult = $this->mydb->query($stmt))) {
echo 'Insert Error: ' . $this->mydb->error . '<br/>';
} else {
return $changeResult;
} /** End Query Check */
} /** End change method */
public function __destruct() {
if (is_object($this->mydb)) {
$this->mydb->close();
}
} /** End destruct */
} /** End mydb Class */
</code></pre>
<p>Example of CODE use:</p>
<p>::Include above and create $mydb object::</p>
<p><code>$set = array('team'=>'First Shift Tech','access'=>'None');</code></p>
<p><code>$where = Array('target'=>'author','match'=>'John Doe');</code></p>
<p><code>$mydb->change('agent',$set,$where);</code> Can I pass array's in this line instead? Seems I get an inspection error in phpstorm if I try to do some type of lazy deal.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>First of a note: you say yourself that everything is working. And that\n is what often counts. I hope I'm not to harsh, but it's my way of\n telling things ;)</p>\n</blockquote>\n\n<p>Overall:</p>\n\n<ul>\n<li>you should (try and) avoid an 'if' statement that change the action\nof a method. And document the $config (what does it mean, what does it do)</li>\n<li>you should use method names that are self-explicable (choose is\nactually select, change is actually update, put is actually insert.)</li>\n<li>Again, use method names that say what they do. 'change': change what? a record? the table declaration? the column definition?</li>\n<li>Never echo inside a method. If there is an error throw one. Of use a global Error handling class. e.g. Log::setError(..); (just imagining trying to figure out why there is a 'header allready sent' error because of that error).</li>\n</ul>\n\n<p>Now,I don't really know what you wrote. Is it a wrapper class for mysqli? That failed, you can now do less and code doesn't get easier to read (imo).</p>\n\n<p>Is it an adapter that adapts mysqli to a certain interface? Where is the interface?</p>\n\n<p>Does it help you abstract the database-layer and easily change the DB? again, no. mysqli is tightly coupled with this mysql class. What if we want to start using PDO? Or even step away from mySQL? All that code is useless then.</p>\n\n<p>Now, some specific remarks:</p>\n\n<hr>\n\n<pre><code>function choose();\n</code></pre>\n\n<blockquote>\n <p>Designed to be slim and rely more on PHP than mysql for result\n formating</p>\n</blockquote>\n\n<p>In what way does it rely more on php for result formatting? You are simply calling fetch_assoc(); where is the formatting happening?</p>\n\n<hr>\n\n<pre><code>function change(); & function put();\n</code></pre>\n\n<blockquote>\n <p>This method was designed to do basic updates without complicating it\n and filter when $clean is required</p>\n</blockquote>\n\n<p>How doesnt it complicate things? Why not use the mysqli prepared statements and let mysqli handle the filtering of of inputted variables? And your code isn't really basic. There is a lof of 'Repeat-yourself code'.</p>\n\n<hr>\n\n<p>So, let's fix what is 'broken'.</p>\n\n<p>I think that what you actually wanted to create was an adapter. The task of an adapter is translating the desired interface onto the correct method of the actual db class (mysqli in your case).</p>\n\n<p>To start of, we will have to design the desired interface. Let's for the sake of my answer (I'm lazy) create a simple <code>Select</code>, <code>Update</code>, <code>Delete</code> and <code>Insert</code> interface using an 'identifier' string as primary key.</p>\n\n<pre><code><?php\ninterface Database {\n public function __construct($client);\n public function select($table, $identifier);\n public function insert($table, $identifier, $data);\n public function update($table, $identifier, $data);\n public function delete($table, $identifier);\n}\n</code></pre>\n\n<p>Ok, brilliant. We now let other programmers (and ourself) know that if you are passing me a Database object, it has to implement these methods. Sadly for us, <code>mysqli</code> doesn't implement these methods directly. So the adapter pattern comes in handy here. We write an adapter for mysqli to fit our Database interface:</p>\n\n<pre><code><?php\nclass MysqliToDatabaseAdapter implements Database {\n private final $client;\n\n public function __construct($client) {\n $this->client = $client;\n }\n\n public function select($table, $identifier) {\n $stmt = $this->client->prepare('SELECT * FROM ' . $table . ' WHERE identifier = ?');\n $stmt->bind_param('s', $identifier);\n $stmt->execute();\n return $stmt->fetch();\n }\n\n public function insert($table, $identifier, $data) {\n $stmt = $this->client->prepare(\n 'INSERT INTO ' . $table .\n ' (`identifier`, `' . implode('`,`'array_keys($data)) . '`)' .\n ' VALUES (? ' . str_repeat(',?', count($data)) . ')'\n );\n $data = array_values($data);\n array_unshift($identifier, $data);\n $stmt->bind_param(\n str_repeat('s', count($data)),\n $data\n );\n return $stmt->execute();\n }\n\n public function update($table, $identifier, $data) {\n //...\n }\n public function delete($table, $identifier, $data) {\n //...\n }\n}\n</code></pre>\n\n<p>We would then use this class as follows:</p>\n\n<pre><code><?php\n$mysqli = new mysqli('host', 'database', 'user', 'pass');\n$myDbHandler = new MysqliToDatabaseAdapter($mysqli);\n//somewhere in the code\n$myDbHandler->insert('my_table','my_identifier',array('my_column'=>'my_column_data'));\n//and then we select it\n$data = $myDbHandler->select('my_table','my_identifier';\n</code></pre>\n\n<p>Now this code is easy to maintina, the methods do what they are called (select, insert,...) and we can now easily change the databaseHandler without having to change anything in our application.</p>\n\n<p>Offcourse at this point the Database interface is of not much use. There is no way to 'filter' data, bulk update, ... But these could all be implemented.\nA good rule here is if you have to write 'if' in the documentation, then split up the method into two different methods. e.f.:\n<code>update()</code> and <code>bulkUpdate()</code> or <code>select()</code> and <code>selectByColumn();</code></p>\n\n<p>Always keep your code small. Don't stuff one interface with massive amount of functions.\nCreate little small interfaces that focus on one part. e.g.\nDatabaseCrud (for simple create, read update and delete)\nDatabaseBulk (for bulk manipulations)\nDatabaseSomethingCompletlyDifferent (some other functions)</p>\n\n<p>Then depending on what you ned you can easily pass different DatabaseAdapters to different objects. Most code will only need simple CRUD functions. So you pass in the simple DatabaseCrudAdapter we made. For some special exotic method we can then create a bigger Adapter that implements extra interfaces that uses the same mysqli object.\nSome code for demonstrations:</p>\n\n<pre><code><?php\n//create the mysqli object\n$mysqli = new mysqli('host', 'database', 'user', 'pass');\n//create our adapters\n$simpleCrud = new MysqliToSimpleDatabaseCrud($mysqli); // implements SimpleDatabaseCrud();\n$simpleBulkCrud = new MysqliToSimpleBulkDatabase($mysqli); // extends MysqliToSimpleDatabaseCrud implements DatabaseBulk\n//create some objects\n$foo = new IOnlyNeedSimpltCrudFunctions($simpleCrud);\n$bar = new INeedSomeSpecialBulkFunctions($simpleBulkCrud);\n</code></pre>\n\n<p>I hope this maks any sense :p</p>\n\n<p>So, now it's up to you. You will have to write out a decent set of interfaces used inside your program. Then create adapters for existing code to fit those interfaces.</p>\n\n<p>More on the adapter pattern: <a href=\"http://en.wikipedia.org/wiki/Adapter_pattern\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Adapter_pattern</a>\nSome other usefull links:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Don%27t_repeat_yourself</a></li>\n<li><a href=\"http://www.jamisbuck.org/presentations/rubyconf2011/index.html\" rel=\"nofollow\">http://www.jamisbuck.org/presentations/rubyconf2011/index.html</a></li>\n<li><a href=\"http://thc.org/root/phun/unmaintain.html\" rel=\"nofollow\">http://thc.org/root/phun/unmaintain.html</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T20:57:06.500",
"Id": "47014",
"Score": "0",
"body": "This code was designed for a simple task of not passing the info for the db in each page that needed the database. I normally use exact method names but figured I would use different names for the heck of it. I felt like the interface only had benefit in the event that you had a bunch of different developers adding to the design but I see why its good to get into that practice. I did write a prepared version and a PDO version but I hate PDO and think it complicates things too much. The points you are making do help me a lot as Thanks for your time!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:01:19.690",
"Id": "47015",
"Score": "0",
"body": "Also instead of waiting till I fully understand the requirements of the code I decided to make the basic \"crud\" setup to just give me a base to work with. Talking about `Designed to be slim and rely more on PHP than mysql for result formating` that meant I pull a large DB result and use arrays and functions to return results that don't need joins. I understand the importance of not duplicating the results in the db but don't really see a need for joins yet! If I change the db type I would write a new class for it since I feel PDO adds too much and slows everything down."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T09:06:02.690",
"Id": "47034",
"Score": "0",
"body": "@sin0cide People think that using certain patterns instead of hacking away until it works is only good for big development enviroments. But they tend to forget themselves. If I now loko back at code I wrote 2 years ago before. I have no idea what is going on. I then am very happy to see that I used Patterns and good names. BEcause let's face it. We hardly read documentation :p\nI'm glad my answer helped :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T12:57:40.770",
"Id": "29685",
"ParentId": "29670",
"Score": "4"
}
},
{
"body": "<p>I basically subscribe to most of Pinoniq's remarks, but I'd like to touch on one thing in particular, that I just don't get.<br/>\nIt's good to see you're using <code>mysqli_*</code>, and I, for one, do understand why one would write a wrapper for this extension. It's API can be messy, and look confusing, and just allows for the users to sort-of switch from OO to procedural style, as they see fit. That's just wrong.</p>\n\n<p>However, you are <em>significantly</em> reducing the features I can use: Where is the <code>prepare</code> method? How can I use transactions? How do I configure the connections? can't I link data models to rows of a given table?<br/>\nNo, so what would stop me from creating my own instance of <code>mysqli</code> and do what I want? There's no <em>insentive</em> for me to use your code, if anything, there are a few reasons why I <em>wouldn't want to use your code</em>. </p>\n\n<p>You attempt to sanitize the values you insert into a table, as you also sanitze the <code>where</code> clauses. You're not using prepared statements, though, why?<Br/>\nWhat if I wanted to query the DB like so:</p>\n\n<pre><code>SELECT clients.first_name, clients.last_name, contacts.email FROM db.clients\n LEFT JOIN db.contacts \n ON contacts.client_id = clients.id\nWHERE clients.language = 1\n AND clients.active = TRUE;\n</code></pre>\n\n<p>You're treating everything as strings, whereas I'm actualy using a boolean and integer value in the where clause. But that's not the real issue. The only way I can possibly get my query to execute via your class is to pass my fields <em>and</em> the <code>JOIN</code> as the <code>$from</code> parameter, since it's just being concatenated in there, without any check on it whatsoever.<br/>\nNow I know it's highly unlikely that user input will ever be passed through via these arguments, and it does at least allow users to perform a <code>JOIN</code>. Still, you have to agree this is a rather hacky workaround for a problem that needn't exist in the first place, <em>and</em> it does mean that, in theory, this is possible:</p>\n\n<pre><code>$mydb->choose($_POST['input'], $_POST['input2']);\n</code></pre>\n\n<p>With the post values being <code>* FROM users /*</code> and <code>*/</code> respectively, which means, you're executing this query:</p>\n\n<pre><code>SELECT * FROM users /* FROM */\n</code></pre>\n\n<p>Not what you want, I think...</p>\n\n<p>The whole point of an abstraction layer should be to shield the users from having to write a ton of queries. Not all great devs are capable of writing <em>great</em> queries.</p>\n\n<p>Basically, I'd advise you to <em>not</em> reinvent the wheel, but if you want to, as a technical exercise, look at the bigger picture: DB's consist of tables/collections. Each row of those tables holds a finite number of fields, and each field has a given type/dimension. The rows, therefore, can easily be poured into data objects. As can the tables, because, if you know the fields, you'll want to know how they fit in the table (key, primary, index, collation, storage engine...).</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394\">Take a look here</a>, especially at the links below (ActiveRecord and ORM).<br/>\nRead through a couple of pages, let it sit for a while, and think about how you'd go about implementing a simple <em>query api</em>.</p>\n\n<p>And please, do use <em>type-hints:</em><br/>\nFor example here:</p>\n\n<pre><code>public function choose ($select, $from, $config = NULL, $options = NULL)\n{\n //some stuff\n $options['some_key'];\n}\n</code></pre>\n\n<p>If I passed a string there, or a numerically indexed array, and saw there was an error, and the message pointed to a line in <em>your</em> code, I'd tell you to debug your class. If a user doesn't pass the correct type of argument, he should be notified <em>when he attempts to call the method</em>. Change the signature to:</p>\n\n<pre><code>public function choose ($select, $from, array $config = NULL, array $options = NULL)\n</code></pre>\n\n<p>Even so, you're simply <em>assuming</em> certain keys will be set. Either use an object, that has the <em>property</em> you need, and defaults to a meaningful value, or compare the provided array to a private array that contains the default values:</p>\n\n<pre><code>class FoolMe\n{//minimal checks\n private $defaults = array(\n 'name' => array('type' => 'string', 'value' => 'default'),\n 'age' => array('type' => 'integer', 'value' => 0)\n );\n public function checkArray(array $arr)\n {\n foreach($this->defaults as $k => $settings)\n {\n if (isset($arr[$k]))\n {\n $arr[$k] = gettype($arr[$k]) === $settings['type'] ? $arr[$k] : $settings['value'];\n }\n else\n {\n $arr[$k] = $settings['value'];\n }\n }\n return $arr;\n }\n}\n\nclass SelectOptions\n{\n protected $where_comp = null;\n public function __get($name)\n {//bad, but better than array\n if (property_exists($this, $name))\n {\n return $this->{$name};\n }\n }\n //best:\n public function getWhereComp()\n {\n if ($this->where_comp === null)\n {\n return '';\n }\n return (string) $this->where_comp;\n }\n public function setWhereComp($str)\n {\n $this->where_comp = (string) $str;//ensure types using setters\n }\n}\n</code></pre>\n\n<p>Ah well, check a couple of my answers, both here and on SO. They often contain some elaborate example of a data-model and why you shouldn't use magic <code>__get</code> and <code>__set</code> methods and so on...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:53:18.417",
"Id": "46966",
"Score": "0",
"body": "+1. I should indedd have gon a little deeper in the point you point out here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:56:56.093",
"Id": "46967",
"Score": "0",
"body": "@Pinoniq: To be honest, I'm surprized you didn't. Especially since your main focus in the comments to the linked question were about prepared statements. There's a lot of things in your answer I subscribe to, but I can't bring myself to upvote: in my latest edit, I pointed at the (highly unlikely, but still) security holes introduced by stringing a table name into the query. That's why I suggested making a table and row objects (like most FW's and ORM's do)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:02:12.407",
"Id": "46968",
"Score": "0",
"body": "That makes two of us. Usually not acounting for prepared statements sets me off real hard :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:09:19.797",
"Id": "46969",
"Score": "1",
"body": "True about the security concerns, in fact my code is crap and should never be used in production enviroments. It's more about explaining the adapter pattern and showing it's strengths. Then depending on what type of code you are writing you could go for Design by contract, defensive programming,..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:14:09.367",
"Id": "46970",
"Score": "1",
"body": "@Pinoniq: Well, the adapter pattern is nicely explained, +1 for that (I hadn't read the complete answer). Of course, there's a lot to explain, and the longer the answer, the less likely it is ppl will actually _read_ it, there's always going to be a trade-off. Anyway your answer + some of my additions _should_ be enough to get the OP started"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:27:25.203",
"Id": "46973",
"Score": "0",
"body": "Your additions are indeed needed. Off-topic: somehow I can't tag you with @ in these comments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:29:09.743",
"Id": "46974",
"Score": "0",
"body": "@Pinoniq: that's because comments to an answer automatically relayed to the poster of that answer/question. No need to tag, I get a notification anyway"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:06:31.810",
"Id": "47016",
"Score": "0",
"body": "@EliasVanOotegem: When I tried to write the prepared statement I found myself not really needing the sanitation and only complicating the code because I tried to pass identifiers into prepare. I was also thinking about making a method that would just give me a mysqli object that I could run more advanced queries on. In my opinion the class seemed to shorten the code by not duplicating a lot of SQL but in the long run I don't think its that beneficial to anyone else to use. I agree with a lot of the suggestions you made and will keep those in mind when going forward. Thanks for your time!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T07:28:01.007",
"Id": "47029",
"Score": "1",
"body": "You could add a method that _exposes_ the `mysqli` object (like a magic `__call` method), but don't return it. Prepared statements and the mysqli API don't mix well, I agree. They're a good example of how the API just looks like a right mess, PDO offers a lot easier, and cleaner API for prepared statements. And of course you don't need to sanitize prepared statements, that's another reason why to use prepared statements..."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:43:56.573",
"Id": "29688",
"ParentId": "29670",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29685",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T02:39:51.330",
"Id": "29670",
"Score": "6",
"Tags": [
"php",
"object-oriented",
"mysqli"
],
"Title": "Minimalistic mysql db class"
}
|
29670
|
<p>Over the weekend I was perusing the web, and came across the programming problem, finding the longest non-decreasing subsequence in a grid, and I wanted to tackle it. I'm a web developer by profession, and sometimes, honestly, I feel like I fit <a href="http://www.codinghorror.com/blog/2009/08/all-programming-is-web-programming.html" rel="nofollow">the bill described by Jeff</a>. I don't feel that I chose web development because I'm too stupid for anything else, I just happen to have a passion for it. But I do feel that a lot of what Jeff says is true. I feel like what I do in and day out really isn't that <strong>hard</strong> and <strong>doesn't</strong> challenge me. Sure, I bind click handlers like nobody's business, make things pretty and even communicate with a database from time to time, but lets be honest...its just not that big of a deal. (Ok, except for tricky CSS inheritance issues :) )</p>
<p>So anyway, from time to time I look up interesting problems I want to try to solve or enter code challenges, to keep my mind sharp and challenge myself. So that's how I came to this. Also though, wanting to test <a href="http://www.codinghorror.com/blog/2007/07/the-principle-of-least-power.html" rel="nofollow">Atwood's law</a>, I wrote it in JavaScript, even if it makes no sense. :)</p>
<p>Basically, the algorithm first finds the smallest number in the grid, then begins at that point to inspect each adjacent cell for a number matching specified criteria. Cells are pre-filtered so they don't have to be inspected if they don't match specified criteria. Of course a matching number is also added to the filtering indices array, so we don't look at it again. This process repeats until no adjacent cell can be found that matches given criteria. </p>
<p>So the question for you is, what suggestions do you have for me to optimize and improve my current algorithm? Things I already want to implement:</p>
<ol>
<li>Create a few more functions like <code>matches_criteria()</code> and <code>do_assignments()</code> ti minimize repeating myself.</li>
<li>Use recursion instead of a loop and in other places to improve code readability. </li>
<li>Implement my own <code>copy_object()</code> function instead of using jQuery's <code>extend()</code>. I don't need all the functionality of <code>.extend()</code>. Thus becoming library independent and avoiding overhead from including jQuery. </li>
<li>I also feel like I just need to simplify it, and Im not exactly sure where I can simplify most.</li>
</ol>
<p>I'm looking for any suggestions, from JavaScript-specific performance tips to general algorithm suggestions.</p>
<pre><code> (function($) {
"use strict";
var day_lookup = {
"0": "Sunday",
"1": "Monday",
"2": "Tuesday",
"3": "Wednesday",
"4": "Thursday",
"5": "Friday",
"6": "Saturday"
};
var today = day_lookup[new Date().getDay()];
var initial_number_data = {
value: null,
grid_location: {
row: null,
column: null
}
};
function valid_grid(grid) {
var this_row = [];
var next_row = [];
for (var i = 0; i < grid.length; i++) {
this_row = grid[i];
// if there is another row
if (typeof(next_row = grid[i + 1]) !== "undefined") {
// make sure we have the same number of columns in each row
// there can be an arbitrary number of rows and columns but
// each row has to have the same number of columns, whatever
// that number is.
if (this_row.length !== next_row.length) {
return false;
}
}
}
// if we made it through the for loop all rows have been checked
// and the grid is valid.
return true;
}
function print_grid(grid) {
var grid_row_strings = [];
for (var i = 0; i < grid.length; i++) {
grid_row_strings.push(grid[i].join(" -- "));
}
console.log(grid_row_strings.join("\n"));
}
// checks to see if the row and column have already been added
// to the path
function is_already_indexed(indices, grid_location) {
for (var i = 0; i < indices.length; i++) {
if (indices[i].row === grid_location.row && indices[i].column === grid_location.column) {
return true;
}
}
return false;
}
function is_equal(obj1, obj2) {
for (var prop in obj1) {
if (typeof obj1[prop] === "object" && typeof obj2[prop] === "object") {
if (!is_equal(obj1[prop], obj2[prop])) {
return false;
}
} else {
if (obj1[prop] !== obj2[prop]) {
return false;
}
}
}
return true;
}
function calc_smallest_number(grid) {
console.time("calc_smallest_number");
var smallest_number = $.extend(true, {}, initial_number_data);
var current_value = 0;
var iterations = 0;
// loop through rows
for (var i = 0; i < grid.length; i++) {
console.log("examining row: " + i);
// loop through columns of a row
for (var j = 0; j < grid[i].length; j++) {
console.log("examining column: " + j);
current_value = grid[i][j];
// number is less than the stored smallest number, set the current number as
// the smallest number.
if (smallest_number.value === null || current_value < smallest_number.value) {
console.log("setting smallest_number.value to " + current_value);
smallest_number.value = current_value;
console.log("setting smallest_number.grid_location.row to: " + i);
// now store the location of this number so we can access it later
smallest_number.grid_location.row = i;
console.log("setting smallest_number.grid_location.column to: " + j);
smallest_number.grid_location.column = j;
iterations++;
}
}
iterations++;
}
console.log("It took "+ iterations +" iterations to determine the smallest number in the following grid:");
print_grid(grid);
console.log("Time needed to determine the smallest number in the grid:");
console.timeEnd("calc_smallest_number");
console.log("***********************************************");
console.log("Smallest number: " + smallest_number.value);
console.log("***********************************************");
return smallest_number;
}
window.find_longest_sequence = function(grid) {
if (!valid_grid(grid)) {
console.log("The following grid is invalid:");
print_grid(grid);
console.log("Please pass a valid grid to find_longest_sequence and enjoy your " + today +".");
return false;
}
// graph is valid...lets dig in...
// first lets get the smallest number in the grid.
var smallest_number = calc_smallest_number(grid);
// awesome, we have the smallest number and its location in the grid
// now lets start searching...
var current_num = $.extend(true, {}, smallest_number);
var next_num = $.extend(true, {}, initial_number_data);
var row = null;
var column = null;
var backwards = $.extend(true, {}, initial_number_data);
var below = $.extend(true, {}, initial_number_data);
var forwards = $.extend(true, {}, initial_number_data);
var above = $.extend(true, {}, initial_number_data);
var bottom_right = $.extend(true, {}, initial_number_data);
var bottom_left = $.extend(true, {}, initial_number_data);
var top_right = $.extend(true, {}, initial_number_data);
var top_left = $.extend(true, {}, initial_number_data);
var needle = $.extend(true, {}, initial_number_data);
var found_next_num_candidate = false;
var found_next_num = false;
var done = false;
var indices = [];
var path = [];
var indices_to_add = [];
var iterations = 0;
// begin search algorithm....
// order of searching is...
// 1. look backwards
// 2. look below
// 3. look forward
// 4. look above
// 5. look down and to the right
// 6. look down and to the left
// 7. look up and to the right
// 8. look up and to the left
// determine next biggest number and keep going
console.time("find_longest_sequence");
while (!done) {
console.log("Pushing "+ current_num.value +" onto path.");
// push the current value onto the path.
path.push(current_num.value);
row = current_num.grid_location.row;
column = current_num.grid_location.column;
// reset all searchers
backwards = $.extend(true, {}, initial_number_data);
forwards = $.extend(true, {}, initial_number_data);
above = $.extend(true, {}, initial_number_data);
bottom_right = $.extend(true, {}, initial_number_data);
bottom_left = $.extend(true, {}, initial_number_data);
top_right = $.extend(true, {}, initial_number_data);
top_left = $.extend(true, {}, initial_number_data);
// reset holder of indices that need to be added to the indices
// array but have not yet been added.
indices_to_add.length = 0;
// backwards.grid_location.row = row;
// backwards.grid_location.column = column - 1;
backwards.value = (grid[row] && grid[row][column - 1]) ? grid[row][column - 1] : false;
// console.log("backwards: " + backwards);
if (backwards.value) {
backwards.grid_location = {
row: row,
column: column - 1
};
if (!(backwards.value >= current_num.value)) {
indices_to_add.push(backwards.grid_location);
}
}
// below.grid_location.row = row + 1;
// below.grid_location.column = column;
below.value = (grid[row + 1] && grid[row + 1][column]) ? grid[row + 1][column] : false;
// console.log("below: " + below);
if (below.value) {
below.grid_location = {
row: row + 1,
column: column
};
if (!(below.value >= current_num.value)) {
indices_to_add.push(below.grid_location);
}
}
// forwards.grid_location.row = row;
// forwards.grid_location.column = column + 1;
forwards.value = (grid[row] && grid[row][column + 1]) ? grid[row][column + 1] : false;
// console.log("forwards: " + forwards);
if (forwards.value) {
forwards.grid_location = {
row: row,
column: column + 1
};
if (!(forwards.value >= current_num.value)) {
indices_to_add.push(forwards.grid_location);
}
}
// above.grid_location.row = row - 1;
// above.grid_location.column = column;
above.value = (grid[row - 1] && grid[row - 1][column]) ? grid[row - 1][column] : false;
// console.log("above: " + above);
if (above.value) {
above.grid_location = {
row: row - 1,
column: column
};
if (!(above.value >= current_num.value)) {
indices_to_add.push(above.grid_location);
}
}
// bottom_right.grid_location.row = row + 1;
// bottom_right.grid_location.column = column + 1;
bottom_right.value = (grid[row + 1] && grid[row + 1][column + 1]) ? grid[row + 1][column + 1] : false;
// console.log("bottom_right: " + bottom_right);
if (bottom_right.value) {
bottom_right.grid_location = {
row: row + 1,
column: column + 1
};
if (!(bottom_right.value >= current_num.value)) {
indices_to_add.push(bottom_right.grid_location);
}
}
// bottom_left.grid_location.row = row + 1;
// bottom_left.grid_location.column = column - 1;
bottom_left.value = (grid[row + 1] && grid[row + 1][column - 1]) ? grid[row + 1][column - 1] : false;
// console.log("bottom_left: " + bottom_left);
if (bottom_left.value) {
bottom_left.grid_location = {
row: row + 1,
column: column - 1
};
if (!(bottom_left.value >= current_num.value)) {
indices_to_add.push(bottom_left.grid_location);
}
}
// top_right.grid_location.row = row - 1;
// top_right.grid_location.column = column + 1;
top_right.value = (grid[row - 1] && grid[row - 1][column + 1]) ? grid[row - 1][column + 1] : false;
// console.log("top_right: " + top_right);
if (top_right.value) {
top_right.grid_location = {
row: row - 1,
column: column + 1
};
if (!(top_right.value >= current_num.value)) {
indices_to_add.push(top_right.grid_location);
}
}
// top_left.grid_location.row = row - 1;
// top_left.grid_location.column = column - 1;
top_left.value = (grid[row - 1] && grid[row - 1][column - 1]) ? grid[row - 1][column - 1] : false;
// console.log("top_left: " + top_left);
if (top_left.value) {
top_left.grid_location = {
row: row - 1,
column: column - 1
};
if (!(top_left.value >= current_num.value)) {
indices_to_add.push(top_left.grid_location);
}
}
found_next_num_candidate = false;
found_next_num = false;
if ((needle = $.extend(true, {}, backwards)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, below)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, forwards)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, above)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, bottom_right)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, bottom_left)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, top_right)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if ((needle = $.extend(true, {}, top_left)) && needle.value && !is_already_indexed(indices, needle.grid_location) && needle.value >= current_num.value && (needle.value <= next_num.value || is_equal(next_num, initial_number_data))) {
next_num = $.extend(true, {}, needle);
found_next_num_candidate = true;
}
if (found_next_num_candidate) {
current_num = $.extend(true, {}, next_num);
next_num = $.extend(true, {}, initial_number_data);
found_next_num = true;
indices_to_add.push(current_num.grid_location);
}
// push all succesfully indexed positions in the grid
// onto the indicies array if they arent already there.
for (var i = 0; i < indices_to_add.length; i++) {
if (!is_already_indexed(indices, indices_to_add[i])) {
console.log("Pushing index:");
console.log(JSON.stringify(indices_to_add[i], null, 4));
console.log("onto indices array in loop iteration "+ iterations + ".");
indices.push(indices_to_add[i]);
}
}
if (!found_next_num) {
done = true;
}
iterations++;
}
console.log("It took "+ iterations +" iterations to determine the longest non-decreasing sequence for the following grid:");
print_grid(grid);
console.log("Time needed to determine the longest non-decreasing sequence in the grid:");
console.timeEnd("find_longest_sequence");
console.log("========================================================");
console.log("Longest non-decreasing sequence: " + path.join("->"));
console.log("========================================================");
console.log("Enjoy your "+ today +"!");
};
})($KOBJ); // jQuery is aliased to $KOBJ in my environment.
(function() {
"use strict";
find_longest_sequence([[8, 2, 4],
[0, 7, 1],
[3, 7, 9]]); // this call produces the sequence: 0->2->4->7->7->9
})();
</code></pre>
<hr>
<p><strong>Original Problem Description:</strong></p>
<blockquote>
<p>Find the length of the longest non-decreasing sequence through
adjacent, non-repeating cells (including diagonals) in a rectangular
grid of numbers in a language of your choice. The solution should
handle grids of arbitrary width and height. For example, in the
following grid, one legal path (though not the longest) that could be
traced is 0->3->7->9 and its length would be 4. 8 2 4 0 7 1 3 7 9 The
path can only connect adjacent locations (you could not connect 8 ->
9). The longest possible sequence for this example would be of length
6 by tracing the path 0->2->4->7->7->9 or 1->2->4->7->7->9.</p>
</blockquote>
<hr>
<p><strong>Update:</strong></p>
<p>As pointed out by Stuart, my algorithm has a fatal wrong assumption. I assume in the algorithm that the longest non-decreasing sequence will always start at the smallest number in the grid. This is <strong>wrong</strong>. Passing the following grid:</p>
<pre><code>[[0, 9, 8],
[9, 9, 4],
[1, 2, 3]]
</code></pre>
<p>to <code>find_longest_sequence()</code> function produces the following sequence:</p>
<pre><code>0->9->9->9
</code></pre>
<p>which is clearly not the the longest increasing sequence. This happens because my algorithm assumes that its always starting from the right position, and so if it cant find any positions that match criteria in any adjacent cells, it assumes its automatically found the longest non decreasing sequence in the grid, when really its only found the longest non-decreasing sequence for that <strong>starting position.</strong> Stuart, thanks a ton! This is a huge help! I'm excited to fix this and come back with my updated solution for further review.</p>
<p>Updates to come...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:07:28.137",
"Id": "47017",
"Score": "1",
"body": "Does your function actually work? If the grid you pass to it is `[[0, 9, 8],\n [9, 9, 4],\n [1, 2, 3]]`, for example, does it get the correct sequence `[1, 2, 3, 4, 8, 9]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:15:53.090",
"Id": "47018",
"Score": "1",
"body": "oh my example is wrong! But anyway have you tested it on a few cases like that? From a glance your function seems to me unlikely to work in such cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:50:45.273",
"Id": "47020",
"Score": "0",
"body": "Aha! It does not! I make a false assumption about starting at the smallest number! That doesn't necessarily mean it will be the longest non-decreasing sequence! Thanks for the catch!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T22:12:50.683",
"Id": "47021",
"Score": "0",
"body": "@Stuart Btw thanks for taking the time to go through it and find issues! I know its a fair bit of code thats not really in the best state right now. :)"
}
] |
[
{
"body": "<p>Aside from the fact that your algorithm doesn't work in cases where there is a solution that does not start with the smallest number, I would say that you are doing everything in an unnecessarily complex way, particularly in the way you use objects for all of the numbers and having to make copies of the <code>initial_number_data</code> all the time.</p>\n\n<p>For example, <code>calc_smallest_number</code> could be simplified to:</p>\n\n<pre><code>function calcSmallestNumber(grid) {\n var r;\n for (var i = 0; i < grid.length; i++) {\n for (var j = 0; j < grid[i].length; j++) {\n if (!r || grid[i][j] < r.value) {\n r = {\n value: grid[i][j],\n gridLocation: {row: i, column: j}\n };\n }\n }\n }\n return r;\n }\n</code></pre>\n\n<p>Then in the main function <code>find_longest_sequence</code> you have a load of repetition which could be avoided in a number of possible ways, such as by using a list of coordinate offsets representing the different directions, something like this:</p>\n\n<pre><code>var directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];\nfor (var i = 0; i < directions.length; i++) {\n neighbouringLocation = {\n row: myPoint.gridLocation.row + directions[i][0],\n column: myPoint.gridLocation.column + directions[i][1]\n };\n // do stuff with neighbouringLocation\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T22:24:14.047",
"Id": "47022",
"Score": "0",
"body": "Yeah I was thinking about just using an array of arrays with two values to store locations. Looping over each direction and doing stuff in that specific iteration with a location would drastically reduce repeating myself. Also I really like what you did with `calc_smallest_number()`. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T06:00:21.357",
"Id": "47365",
"Score": "0",
"body": "This week has been a busy one. Hopefully have some updates this weeekend."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T22:16:12.007",
"Id": "29710",
"ParentId": "29674",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29710",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T05:07:34.980",
"Id": "29674",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"algorithm",
"recursion"
],
"Title": "Finding the longest non-decreasing subsequence in a grid"
}
|
29674
|
<p>I need to refactor following class:</p>
<pre><code>public class Message
{
public Guid ID { get; set; }
public string MessageIn { get; set; }
public string MessageOut { get; set; }
public int StatusCode { get; set; } //EDIT could be changed during message lifecycle
public bool IsDeletable
{
get
{
switch (this.StatusCode)
{
case 12:
case 13:
case 22:
case 120:
return true;
default:
return false;
}
}
}
public bool IsEditable
{
get
{
switch (this.StatusCode)
{
case 12:
case 13:
case 22:
case 120:
return true;
default:
return false;
}
}
}
public string Message
{
get
{
switch (this.StatusCode)
{
case 11:
case 110:
return this.MessageIn;
case 12:
case 13:
case 22:
case 120:
return this.MessageOut;
default:
return string.Empty;
}
}
}
}
</code></pre>
<ol>
<li>I would like to remove the business rules <code>IsDeletable</code> and <code>IsEditable</code></li>
<li>I would like to remove these <code>switch</code> statements at the same time</li>
</ol>
<p>I am not sure if it's worth knowing that I am mapping entity to database table through Entity Framework.</p>
<p>One more problem that I have is that fields <code>MessageIn</code> and <code>MessageOut</code> are dependent on <code>StatusCode</code>. One of them are always populated. I could create new property but still the switch case is there:</p>
<pre><code>public string Message
{
get
{
switch (this.StatusCode)
{
case 10:
case 12:
case 13:
case :
return this.MessageIn;
default:
return this.MessageOut;
}
}
set { // switch again}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:14:30.260",
"Id": "46971",
"Score": "0",
"body": "You said \"you *need* to...\", or is it just esthetics? If `StatusCode` is integral to a `Message` and edit/delete is directly related to `StatusCode` then it looks reasonable as is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:26:27.370",
"Id": "46976",
"Score": "2",
"body": "`public bool IsDeletable {get{return IsEditable;}}` ? Currently, the two switches are identical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T06:08:22.563",
"Id": "47026",
"Score": "0",
"body": "@Brian Yes indeed, today. Tomorrow maybe not."
}
] |
[
{
"body": "<blockquote>\n <p>I would like to remove these switch statments in the same time</p>\n</blockquote>\n\n<pre><code>[Flags]\npublic enum StatusCode{\n codeX = 1,\n codeY = 2,\n codeZ = 4,\n codeA = 8,\n editable = codeX | codeZ,\n deleteable = codeY | codeZ\n}\n</code></pre>\n\n<p><strong>Key points</strong></p>\n\n<ul>\n<li>Use the <code>Flags</code> attribute</li>\n<li>enum values are powers of 2 - NOT multiples of 2</li>\n<li>bit-wise AND, OR provides the magic!</li>\n</ul>\n\n<h2>Edit</h2>\n\n<p>addressing the comments:</p>\n\n<pre><code>public static class StatusCodes {\n private Dictionary<StatusCode, int> values;\n private Dictionary<int,StatusCode> keys;\n\n static StatusCodes() {\n\n values = new Dictionary<StatusCode, string> {\n {StatusCode.A, 10},\n {StatusCode.B, 20},\n // and so on\n }\n\n keys = new Dictionary<in, StatusCode> {\n {10, StatusCode.A},\n {20, StatusCode.B},\n }\n }\n\n public static int GetValue(StatusCode theStatusCodeKey) {} // don't forget error trapping!\n public static StatusCode GetKey(int theIntValue) {} // ditto\n\n public static bool Editable(StatusCode thisCode) {\n return (StatusCode.editable & thisCode) == thisCode;\n }\n\n public static bool Editable(int thisValue) {\n return Editable( GetKey(thisValue));\n }\n}\n</code></pre>\n\n<ul>\n<li>The definition of the codes is all in one place - that's SOLID (D = DRY, don't repeat yourself)</li>\n<li>The definitions are in its own class - that's SOLID (S = single responsibility)</li>\n<li><code>editable</code> and <code>deleteable</code> can be removed from <code>Message</code> - that's <em>very</em> SOLID (S = single responsibility)</li>\n<li>We know what all those integers mean - thats.. well, just good programming.</li>\n<li>The <code>StatusCode</code>s are available anywhere and everywhere in the application - That's SOLID, an attribute of being DRY.</li>\n<li>I'm not sure what \"status code values might not be fixed\" in the comments means. Surely the set of status codes is finite.</li>\n</ul>\n\n<h2>Edit</h2>\n\n<ul>\n<li>Define \"editability\" in StatusCodes</li>\n<li>Use above to express Message is editable</li>\n<li>Address issue of exposing <code>StatusCode.editable</code> \"as if it were a valid code\"</li>\n<li>Adhere to Single Responsibility</li>\n<li>Adhere to DRY principle</li>\n</ul>\n\n<p>...</p>\n\n<pre><code>public static class StatusCodes\n{\n private static Dictionary<StatusCode, int> values;\n private static Dictionary<int,StatusCode> keys;\n\n static StatusCodes() {\n\n values = new Dictionary<StatusCode, int> {\n {StatusCode.A, 10},\n {StatusCode.B, 20},\n {StatusCode.C, 30},\n {StatusCode.D, 40}\n // and so on\n };\n\n keys = new Dictionary<int, StatusCode> {\n {10, StatusCode.A},\n {20, StatusCode.B},\n {30, StatusCode.C},\n {40, StatusCode.D}\n };\n }\n\n [Flags]\n enum Fungability\n {\n Editable = StatusCode.A | StatusCode.B,\n Deleteable = StatusCode.B | StatusCode.D\n }\n\n public static int GetValue( StatusCode theStatusCodeKey ) {\n int retVal;\n\n values.TryGetValue( theStatusCodeKey, out retVal );\n return retVal;\n } // don't forget error trapping!\n\n\n public static StatusCode GetKey( int theIntValue ) {\n StatusCode retVal;\n keys.TryGetValue( theIntValue, out retVal );\n return retVal;\n } // ditto\n\n public static bool Editable( StatusCode thisCode )\n {\n return ( (StatusCode)Fungability.Editable & thisCode ) == thisCode;\n }\n\n public static bool Editable( int thisValue )\n {\n return Editable( GetKey( thisValue ) );\n }\n\n}\n\n\npublic class Message\n{\n public StatusCode myStatus;\n\n public Message( int statusCode = 20 ) { myStatus = StatusCodes.GetKey(statusCode); }\n public Message( StatusCode statusCode = StatusCode.A ) { myStatus = statusCode; }\n\n public bool Editable\n {\n get { return StatusCodes.Editable( myStatus ); }\n }\n\n public bool Deleteable\n {\n get { return StatusCodes.Deleteable( myStatus ); }\n }\n}\n</code></pre>\n\n<p><strong>Take Away</strong></p>\n\n<ul>\n<li>Structure data in an OO way</li>\n<li>Expose the data adhering to the Single Responsibility principle</li>\n<li>You get DRY as a side effect</li>\n<li>Structure yields simplicity, coherence, clarity. <code>Editable</code> is implemented with <em>only one line of code!</em></li>\n<li><code>Message.Editable</code> went from originally \"calculating\" if the status code was editable, to simply asking the <code>StatusCode</code> \"are you editable?\" </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:31:14.977",
"Id": "46989",
"Score": "2",
"body": "This only works if the status code values aren't fixed. They might be set to correspond to external values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:35:38.373",
"Id": "46990",
"Score": "0",
"body": "It's a good idea but it does look like the values correspond to an external specification. They are are too arbitrary otherwise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:46:09.413",
"Id": "46991",
"Score": "0",
"body": "well, these codes should be defined somewhere, somehow. Use `Dictionary`s to map them to/from the `StatusCode` enumeration. The `case` statements, along with the redundancy and maintenance, are gone; and as a bonus *we know what those integers mean!*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:21:54.607",
"Id": "46995",
"Score": "0",
"body": "By \"fixed\" I mean that the OP can't change them. So if they aren't fixed, he can set them to powers-of-two."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:23:25.623",
"Id": "46996",
"Score": "0",
"body": "By the way, the D in SOLID is for \"Dependency Inversion Principle\", not DRY."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:49:39.190",
"Id": "47000",
"Score": "0",
"body": "OOPS!! Well, its a principle anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T01:01:06.267",
"Id": "47023",
"Score": "2",
"body": "This makes `editable` look like a valid status code. I mean, you could write `message.myStatus = StatusCode.editable`, which would assign multiple codes, when only one code is actually needed for it to be considered \"editable\". How about a separate enum like `enum StatusCodeGroup { editable = StatusCode.codeX | StatusCode.codeZ ... }`? The check would then be `StatusCodeGroup.editable.HasFlag((StatusCodeGroup)myStatus)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T03:23:53.493",
"Id": "47024",
"Score": "0",
"body": "\"... look like a valid status code.\" Yes, good point. But in as much as these are *defined* strictly in terms of `StatusCode` values I very much like them where they are; but it is somewhat concerning. But at the very least do not include `editable/deleatable` in the dictionaries, and ensure these values are not allowed on the objects' statuscode property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T08:46:59.877",
"Id": "47032",
"Score": "0",
"body": "@radarbob Great solution. Could you please revise the code to be more complete? \"editable and deleteable can be removed from Message - that's very SOLID (S = single responsibility)\". Can be? Should be or not? Those two Dictionaries are there only for the mapping sake?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:52:55.917",
"Id": "47048",
"Score": "0",
"body": "@Dzenan - \".. there only for mapping sake?\". More than a \"mere translation\" mechanism, I see the dictionaries as the declaration & definition of data. The enum gives business meaning to otherwise arbitrary service code numbers and the dictionary holds the complete list of service codes. And I like enums for coding technical reasons - it Types the service codes and I get enum intellisense in visual studio."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:13:39.347",
"Id": "47053",
"Score": "0",
"body": "@Dzenan - \"editable ... can be removed from Message. .. Can or Should?\" I see it as how do you want your code to express concepts. \"editable\" is based on service code. If you want to hide/gloss over the fact that and editable Message is really all about service codes, then by all means have `Message.Editable`. These are not mutually exclusive. But no matter what, we must *clearly* encode what service codes *define* 'editable'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T06:53:19.930",
"Id": "47130",
"Score": "0",
"body": "@radarbob - I am not sure if I have a reason to hide it. I am using Message.Editable in business layer(when validating and performing action) and UI layer(when constracting view models) when presenting data. I am tempted to just use `StatusCodes.Editable(myStatus)` in these layers and remove Message.Editable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T07:21:52.407",
"Id": "47226",
"Score": "1",
"body": "Having both `keys` and `values` defined like that doesn't look very DRY to me. Granted, they are in the same place, but it's still very possible to update one and forget to update the other. I'd add a little code to programmatically reverse the mapping so there really is one place where you can change the codes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T13:14:25.770",
"Id": "47733",
"Score": "0",
"body": "I agree that 2 dictionaries is not completely DRY but I rationalized it thus: I want the speed of indexing, I don't want to iterate the dictionary, it is all in one place, and not shown in the code - but error trapping/exception handling means we will capture the \"update one and forgot to update the other [dictionary]\", and finally, awareness of the problem means we'll test for it!"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:08:49.520",
"Id": "29692",
"ParentId": "29680",
"Score": "4"
}
},
{
"body": "<p>To adhere to the Open/Closed Principle for this class, you can either:</p>\n\n<ol>\n<li>Change <code>StatusCode</code> to a class with <code>bool IsEditable</code>, <code>bool IsDeletable</code>, and <code>bool?UsesOutMessage</code> gettable only properties, generating the instances via a factory class, OR</li>\n<li>Pass <code>Func<bool, StatusCode> IsEditable</code>, <code>Func<bool, StatusCode> IsDeletable</code>, and <code>Func<bool?, StatusCode> UsesOutMessage</code> functions into <code>StatusCode</code>'s constructor.</li>\n</ol>\n\n<p>I don't see any other SOLID principles being broken in your original code, but it can be hard to tell out of context.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>If you went with option 1, <code>StatusCode</code> would be a class:</p>\n\n<pre><code>class StatusCode\n{\n private bool isDeletable;\n private bool isEditable;\n private bool? usesOutMessage;\n\n public StatusCode(bool isDeletable, bool isEditable, bool? usesOutMessage)\n {\n IsDeletable = isDeletable;\n IsEditable = isEditable;\n UsesOutMessage = usesOutMessage;\n }\n\n public bool IsDeletable\n {\n get { return isDeletable; }\n set { isDeletable = value; }\n }\n\n public bool IsEditable\n {\n get { return isEditable; }\n set { isEditable = value; }\n }\n\n public bool? UsesOutMessage\n {\n get { return usesOutMessage; }\n set { usesOutMessage = value; }\n }\n}\n</code></pre>\n\n<p>Your code above would become:</p>\n\n<pre><code>public class Message\n{\n public Guid ID { get; set; }\n public string MessageIn { get; set; }\n public string MessageOut { get; set; }\n public StatusCode StatusCode { get; set; } //EDIT could be changed during message lifecycle\n\n public bool IsDeletable\n {\n get\n {\n return this.StatusCode.IsDeletable;\n }\n }\n\n public bool IsEditable\n {\n get\n {\n return this.StatusCode.IsEditable;\n }\n }\n\n public string Message\n {\n get\n {\n\n if (this.StatusCode.UsesOutMessage.HasValue)\n {\n if (this.StatusCode.UsesOutMessage.Value)\n {\n return this.MessageOut;\n }\n else\n {\n return this.MessageIn;\n }\n }\n else\n {\n return string.Empty;\n }\n }\n }\n}\n</code></pre>\n\n<p>The factory class would still need to do something like:</p>\n\n<pre><code>StatusCode redAlert = new StatusCode(false, true, null);\nStatusCode amberAlert = new StatusCode(false, false, true);\nStatusCode chartreuseAlert = new StatusCode(true, true, false);\n</code></pre>\n\n<p>It looks like this is just moving the logic out of <code>MessageBase</code> into a factory, but this adheres to the Open/Closed principle for <code>MessageBase</code>. <code>MessageBase</code> and its unit test now no longer need to be modified when new status codes are added, removed, or modified. It just works now matter how the status codes change. </p>\n\n<p>This approach also keeps the logic in one place: the factory. Everything that needs to be known about status codes can be found in the factory rather than spread across multiple classes which use status codes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T14:45:57.890",
"Id": "47738",
"Score": "0",
"body": "Could you provide code sample illustrating solution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T15:25:49.097",
"Id": "47744",
"Score": "0",
"body": "@Dzenan, sure thing. See the edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:53:28.217",
"Id": "29741",
"ParentId": "29680",
"Score": "1"
}
},
{
"body": "<p>If status code of a message does not change during the lifecycle of Message instance, you probably can do a <a href=\"http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html\" rel=\"nofollow\">Replace Conditional with Polymorphism</a> refactoring. Thus you will get an hierarchy of classes that exposes common fields. The consumers of Message class will be working with a base class, unaware of exact implementation. Exact message classes could be created via <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow\">Factory Method</a> in a base class. This approach lets you give your message classes meaningful names which would be appreciated by the future developers as they will not have to guess what that mysterious 112 status code means.\nPlease see example below: </p>\n\n<pre><code>public abstract class MessageBase\n{\n public Guid ID { get; set; }\n public string MessageIn { get; set; }\n public string MessageOut { get; set; }\n public int StatusCode { get; set; }\n\n public static MessageBase CreateMessage(int statusCode)\n {\n switch (statusCode)\n {\n case 12:\n case 13:\n case 22:\n case 120:\n return new MessageA();\n default:\n return new MessageB(); \n }\n }\n\n public virtual bool IsDeletable\n {\n get { return false; }\n }\n\n public virtual bool IsEditable\n {\n get { return false; }\n }\n\n public virtual string Message\n {\n get\n {\n return string.Empty;\n }\n }\n}\n\npublic class MessageA : MessageBase\n{\n public override bool IsDeletable\n {\n get { return true; }\n }\n\n public override bool IsEditable\n {\n get { return true; }\n }\n\n public override string Message\n {\n get { return MessageOut; }\n }\n}\n\npublic class MessageB : MessageBase\n{\n public override bool IsDeletable\n {\n get { return true; }\n }\n\n public override string Message\n {\n get { return MessageIn; }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T09:17:03.910",
"Id": "47234",
"Score": "0",
"body": "In this case status code could change during the lifecycle of Message instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T09:29:31.770",
"Id": "47235",
"Score": "0",
"body": "In that case you may encapsulate message retrieving and deletable/editable logic in StatusCode class just like Robert suggested. In any case you definitely should have a class that represents various types of Statuses. Avoid using numbers and magic constants. It's usually hard to comprehend and maintain."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T06:52:41.637",
"Id": "29828",
"ParentId": "29680",
"Score": "1"
}
},
{
"body": "<p>When ever you encounter multiple conditions that you see growing, that should be a clear indication that a strategy pattern could help. You start by doing the following.</p>\n\n<p>Create a simple enum for your status codes.</p>\n\n<pre><code>public enum MessageStatusCodes{\n case12= 12,\n case13= 13,\n case22 = 22,\n case120 = 120\n}\n</code></pre>\n\n<p><strong>Create your interface that will instruct your concrete strategy classes how to handle your messages</strong></p>\n\n<pre><code>public interface IMessageStrategy{\nvoid Process(Message);\n\n}\n</code></pre>\n\n<p>Here your Message class will become your context object.</p>\n\n<pre><code>public class Message\n{\npublic Guid ID { get; private set; }\npublic string MessageIn { get; private set; }\npublic string MessageOut { get; private set; }\npublic MessageStatusCodes StatusCode { get; set; } //EDIT could be changed during message lifecycle\npublic Message(Guid id, string messageIn, string messageOut, MessageStatusCodes statusCode){\nID=id;\nMessageIn=messageIn;\nMessageOut=messageOut;\nStatusCode = statusCode;\nLoadStrategies();\n}\n\nprivate static Dictionary<MessageStatusCodes, IMessageStrategy> messageStrategies;\nprivate void LoadStrategies()\n{\n messageStrategies = new Dictionary<MessageStatusCodes,IMessageStrategy>();\n messageStrategies.Add(MessageStatusCodes.case12, new DeleteMessageStrategy() );\n\n}\n\n public void Process()\n{ \n return messageStrategies[StatusCode].Process(this);\n}\n}\n</code></pre>\n\n<p>Then you start by creating your concrete classes that implement the different actions or strategies that you want to perform for each condition. \nFor example, the Delete message action could be a strategy.</p>\n\n<pre><code>public class DeleteMessageStrategy : IMessageStrategy {\n\npublic void Process(Message){\n//do something based on delete status code\n}\n}\n</code></pre>\n\n<p>Then you call your Message like so</p>\n\n<pre><code>Message message = new Message(....);\nmessage.Process();\n</code></pre>\n\n<p>And then your code will process the message with respect to the status code passed in.</p>\n\n<p>When you're ready to expand, you implement new strategies and add those new strategies to your Message class so its aware of them.</p>\n\n<p>You can really expand on this template I have shown here. Take a look at my post, I did something very similar and had questions and came to codereview for answers</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/39844/preserving-dry-while-using-an-interface-abstract-class-and-delegate\">My Code Review Question</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T18:19:06.360",
"Id": "39896",
"ParentId": "29680",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29692",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-08-13T12:08:27.417",
"Id": "29680",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"design-patterns"
],
"Title": "Messages with status codes"
}
|
29680
|
<p>I'm new to ruby on rails, on this project I'm using Ruby 2.0 and Ruby on Rails 3.0.</p>
<p>I would like to know if this piece of code can be refactored, as it is</p>
<pre><code>unless params["ot_code"].nil?
ots = params["ot_code"].gsub(/\r\n?/, "").gsub(";","','").upcase
ots[ots.length,1] = "'"
ots = ots.rjust(ots.length+1,"'")
end
unless params["circuit_id_multiple"].nil?
multiple_circuit = params["circuit_id_multiple"].gsub(/\r\n?/, "").gsub(";","','")
multiple_circuit[multiple_circuit.length,1] = "'"
multiple_circuit = multiple_circuit.rjust(multiple_circuit.length+1,"'")
end
unless params["multiple_element_code"].nil?
multiple_element_code = params["multiple_element_code"].gsub(/\r\n?/, "").gsub(";","','")
multiple_element_code[multiple_element_code.length,1] = "'"
multiple_element_code = multiple_element_code.rjust(multiple_element_code.length+1,"'")
end
</code></pre>
|
[] |
[
{
"body": "<p>I'm a little worried about your <code>gsubs</code>, but assuming this is what you want to do:</p>\n\n<pre><code>def replace_and_wrap(str)\n return nil if str.nil?\n %Q{'#{str.gsub(/\\r\\n?/, \"\").gsub(\";\",\"','\")}'} \nend\n\nots = replace_and_wrap(params[\"ot_code\"])\nmultiple_circuit = replace_and_wrap(params[\"circuit_id_multiple\"])\nmultiple_element_code = replace_and_wrap(params[\"multiple_element_code\"])\n</code></pre>\n\n<p><del>Note that this changes the behavior of your code slightly: variables (like <code>ots</code>) are set to <code>nil</code> if the param is <code>nil</code>, rather than remaining <code>undefined</code>. Depending on how you are using these variables, this behavior is probably better anyway.</del></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T16:51:24.157",
"Id": "46992",
"Score": "0",
"body": "Actually a variable set inside a conditional is created (with value `nil`) even if the branch is not executed, so it's the same behavior. Not that's good practice though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:19:23.223",
"Id": "47005",
"Score": "0",
"body": "In fact, that's a good sign, conceptually it makes no sense :-). +1 btw. I would write `str ? expression_using_str : nil` but it's a minor detail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:29:57.003",
"Id": "47063",
"Score": "0",
"body": "`str && \"'#{str.gsub(/\\r\\n?/, \"\").gsub(\";\",\"','\")}'\"`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:18:56.463",
"Id": "29690",
"ParentId": "29687",
"Score": "2"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>params[\"ot_code\"]</code>. Is this a Rails controller? Then the first advice would be: never, ever write such long code in controllers. Controllers methods should be very lean, they should deal with the very minimal calls to models, flash setting and other render details. Nothing more.</p></li>\n<li><p><code>unless params[\"ot_code\"].nil?</code>. Try to use positive logic (and use symbols, it's more idiomatic): <code>if params[:ot_code]</code> or <code>if params[:ot_code].present?</code> depending whether you want to consider empty strings or not.</p></li>\n<li><p>There is almost exactly the same code repeated 3 times, that needs some DRYing. The two typical approaches: 1) bottom-up: abstract to function/method, or 2) top-bottom: write a loop. The first approach was already covered by @kardeiz, so I'll show the second:</p>\n\n<pre><code>keys = [:ot_code, :circuit_id_multiple, :multiple_element_code]\nots, multiple_circuit, multiple_element_code = keys.map do |key|\n if params[key].present?\n \"'%s'\" % params[key].gsub(/\\r\\n?/, '').gsub(/;/, '')\n end\nend\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:30:53.860",
"Id": "29703",
"ParentId": "29687",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T13:26:39.400",
"Id": "29687",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Is there a way to refactor this code?"
}
|
29687
|
<p>Just a small code review.
Is there a better way to get all folder names?</p>
<pre><code><?php
$folders = glob(dirname(__FILE__) . '/myFolder', GLOB_ONLYDIR);
foreach ( $folders as $f ) {
$lastDsPos = strrpos($v, DIRECTORY_SEPARATOR);
$myFolders[] = substr($v, $lastDsPos+1);
}
</code></pre>
|
[] |
[
{
"body": "<p>Have you considered using SPLs RecursiveIteratorIterator and RecursiveDirectoryIterator? Like this:</p>\n\n<pre><code>$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory), RecursiveIteratorIterator::CHILD_FIRST);\nforeach($iterator as $path){\n if($path->isDir()){\n $cache = $this->GetInfoArray($path->__toString());\n isset($cache) ? $this->listing['directories'][] = $cache : \"\";\n unset($cache);\n } else {\n $this->listing['files'][] = $this->GetInfoArray($path->__toString());\n }\n}\n</code></pre>\n\n<p>This will leave you with an array with two main nodes: files and directories. I wrote this for a PHP distributed test-and-build-on-commit system and it worked well. More info on the PHP SPL Iterators can be found here: <a href=\"http://www.php.net/manual/en/spl.iterators.php\" rel=\"nofollow\">http://www.php.net/manual/en/spl.iterators.php</a></p>\n\n<p>By the way, the GetInfoArray is this: </p>\n\n<pre><code>private function GetInfoArray($path){\n $d = new SplFileInfo($path);\n if($d->getBasename() == \".\" || $d->getBasename() == \"..\"){\n return;\n } else {\n return array(\n \"pathname\" => $d->getPathname(),\n \"access\" => $d->getATime(),\n \"modified\" => $d->getMTime(),\n \"permissions\" => $d->getPerms(),\n \"size\" => $d->getSize(),\n \"type\" => $d->getType(),\n \"path\" => $d->getPath(),\n \"basename\" => $d->getBasename(),\n \"filename\" => $d->getFilename()\n );\n }\n}\n</code></pre>\n\n<p>In the end, you're left with something like this:</p>\n\n<pre><code>$this->listing['files']['smiles.jpg']['pathname'] = \"/srv/www/smiles.jpg\"\n$this->listing['files']['smiles.jpg']['access'] = \"1323546894\"\n$this->listing['files']['smiles.jpg']['modified'] = \"2316546521\"\n$this->listing['files']['smiles.jpg']['permissions'] = \"744\"\n$this->listing['files']['smiles.jpg']['size'] = \"12Kb\"\n$this->listing['files']['smiles.jpg']['type'] = \"jpg\"\n$this->listing['files']['smiles.jpg']['path'] = \"/srv/www\"\n$this->listing['files']['smiles.jpg']['basename'] = \"smiles\"\n$this->listing['files']['smiles.jpg']['filename'] = \"smiles.jpg\"\n</code></pre>\n\n<p>What the heck, heres the class itself:</p>\n\n<p>\n\n<pre><code># Done\n\nclass DirectoryReader{\n private $directory;\n private $listing;\n\n public function __construct($directory){\n try {\n $this->directory = $directory;\n $this->listing = array();\n $this->ListDir();\n } catch(UnexpectedValueException $e){\n die(\"Path cannot be opened.\");\n } catch(RuntimeException $e){\n die(\"Path given is empty string.\");\n }\n }\n\n public function GetListing(){\n return $this->listing;\n }\n\n private function ListDir(){\n $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory), RecursiveIteratorIterator::CHILD_FIRST);\n foreach($iterator as $path){\n if($path->isDir()){\n $cache = $this->GetInfoArray($path->__toString());\n isset($cache) ? $this->listing['directories'][] = $cache : \"\";\n unset($cache);\n } else {\n $this->listing['files'][] = $this->GetInfoArray($path->__toString());\n }\n }\n }\n\n private function GetInfoArray($path){\n $d = new SplFileInfo($path);\n if($d->getBasename() == \".\" || $d->getBasename() == \"..\"){\n return;\n } else {\n return array(\n \"pathname\" => $d->getPathname(),\n \"access\" => $d->getATime(),\n \"modified\" => $d->getMTime(),\n \"permissions\" => $d->getPerms(),\n \"size\" => $d->getSize(),\n \"type\" => $d->getType(),\n \"path\" => $d->getPath(),\n \"basename\" => $d->getBasename(),\n \"filename\" => $d->getFilename()\n );\n }\n }\n}\n</code></pre>\n\n<p>As a further note, you can also just call <code>scandir($directory)</code> and filter via <code>is_dir()</code> in a <code>foreach</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T08:59:46.037",
"Id": "47033",
"Score": "0",
"body": "+1 for the nice snippet, didnt know the DirectoryIterator. But before I check as correct answer. Isn't this a lot of bloat for simply showing the directory names that are inside a given directory?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:36:29.447",
"Id": "47064",
"Score": "0",
"body": "@Pinoniq - it is a lot of bloat...like I mentioned, this is a class for a custom built build tool, so some bloat is ok since it only gets used every now and again. Also, this gives you a whole lot more information about the file and directory, than just a listing (gives last accessed time, permissions, etc). Also, it could benefit from some optimization, considering this is the first version of the tool & class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:38:11.563",
"Id": "47065",
"Score": "0",
"body": "Also, can just be autoloaded and called via `$dirsAndFiles = (new DirectoryReader($directory))->GetListing();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:05:49.713",
"Id": "47077",
"Score": "0",
"body": "You should create gist ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T17:57:27.400",
"Id": "47096",
"Score": "0",
"body": "Here you go @Pinoniq https://gist.github.com/jsanc623/6233664"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T18:04:35.007",
"Id": "47097",
"Score": "1",
"body": "also did a quick `microtime()'d` test and average for a directory containing 338 leafs (files + directories), total time taken was 0.009312 - not bad at all"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:23:38.923",
"Id": "29702",
"ParentId": "29691",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T14:51:30.243",
"Id": "29691",
"Score": "1",
"Tags": [
"php",
"php5"
],
"Title": "Retrieving all directorie names (relative path)"
}
|
29691
|
<p>I have the following case statements that has to be modified to fit these cases:
<code>Dec</code>, <code>Double</code>, <code>Int</code>, <code>Long</code>, <code>Short</code>, <code>Date</code>, and <code>String</code>.</p>
<p>Please let me know if there is an easier way to handle this rather than repeating the following (slightly modified for each case):</p>
<pre><code>Case GetType(Integer)
If String.IsNullOrEmpty(c.Text) Then
list.Add(CInt(0))
Else
Try
list.Add(CInt(c.Text))
Catch ex As Exception
WriteAudit(ex, True)
Dim intValue As Integer
If Not Integer.TryParse(c.Text, intValue) Then
c.Text = c.Text.Substring(0, c.Text.Length - 1)
MessageBox.Show("Please Enter Only Integer Values Here")
End If
End Try
End If
</code></pre>
|
[] |
[
{
"body": "<p>For value types (i.e. all your types except <code>String</code>) you can use the <a href=\"http://msdn.microsoft.com/en-us/library/dtb69x08.aspx\" rel=\"nofollow\"><code>Convert.ChangeType</code> method</a>:</p>\n\n<pre><code>list.Add(Convert.ChangeType(c.Text, theType))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T18:38:06.523",
"Id": "29704",
"ParentId": "29693",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29704",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T15:34:35.400",
"Id": "29693",
"Score": "0",
"Tags": [
"vb.net"
],
"Title": "Manage Case Statement with (Int, long, short, double.....)"
}
|
29693
|
<p>We're using a class called <code>Places</code> (inspired by <a href="http://www.drdobbs.com/jvm/solving-the-configuration-problem-for-ja/232601218?queryText=allen%2Bholub" rel="nofollow">Allen Holub's great article on DrDobbs</a>) that resolved our program paths based on the existence of a configuration file, environment variable or neither. In the neither case, we want all paths to default to resources within our package, the .jar. Additionally, we want to force local paths if we are in a testing environment because of the complexity in handling the Lucene Database.</p>
<p>The original code looks like this:</p>
<pre><code>private void resolvePaths() {
for (NewPlaces place : values()) {
List<String> probablePaths = new ArrayList<>();
try {
if (! IS_IN_A_UNIT_TESTING_ENVIRONMENT && !place.forceLocalPaths) {
File configuration = new File("places.properties");
if (configuration.exists()) {
LOGGER.info("The configuration file exists!");
Properties properties = new Properties();
properties.load(new FileInputStream(configuration));
probablePaths.add(place.path.replace("~", properties.getProperty("mediaplatform.home")));
}
if (System.getenv("MEDIAPLATFORM_HOME") != null) {
String environmentValue = System.getenv("MEDIAPLATFORM_HOME");
probablePaths.add(place.path.replace("~", environmentValue));
}
}
} catch (IOException e) {
throw new RuntimeException("The file could not be read.");
}
String localPath = place.path.replace("~/", "");
URL localUrl = Thread.currentThread().getContextClassLoader().getResource(localPath);
if (localUrl != null)
probablePaths.add(localUrl.getPath());
for (String probablePath : probablePaths) {
File file = new File(probablePath);
if (file.isDirectory()) {
LOGGER.info("\t{} -> {}", place.path, probablePath);
place.path = probablePath;
break;
}
}
if (place.path.contains("~"))
throw new RuntimeException("Could not find a proper path for value '" + place.path + "'");
}
}
</code></pre>
<p>I thought this function was long and needlessly complex to read, so I tried refactoring it into smaller methods with clearer meanings. The code ended up roughly 30 lines longer. The question is, did I make it simpler, easier to read and maintain, or did I just waste my time?</p>
<pre><code>private void resolvePaths() {
for (NewPlaces place : values()) {
List<String> probablePaths = new ArrayList<>();
if (!IS_IN_A_UNIT_TESTING_ENVIRONMENT)
probablePaths.addAll(findExternalPaths(place.path));
probablePaths.add(resolveLocalPath(place.path));
place.path = findBestPath(probablePaths);
}
}
private String resolveLocalPath(String unresolvedPath) {
String localPath = unresolvedPath.replace("~/", "");
URL localUrl = Thread.currentThread().getContextClassLoader().getResource(localPath);
checkArgument(localUrl != null, "The path '%s' does not exist locally, but it should.", localPath);
return localUrl.getPath();
}
private List<String> findExternalPaths(String unresolvedPath) {
List<String> externalPaths = new ArrayList<>();
Optional<String> configurationPath = resolvePathFromConfiguration(unresolvedPath);
if (configurationPath.isPresent())
externalPaths.add(configurationPath.get());
Optional<String> environmentPath = resolvePathFromEnvironment(unresolvedPath);
if (environmentPath.isPresent())
externalPaths.add(environmentPath.get());
return externalPaths;
}
private Optional<String> resolvePathFromConfiguration(String unresolvedPath) {
File configuration = new File("places.properties");
if (!configuration.exists())
return Optional.absent();
try {
LOGGER.info("The configuration file exists!");
Properties properties = new Properties();
properties.load(new FileInputStream(configuration));
return Optional.of(unresolvedPath.replace("~", properties.getProperty("mediaplatform.home")));
} catch (IOException e) {
throw new RuntimeException("Could not open or access configuration file 'places.properties'");
}
}
private Optional<String> resolvePathFromEnvironment(String unresolvedPath) {
if (System.getenv("MEDIAPLATFORM_HOME") == null)
return Optional.absent();
String environmentValue = System.getenv("MEDIAPLATFORM_HOME");
return Optional.of(unresolvedPath.replace("~", environmentValue));
}
private String findBestPath(List<String> probablePaths) {
for (String probablePath : probablePaths) {
File file = new File(probablePath);
if (file.isDirectory())
return probablePath;
}
throw new RuntimeException("Could not find a proper path!");
}
</code></pre>
<p><strong>Additional Info:</strong></p>
<p>NewPlaces is an enum class with the following structure:</p>
<pre><code>public enum NewPlaces {
DATA_STORE_PERSON("~/data_stores/prod/person_store"), DATA_STORE_TERM("~/data_stores/prod/term_store"), DATA_STORE_RESOURCE(
"~/data_stores/prod/resource_store"),
TESTDATA("~/testdata", ForceLocalPaths.TRUE), PROPERTIES("~/properties"), CONFIGURATION("~/configuration", ForceLocalPaths.TRUE);
private enum ForceLocalPaths {
TRUE, FALSE;
}
</code></pre>
<p>If a developer tries to access a directory contained in an enum for the first time, then the paths will be resolved via the above semantics:</p>
<pre><code>public File directory() {
if (path.contains("~"))
resolvePaths();
File directory = new File(path);
assert directory.isDirectory() : "The directory does not exist or is not a directory.";
return directory;
}
</code></pre>
|
[] |
[
{
"body": "<p>Due to the size of the code I think you'd be better off just adding some comprehensive comments rather than refactor. </p>\n\n<p>So to answer your question:</p>\n\n<p>Did you needlessly complicate it? Yes and No</p>\n\n<p>Yes: It is needless since the code already worked as intended.<br>\nNo: You didn't complicate it. </p>\n\n<p>So you spent some time for an un-necessary refactor, but if it helped you understand the code then that is a plus. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:46:29.407",
"Id": "29698",
"ParentId": "29695",
"Score": "3"
}
},
{
"body": "<p>I think you have achieved your objective. The new code is significantly easier to follow and will be much easier to maintain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:52:59.867",
"Id": "29700",
"ParentId": "29695",
"Score": "1"
}
},
{
"body": "<p>You're on the right track, you just need to take it a bit further.</p>\n\n<ul>\n<li>The <code>IS_IN_A_UNIT_TESTING_ENVIRONMENT</code> is the greatest eye sore. Delegate loading properties from a file to a collaborator class and the code will become simpler in this class, and easier to test, since you can now inject a dummy/mock <code>PropertiesLoader</code>.</li>\n</ul>\n\n<p>example - <em>untested</em> -</p>\n\n<pre><code>public interface PropertiesLoader {\n\n Optional<Properties> load(String name);\n}\n\npublic class FilePropertiesLoader implements PropertiesLoader {\n @Override\n public Optional<Properties> load(String name) {\n File configuration = new File(name + \".properties\");\n if (!configuration.exists()) {\n return Optional.absent();\n }\n LOGGER.info(\"The configuration file exists!\");\n Properties properties = new Properties();\n try {\n properties.load(new FileInputStream(configuration));\n return Optional.of(properties);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n}\n</code></pre>\n\n<ul>\n<li><p><code>Optional</code> is a great guava class, but probably a bit overkill to use in private methods.</p></li>\n<li><p>a few more extract methods to work away some duplication, and some tactical renames can make all the difference.</p></li>\n<li><p>the result is perhaps a few lines longer, but you'll find that shorter methods help you in all kinds of ways : </p>\n\n<ul>\n<li>they make code more readable</li>\n<li>they separate different levels of abstraction</li>\n<li>in case of a bug, the stacktrace will be much more revealing what is going wrong</li>\n<li>they offer more opportunity to explain what the code is doing in method names rather than in comments, which are harder to keep in sync with the code.</li>\n<li>I find small methods can be categorized in a number of idioms, this makes them easy to recognize, and lowers their conceptual threshold.</li>\n</ul></li>\n</ul>\n\n<p>And of course : one large method is always a puzzle.</p>\n\n<p>my current version : </p>\n\n<pre><code>private void resolvePaths() {\n for (NewPlaces place : NewPlaces.values()) {\n resolvePathsForPlace(place);\n }\n}\n\nprivate void resolvePathsForPlace(NewPlaces place) {\n List<String> probablePaths = new ArrayList<>();\n probablePaths.addAll(findExternalPaths(place.path));\n probablePaths.add(resolveLocalPath(place.path));\n place.path = findBestPath(probablePaths);\n}\n\nprivate String resolveLocalPath(String unresolvedPath) {\n String localPath = unresolvedPath.replace(\"~/\", \"\");\n URL localUrl = Thread.currentThread().getContextClassLoader().getResource(localPath);\n checkArgument(localUrl != null, \"The path '%s' does not exist locally, but it should.\", localPath);\n return localUrl.getPath();\n}\n\nprivate List<String> findExternalPaths(String unresolvedPath) {\n List<String> externalPaths = new ArrayList<>();\n addIfNotNull(externalPaths, resolvePathFromConfiguration(unresolvedPath));\n addIfNotNull(externalPaths, resolvePathFromEnvironment(unresolvedPath));\n return externalPaths;\n}\n\nprivate void addIfNotNull(List<String> externalPaths, String configurationPath) {\n if (configurationPath != null) {\n externalPaths.add(configurationPath);\n }\n}\n\nprivate String resolvePathFromConfiguration(String unresolvedPath) {\n Optional<Properties> properties = propertiesLoader.load(\"places\");\n return properties.isPresent() ? unresolvedPath.replace(\"~\", properties.get().getProperty(\"mediaplatform.home\")) : null;\n}\n\nprivate String resolvePathFromEnvironment(String unresolvedPath) {\n if (System.getenv(\"MEDIAPLATFORM_HOME\") == null) {\n return null;\n }\n return unresolvedPath.replace(\"~\", System.getenv(\"MEDIAPLATFORM_HOME\"));\n}\n\nprivate String findBestPath(List<String> probablePaths) {\n for (String probablePath : probablePaths) {\n if (new File(probablePath).isDirectory()) {\n return probablePath;\n }\n }\n throw new RuntimeException(\"Could not find a proper path!\");\n}\n\n\nprivate void checkArgument(boolean b, String s, String localPath) {\n //To change body of created methods use File | Settings | File Templates.\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T22:04:27.953",
"Id": "29709",
"ParentId": "29695",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:12:11.687",
"Id": "29695",
"Score": "3",
"Tags": [
"java",
"object-oriented"
],
"Title": "Resolving paths"
}
|
29695
|
<p>I am fairly new to writing unit tests, and I was wondering if this approach I have taken is on the right track?</p>
<p>Given the following interfaces/classes:</p>
<pre><code>public interface ILoggingService
{
void Log(string message);
}
public interface IShoppingCart
{
IList<IShoppingCartItem> Items { get; }
}
public interface IShoppingCartItem
{
string Sku { get; set; }
string Name { get; set; }
string Description { get; set; }
decimal Price { get; set; }
int Quantity { get; set; }
}
public interface IShippingCalculator
{
decimal Calculate();
}
public class ShoppingCartItem : IShoppingCartItem
{
public string Sku { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
public class ShippingCalculator : IShippingCalculator
{
private readonly ILoggingService loggingService;
private readonly IShoppingCart shoppingCart;
public ShippingCalculator(IShoppingCart shoppingCart, ILoggingService loggingService)
{
this.shoppingCart = shoppingCart;
this.loggingService = loggingService;
}
public decimal Calculate()
{
if (shoppingCart.Items.Count == 0)
return 0;
var pricePerItem = 3;
return shoppingCart.Items.Sum(x => x.Quantity * pricePerItem);
}
}
</code></pre>
<p>Given the requirements of:</p>
<blockquote>
<p>The Shipping Calculator must calculate shipping at the rate of $3.00 per item.</p>
</blockquote>
<p>Does this unit test look correct?</p>
<pre><code>public class ShippingCalculatorTests
{
[Fact]
public void Test1()
{
//Arrange
var cart = new Mock<IShoppingCart>();
cart.Setup(m => m.Items).Returns(
new List<IShoppingCartItem>() {
new ShoppingCartItem() { Quantity = 5 },
new ShoppingCartItem() { Quantity = 3 }
}
);
var logger = new Mock<ILoggingService>();
var calc = new ShippingCalculator(cart.Object, logger.Object);
//Act
var result = calc.Calculate();
//Assert
Assert.Equal(24, result);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your test is testing one thing only which is a very good thing. It is better to have many simple tests instead of one massive and it makes bug finding much easier.</p>\n\n<p>First of all, I would suggest using more descriptive names for both methods and test. Consider calling Calculate() method differently, i.e. CalculateTotalShippingPrice, so that it indicates what it is doing. </p>\n\n<p>Use test names which specify what is being tested, what is the state under test and expected behaviour as in: <a href=\"https://stackoverflow.com/questions/155436/unit-test-naming-best-practices\">https://stackoverflow.com/questions/155436/unit-test-naming-best-practices</a>.\nTest1 could be called Calculate_WhenShoppingCartNotEmpty_CorrectlyCalculatesTotalShippingPrice</p>\n\n<p>Make sure you take into account different scenarios, it is worth adding another test: Calculate_WhenShoppingCartEmpty_ReturnsZero.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T20:00:36.100",
"Id": "29705",
"ParentId": "29697",
"Score": "1"
}
},
{
"body": "<p>Unit Testing means testing single functionality at a time which is there above.\nMore test methods can be added similarly for example when cart is empty, when exception, so on.\nMoving further you can check whether some property has been set to specific using VerifySet or a function is called or not.\nThe approach is correct, as already said Method names need to be descriptive, you can follow any consistent pattern for that like: MethodName_TestSum_When_SomethingIsNUll().</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T17:30:47.683",
"Id": "29753",
"ParentId": "29697",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:43:33.357",
"Id": "29697",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"moq"
],
"Title": "Using MOQ in unit-testing for a shipping calculator"
}
|
29697
|
<p>I would love it if someone could give me some suggestions for these 2 graph search functions. I am new to scala and would love to get some insight into making these more idiomatic.</p>
<pre><code> type Vertex=Int
type Graph=Map[Vertex,List[Vertex]]
val g: Graph=Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3))
//example graph meant to represent
// 1---2
// | |
// 4---3
//I want this to return results in the different layers that it finds them (hence the list of list of vertex)
def BFS(start: Vertex, g: Graph): List[List[Vertex]]={
val visited=List(start)
val result=List(List(start))
def BFS0(elems: List[Vertex],result: List[List[Vertex]], visited: List[Vertex]): List[List[Vertex]]={
val newNeighbors=elems.flatMap(g(_)).filterNot(visited.contains).distinct
if(newNeighbors.isEmpty) result
else BFS0(newNeighbors, newNeighbors :: result, visited ++ newNeighbors)
}
BFS0(List(start),result,visited).reverse
}
//I would really appreciate some input on DFS, I have the feeling there is a way to do this sans var.
def DFS(start: Vertex, g: Graph): List[Vertex]={
var visited=List(start)
var result=List(start)
def DFS0(start: Vertex): Unit={
for(n<-g(start); if !visited.contains(n)){
visited=n :: visited
result=n :: result
DFS0(n)
}}
DFS0(start)
result.reverse
}
//some examples
scala> BFS(1,g)
res84: List[List[Vertex]] = List(List(1), List(2, 4), List(3))
scala> BFS(2,g)
res85: List[List[Vertex]] = List(List(2), List(1, 3), List(4))
scala> DFS(1,g)
res86: List[Vertex] = List(1, 2, 3, 4)
scala> DFS(3,g)
res87: List[Vertex] = List(3, 2, 1, 4)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T17:34:09.307",
"Id": "47949",
"Score": "0",
"body": "Your representation of graphs and nodes is broken. Shouldn't that at least be \"type Graph=Map[Vertex,Set[Vertex]]\"? Because no vertex should be listed twice as a connection for any other node (assuming that all the edges are undirected)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T19:18:59.317",
"Id": "47955",
"Score": "0",
"body": "*Why* are you searching this graph? It seems you aren't looking for any particular node, just collecting the whole set of nodes. This doesn't seem generally applicable. Hard to adapt to searching for a node with specific properties."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T13:02:27.810",
"Id": "48061",
"Score": "0",
"body": "@itsbruce you are right about the definition. I have changed that to Set to avoid having that issue.\n\nAs to why I am doing these searches: I was not looking for any node in particular, but rather wanted to check the logic in my DFS to use it to find strongly connected components.\n\nThanks for the review!"
}
] |
[
{
"body": "<p>OK, so I'm going to start with your DFS method. You're right - you should be able to do it without those vars in the outer function. You should be able to work out why - after all, you have vals in the outer layer of your BFS method. Why? Because your BFS uses a recursive helper function, so the vals are only used once (and could be discarded).</p>\n\n<p>So your DFS function should really use recursion, but I suspect you may have rejected recursion because you couldn't see how <strong>visited</strong> would be properly preserved as a recursive function popped back and forth. The answer is <strong>foldLeft</strong>.</p>\n\n<pre><code>def DFS(start: Vertex, g: Graph): List[Vertex] = {\n\n def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {\n if (visited.contains(v))\n visited\n else {\n val neighbours:List[Vertex] = g(v) filterNot visited.contains \n neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))\n } \n }\n DFS0(start,List()).reverse\n} \n</code></pre>\n\n<p>I don't have space here to explain foldLeft, if you've never encountered it - maybe Matt Malone's <a href=\"http://oldfashionedsoftware.com/2009/07/10/scala-code-review-foldleft-and-foldright/\">blog post</a> will help. You can rewrite almost anything with <strong>foldLeft</strong>, although it isn't always a good idea. Definitely the right thing to do here, though. Notice that I completely dropped your <strong>result</strong> var since <strong>visited</strong> <em>is</em> the result, the way you are doing this.</p>\n\n<p>My version of your DFS method is entirely functional, which is how Scala really wants to be used. Note also the lack of braces and brackets in </p>\n\n<pre><code>val neighbours:List[Vertex] = g(v) filterNot visited.contains\n</code></pre>\n\n<p>It <em>can</em> be written </p>\n\n<pre><code>val neighbours:List[Vertex] = g(v).filterNot(visited.contains)\n</code></pre>\n\n<p>but the Scala style is to omit the brackets and braces except where essential.</p>\n\n<p>Your BFS method is similarly over-populated. I've slimmed it down a little without altering the basic way it works:</p>\n\n<pre><code>def BFS(start: Vertex, g: Graph): List[List[Vertex]] = {\n\n def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {\n val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct\n if (newNeighbors.isEmpty) \n visited\n else\n BFS0(newNeighbors, newNeighbors :: visited)\n }\n\n BFS0(List(start),List(List(start))).reverse\n} \n</code></pre>\n\n<p>It still gives the same results.</p>\n\n<p>The other big point to make is that while Scala is a functional language it is also an Object Oriented language. Those DFS and BFS methods should belong to a graph object, preferably at least derived from a generic class. Something like this:</p>\n\n<pre><code>class Graph[T] {\n type Vertex = T\n type GraphMap = Map[Vertex,List[Vertex]]\n var g:GraphMap = Map()\n\n def BFS(start: Vertex): List[List[Vertex]] = {\n\n def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {\n val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct\n if (newNeighbors.isEmpty)\n visited\n else\n BFS0(newNeighbors, newNeighbors :: visited)\n }\n\n BFS0(List(start),List(List(start))).reverse\n }\n\n def DFS(start: Vertex): List[Vertex] = {\n\n def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {\n if (visited.contains(v))\n visited\n else {\n val neighbours:List[Vertex] = g(v) filterNot visited.contains\n neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))\n }\n }\n DFS0(start,List()).reverse \n }\n}\n</code></pre>\n\n<p>And then you could do this:</p>\n\n<pre><code>scala> var intGraph = new Graph[Int]\nscala> intGraph.g = Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3))\nscala> intGraph.BFS(1)\nres2: List[List[Int]] = List(List(1), List(2, 4), List(3))\nscala> intGraph.BFS(2)\nres3: List[List[Int]] = List(List(2), List(1, 3), List(4))\nscala> intGraph.DFS(3)\nres4: List[Int] = List(3, 2, 1, 4)\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>scala> var sGraph = new Graph[String]\nscala> sGraph.g = Map(\"Apple\" -> List (\"Banana\",\"Pear\",\"Grape\"), \"Banana\" -> List(\"Apple\",\"Plum\"), \"Pear\" -> List(\"Apple\",\"Plum\"), \"Grape\" -> List(\"Apple\",\"Plum\"), \"Plum\" -> List (\"Banana\",\"Pear\",\"Grape\"))\nscala> sGraph.BFS(\"Apple\")\nres6: List[List[java.lang.String]] = List(List(Apple), List(Banana, Pear, Grape), List(Plum))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T03:44:51.400",
"Id": "48215",
"Score": "0",
"body": "incredibly helpful!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T08:42:32.170",
"Id": "48230",
"Score": "0",
"body": "You're welcome. Really, though, I don't think Map is the best model for graphs, although having a constructor method which took a Map as input might often be fine. I would implement Graph as an immutable generic collection, most of whose methods returned new views/versions/subsets of the original object. I'd write the DF and BF traversal methods in the style of fold/foldLeft/foldRight so that searching the graph for a specific node (or subset) or returning the whole graph (in either of your given styles) was just a case of passing in the right function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T11:12:12.850",
"Id": "48247",
"Score": "0",
"body": "Is this what you were looking for from an answer, @JPC, or are you after some more/other information?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T11:43:02.980",
"Id": "48250",
"Score": "0",
"body": "I went back and re-read this now and think you did a fantastic job at explaining! I really wish I could give you another upvote. This is exactly the info I was looking for. I'm trying to learn scala on my own, but having few-no people to review what I do, I fear I am incurring in a bunch of pitfalls and developing poor habits. So thank you for helping me change this!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T11:54:58.140",
"Id": "48252",
"Score": "0",
"body": "oh and thanks for actually providing a link to that blog post...few people seem to be doing this now for some reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T12:33:25.903",
"Id": "48388",
"Score": "0",
"body": "oops!, my bad. I thought I had. I gave it an upvote, hadn't realized I hadn't accepted. Thank you for the reminder"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-23T19:23:24.300",
"Id": "272242",
"Score": "0",
"body": "It seems to me that your implementation wouldn't catch input danglers (inputs into the graph which start in places other than your start vertex, but which are unreachable from the start vertex). Would it still be possible to implement this in a purely functional way without mutable state if you want to keep track of these danglers? I'm having a hard time figuring out how to keep track of the explored vertices without mutable state otherwise."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-27T02:09:08.897",
"Id": "30285",
"ParentId": "29699",
"Score": "19"
}
}
] |
{
"AcceptedAnswerId": "30285",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T17:52:31.830",
"Id": "29699",
"Score": "11",
"Tags": [
"scala",
"graph"
],
"Title": "BFS and DFS in Scala"
}
|
29699
|
<p>How can I optimize my jQuery? I remove the extra code to attach click event to the header tags.</p>
<pre><code>$("#dnn_htmlPan1.htmlPan").find(":header").click(function () {
$("#dnn_htmlPan1").find("p").slideToggle("slow");
});
$("#dnn_htmlPan2.htmlPan").find(":header").click(function () {
$("#dnn_htmlPan2").find("p").slideToggle("slow");
});
$("#dnn_htmlPan3.htmlPan").find(":header").click(function () {
$("#dnn_htmlPan3").find("p").slideToggle("slow");
});
$("#dnn_htmlPan4.htmlPan").find(":header").click(function () {
$("#dnn_htmlPan4").find("p").slideToggle("slow");
});
$("#dnn_htmlPan5.htmlPan").find(":header").click(function () {
$("#dnn_htmlPan5").find("p").slideToggle("slow");
});
</code></pre>
|
[] |
[
{
"body": "<p>Without knowing what your elements are or the html around them, i would say just combine the id's into one selector and use $(this).find in the click function. Example:</p>\n\n<pre><code>$(\"#id1, #id2, #id3\").find(':header').click(function(){\n $(this).find('p').slideToggle('slow')l\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T23:41:26.633",
"Id": "29713",
"ParentId": "29708",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29713",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:41:29.573",
"Id": "29708",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to attach click to header child without reusing the code?"
}
|
29708
|
<p>I am reading a book on DSA, and the author explains how to generate the permutation of strings using recursion. I want to know if there are better ways of doing the same, unless this is the best solution. Also, could someone help me understand the time-complexity of this algorithm? Recursion is something I use very rarely but am trying to learn about now.</p>
<pre><code>public class Anagrams {
private char[] chArray;
private int size;
private static int count;
public Anagrams(String anagramString, int size) {
if (size <= 0) {
System.out.println("Please enter a valid String");
}
chArray = anagramString.toCharArray();
this.size = size;
}
public static void main(String args[]) {
String str = "dogs";
Anagrams anagramGenerator = new Anagrams(str, str.length());
anagramGenerator.generateAnagrams(str.length());
}
public void generateAnagrams(int newSize) {
if (newSize == 1)
return;
for (int i = 0; i < newSize; i++) {
generateAnagrams(newSize - 1);
if (newSize == 2)
displayWord();
rotate(newSize);
}
}
private void rotate(int newSize) {
// TODO Auto-generated method stub
int position = size - newSize;
char tempCh = chArray[position];
int i;
for (i = position + 1; i < size; i++) {
chArray[i - 1] = chArray[i];
}
chArray[i - 1] = tempCh;
}
private void displayWord() {
// TODO Auto-generated method stub
String word = "";
count++;
for (int i = 0; i < chArray.length; i++) {
word += chArray[i];
}
System.out.println(count + ")" + word);
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>The <code>rotate</code> function which reverses a sequence can be done in O(n/2) strictly it is still O(n) but when it is used a lot, then it's better to optimize it.</li>\n<li>The <code>displayWord</code> function is O(n²). It can be made constant by passing the array as argument. If StringBuilder is used with append, it can be O(n).</li>\n<li><p><code>generateAnagrams</code> G(n) = O(1) + (n-1)*(G(n-1) + O(n) + O(1)). This complexity is kind of difficult to calculate, I ran it on <a href=\"http://www.wolframalpha.com/input/?i=a%28n%29%20=%20%28n-1%29%20%2a%20%28a%28n-1%29%20%2b%20n%29,%20%20a%281%29%20=%201\" rel=\"nofollow\">WolphramAlpha</a>. If you understand the Gamma function, then go ahead and click. I did narrow down the complexity to Ω(<strong>e</strong>.n!) (<strong>NB:</strong> not <em>theta</em>, or <em>Big O</em> but <em>Omega</em>) by running the following code and <a href=\"http://oeis.org/wiki/Number_of_arrangements#Comparison_of_derangement.2C_permutation_and_arrangement_numbers\" rel=\"nofollow\">OEISWiki</a>;</p>\n\n<p><strong>e</strong> is the exponential constant and n! is the factorial of n.</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>bool compute(int i, int &c ){\n c++;\n if(i==0) return true;\n for(int j=0; j<i; j++)\n compute(i-1,c);\n return true;\n}\n\nint main(){\n for(int i=0; i<11; i++){\n int c = 0;\n compute(i,c);\n cout<<c<<\", \";\n }\n}\n</code></pre>\n\n<p><strong>UPDATE</strong> Your code doesn't treat the case where a character occurs more than once. For example it returns 120 for <code>\"dogss\"</code> instead of 60.</p>\n\n<p>Permutations can be generated by searching for the next array lexicographically greater than the current one, containing the same characters. Check <a href=\"http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order\" rel=\"nofollow\">Wikipedia</a>. This is used in C++i in the function <a href=\"http://msdn.microsoft.com/en-us/library/e7d3xas6.aspx\" rel=\"nofollow\"><code>next_permutation</code></a>. Given a string <code>\"dogs\"</code>, the next permutation would be <code>dosg</code>. Which means that if we are to sort an array containing all possible permutation of the word <code>dogs</code>, we will get the same order given by this method. The problem with this method is that the array/word must be sorted in order to get all possible permutation, if not then the function will print out permutations starting only from the current word.</p>\n\n<p>The algorithm is simple</p>\n\n<pre><code>1. if length of word is 0 or 1 then return false\n2. if not\n3. from the right, find the first two ascending characters\n4. if found, take the left one\n5. from the right, find the first character greater than it,\n6. swap them\n7. then reverse all characters from the right one to the end\n8. return true\n9. if not found, return false\n</code></pre>\n\n<p>Observe that after line <code>3</code>, the sequence formed from the <em>right one</em> to the far left is a non increasing sequence, so after the swap in <code>6</code>, there is a need to reverse to keep the order of permutation strict (we are looking for the next greater permutation after all). In the worst case, supposing that the ascending characters are always found int far right, the the complexity of this algorithm is O(n.n!), since it is called n! times</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class Permutation {\n private char[] word;\n private long count;\n\n public Permutation(char[] _word) {\n word = _word;\n count = 0;\n }\n\n boolean permute() {\n while (nextPermutation())\n ;\n return true;\n }\n\n void print() {\n System.out.print(++count);\n System.out.print(\". \");\n System.out.println(word);\n }\n\n boolean nextPermutation() {\n print();\n int next = word.length;\n if (next-- <= 1)\n return false;\n for (;;) {\n int next1 = next;\n if (word[--next] < word[next1]) {\n int mid = word.length;\n for (; !(word[next] < word[--mid]);)\n ;\n swap(next, mid);\n reverse(next1, word.length);\n return true;\n }\n if (next == 0)\n return false;\n }\n }\n\n boolean swap(int left, int right) {\n char c = word[right];\n word[right] = word[left];\n word[left] = c;\n return true;\n }\n\n boolean reverse(int first, int last) {\n // reverse elements in [first, last)\n for (; first != last && first != --last; ++first)\n swap(first, last);\n return true;\n }\n\n public static void main(String args[]) {\n String str = \"dogs\";\n char[] word = str.toCharArray();\n Arrays.sort(word);\n Permutation permuteWord = new Permutation(word);\n permuteWord.permute();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-08T15:05:23.153",
"Id": "30960",
"ParentId": "29712",
"Score": "2"
}
},
{
"body": "<p><strong>Be consistent</strong></p>\n\n<p>The most important advice I could give you is be consistent. Be consistent with your naming convention, the placement of brackets and everything else. Why ? Because even if you're doing something wrong you will be predictable, and that is what make things faster when reviewing.</p>\n\n<pre><code> if (size <= 0) {\n System.out.println(\"Please enter a valid String\");\n } \n</code></pre>\n\n<p>vs</p>\n\n<pre><code> if (newSize == 1)\n return;\n</code></pre>\n\n<p>Same situation, an <code>if</code> condition and one line of code if the condition is good. Why one have brackets and the other one don't have it ? In this particular case, always use brackets. It's more readable, if you add a line of code you don't have to add brackets and it will probably reduce the chance to have bugs.</p>\n\n<p><strong>Constructor</strong></p>\n\n<p><code>public Anagrams(String anagramString, int size)</code> </p>\n\n<p>You already using <code>String</code> as parameter, why do you have <code>size</code> ? When you call your constructor, you're passing <code>str.lenght()</code>. I suggest that you drop the second argument and just call the <code>length</code> directly in your constructor.</p>\n\n<pre><code>public Anagrams(String anagramString) {\n if (size <= 0) {\n System.out.println(\"Please enter a valid String\");\n }\n chArray = anagramString.toCharArray();\n this.size = anagramString.lenth();\n\n}\n</code></pre>\n\n<p>Another important point, you're checking if the <code>size <= 0</code> and print that you must enter a valid <code>String</code>, but you don't do nothing else. The program will go on in an invalid state. You could throw an exception that specify that the length of the <code>String</code> must be greater than 0. </p>\n\n<p><strong>Comments</strong></p>\n\n<p>Never leave <code>// TODO Auto-generated method stub</code> comments. It's just noise in the code, and could lead to people thinking that your code is somewhat not finished. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:38:59.940",
"Id": "42801",
"ParentId": "29712",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T23:29:38.440",
"Id": "29712",
"Score": "6",
"Tags": [
"java",
"algorithm",
"recursion",
"combinatorics",
"complexity"
],
"Title": "Permutation of given string"
}
|
29712
|
<p>I'm a budding JavaScript programmer, working on an exercise where I'm trying to create two classes (<code>Books</code> and <code>Shelf</code>) and need to have a shelf know what books are on it. I'm pretty new to OOP so I know I'm missing a crucial step (or three). I probably already ran off the rails, but any point in the right direction would be greatly appreciated.</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Library</title>
</head>
<body>
<script type="text/javascript">
//The Books
function Books(title, enshelf, unshelf) {
this.title = title;
this.enshelf = enshelf;
this.unshelf = unshelf;
}
var bookA = new Books('The War of 1812',true,false);
var bookB = new Books('Watership Down',false,true);
var bookC = new Books('Sand Cake',true,false);
//The Shelves
function Shelf (shelfNumber, shelfName) {
this.shelfNumber = shelfNumber;
this.shelfName = shelfName;
}
var shelf100 = new Shelf('100','History');
var shelf200 = new Shelf('200','Fiction');
var shelf300 = new Shelf('300','Childrens');
var shelfTotal = [shelf100, shelf200, shelf300];
var bookInventory = [bookA, bookB, bookC];
// List all the books in the library
function displayBooks(book) {
document.write(book.title + "<br>" + book.shelfName +"<br><br>");
}
//Show total number of books
var showBooks = function() {
for(i=0; i < bookInventory.length; i++) {
displayBooks(bookInventory[i]);
}
}
showBooks();
document.write("Total number of books: " + bookInventory.length);
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>There are multiple ways of handling this. If you can pass the Books you want to the Shelf object, that would be probably one of the easiest methods.</p>\n\n<pre><code>//The Shelves\nfunction Shelf (shelfNumber, shelfName) {\n this.shelfNumber = shelfNumber;\n this.shelfName = shelfName;\n this.books = new Array();\n this.addBook = function(book) {\n this.books[this.books.length] = book;\n }\n this.displayBooks = function() {\n for(i=0; i < this.books.length; i++) {\n displayBooks(this.books[i]);\n }\n }\n}\n\n// then you can use it like this...\n\nshelf100.addBook(bookA);\nshelf100.addBook(bookB);\nshelf100.addBook(bookC);\n\nshelf100.displayBooks();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T08:21:42.853",
"Id": "29715",
"ParentId": "29714",
"Score": "3"
}
},
{
"body": "<p>First off, naming. Objects tend to be singular in form. Thus, the names of your objects should be singular in form. You should name them <code>Book</code> and <code>Shelf</code>, since there's one book per <code>Book</code> instance, and one shelf per <code>Shelf</code> instance.</p>\n\n<p>You got the constructors right, with a bit of correction needed.</p>\n\n<p>A book only needs to care about itself. Thus, only book data should be in the instance, like the title:</p>\n\n<pre><code>function Book(title) {\n this.title = title;\n\n //explained later\n this.currentShelf;\n}\n\nvar book = new Book('The War of 1812');\n</code></pre>\n\n<p>The shelf concerns about itself, and the books it contains. Basically, if you look at the shelf, it's the one that \"manages\" the books inside it. You could have the book identify where it is, but you should delegate the operations to one of the objects instead of have them in both. I'll explain in the following sections, under methods.</p>\n\n<pre><code>function Shelf (number, name) {\n this.books = [];\n this.number = number;\n this.name = name;\n}\n\nvar shelf = new Shelf(1,'History');\n</code></pre>\n\n<p>Now, operations of books and shelves. In prototypal OOP, <em>everything</em> is public. Thus, you don't need setters and getters unless you need intermediate operations like validation.</p>\n\n<pre><code>shelf.books.push(book); //adding a book\nshelf.books[i] //should be book\n</code></pre>\n\n<p>If you want to declare methods for accessing and operating, the formal way in prototypal OOP is to declare it in the prototype. This has the advantage of being shared across instances. This means that instances use the same, single function and not one function each. This saves memory.</p>\n\n<pre><code>Shelf.prototype.addBook = function(book){\n //this refers to the instance\n this.books.push(book)\n}\n\nShelf.prototype.getBook = function(i){\n return this.books[i];\n}\n\n//all instances of Shelf have an addBook\nshelf.addBook(book);\n\n//all instances of Shelf have a getBook\nshelf.getBook(0);\n</code></pre>\n\n<p>Now back to the part where book should know where it is. Think of it in a heirarchy, shelves manage book. But book needs to know where it is, so we set <code>addBook</code> to set it for us. Note that <code>addBook</code> is a method of <code>Shelf</code>. And so, redefining <code>addBook</code>:</p>\n\n<pre><code>Shelf.prototype.addBook = function(book){\n //assigning the book the number of the current shelf it's in\n book.currentShelf = this.number;\n //you might search the array for book before adding it to avoid duplicate\n this.books.push(book);\n}\n</code></pre>\n\n<p>So what we did up there is have shelf add the book, as well as additional info. <code>getBook</code> could also do the same thing with de-shelfing.</p>\n\n<pre><code>Shelf.prototype.getBook = function(i){\n var book = this.books.splice(i,1)[0]; //remove a book from the array\n if(!book) return; //book at index might not exist\n book.currentShelf = null; //indicate book not in a shelf\n return book;\n}\n</code></pre>\n\n<p>For a collection of shelves, you can create another object similar to shelves which collect shelves, like a <code>Library</code> object. This object would only concern itself and it's collection of shelves.</p>\n\n<p>As for displaying the shelves, this is a job for the View. You should read more about <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a> to properly segregate your code into concerns. That way, your code won't be a mangled mess when it grows.</p>\n\n<p>That's pretty much all the formal OOP I can dish out. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:09:30.130",
"Id": "29725",
"ParentId": "29714",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29715",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T04:27:50.097",
"Id": "29714",
"Score": "2",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "How to get two JavaScript classes to talk to each other?"
}
|
29714
|
<p>Here is my simple ticketing system:</p>
<pre><code> <?php
session_start();
session_id();
ob_start();
require("../configuration/config.php");
$GetTickets = $con->query("SELECT * FROM tickets WHERE open='true'");
if(!$_SESSION['Admin']) {
header('Location: login.php'); exit();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> ticketExpress | Admin </title>
<link rel='stylesheet' href='../assets/css/style.css'>
</head>
<body>
<div id='containerAdmin'>
<h1> <img class='logo' src='../assets/images/logo.png' width='200' height='43'> </h1> <a href='?logout' class='logout'> Logout </a>
<h3> Open Tickets </h3>
<hr />
<?php
while($TicketInfo = $GetTickets->fetch_object()) {
$Subject = $TicketInfo->Subject;
if(strlen($Subject)>50) {
$Subject = substr($Subject,0,50)."...";
} else {
$Subject = $TicketInfo->Subject;
}
echo "<div id='ticket'>".$Subject ."<a href='?delete=$TicketInfo->ID'><img style='float:right'src='../assets/images/delete.png' width='15px' height='15px'></a><a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='?close=$TicketInfo->ID'> Close </a><span style='float:right; margin-right:10px;' id='responseMsg'> </span></div>";
}
if(isset($_GET['delete'])) {
$ID = $_GET['delete'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
ajax.open('POST','delete.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg').innerHTML = ajax.responseText;
}
}
ajax.send('delete=$ID');
</script>
";
}
if(isset($_GET['logout'])) {
session_destroy();
header('Location: login.php');
}
if(isset($_GET['close'])) {
$ID = $_GET['close'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
ajax.open('POST','close.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg').innerHTML = ajax.responseText;
}
}
ajax.send('close=$ID');
</script>
";
}
?>
<br />
</div>
</body>
</html>
</code></pre>
<p>Could you give me tips on improving the performance of my script? I've noticed that it takes some time to receive a response, so performance can definitely be further improved. I've been doing PHP for the last 8 months or so and am still a newbie.</p>
|
[] |
[
{
"body": "<p>Profiling is not an art, it's a science.</p>\n\n<p>You need tools to profile your application, and know what eats up performance. It's only this way you'll be able to improve the performance.</p>\n\n<p>For PHP, what's usually used is the xdebug profiler.</p>\n\n<p>w.r.t your code, it's quite small. The only thing that can be slow is the SQL request.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:00:46.640",
"Id": "47036",
"Score": "0",
"body": "Hey, thanks for the response! What should I consider to improve the sql request performance? Also, what do is your opinion on New Relic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:02:35.460",
"Id": "47037",
"Score": "0",
"body": "@Exwolf New Relic is another system for this, and is nice for long-running performance checking. It's also an external service, so it might not always suit your needs. When I need a one-shoot profiling session, I just go with xdebug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:03:02.883",
"Id": "47038",
"Score": "0",
"body": "@Exwolf regarding the SQL performance, first check out this is the real issue. Then, go on db.stackexchange.com if you want this kind of help :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:52:00.240",
"Id": "47047",
"Score": "0",
"body": "`while(true);` is pretty small too but it's working really slowly for me (smallness of code has nothing to do with perf is the point)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:57:30.997",
"Id": "47050",
"Score": "0",
"body": "@Esailija just saying that the code is pretty small to not involve a huge number of lines to bootstrap a framework or whatever."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T09:53:42.103",
"Id": "29718",
"ParentId": "29717",
"Score": "1"
}
},
{
"body": "<p>Let me point out some issues I see in your code</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/29009/21181\">Separate the layout from the logic</a> and get rid of the output puffer.</li>\n<li>Calling <code>session_id();</code> has no effect,</li>\n<li>Storing a admin flag in the session is only slightly better than adding a GET parameter <code>admin=1</code>. In other words this is no secure solution.</li>\n<li>Florian is right, run a debugger/profiler to find your performance issues. Check <a href=\"http://php.net/manual/de/function.microtime.php\" rel=\"nofollow noreferrer\"><code>microtime()</code></a> as a lightweight profiler.</li>\n</ul>\n\n<p><strong>Update</strong></p>\n\n<p>I splitted your code into two files. And removed the ajax call, as it is useless do create client code on the server to issue a new request to do something on the server. Just do it right away (Is not the best approach in general. Google for <strong>GET after POST</strong> or how to update the page after a <strong>AJAX call without reloading the whole page</strong>.)</p>\n\n<pre><code><?php\nsession_start();\nif(!$_SESSION['Admin']) {\n header('Location: login.php');\n exit();\n}\n\nif(isset($_GET['logout'])) {\n session_destroy();\n header('Location: login.php');\n exit();\n}\n\nrequire(\"../configuration/config.php\");\n$GetTickets = $con->query(\"SELECT * FROM tickets WHERE open='true'\");\n\n$tickets=array();\n$messages=array();\nwhile($TicketInfo = $GetTickets->fetch_object()) {\n $Subject = $TicketInfo->Subject;\n if(strlen($Subject)>50) {\n $Subject = substr($Subject,0,50).\"...\";\n } else {\n $Subject = $TicketInfo->Subject;\n $tickets[$TicketInfo->Id]=$Subject\n $messages[$TicketInfo->Id]='';\n}\n\nif(isset($_GET['delete'])) {\n $ID = $_GET['delete'];\n //TODO delete\n $messages[$ID]='Deleted';\n}\n\nif(isset($_GET['close'])) {\n $ID = $_GET['close'];\n //TODO close\n $messages[$ID]='Closed';\n}\n\ninclude \"template.php\"\n</code></pre>\n\n<p>template.php</p>\n\n<pre><code><!DOCTYPE HTML>\n<html>\n<head>\n <title> ticketExpress | Admin </title>\n <link rel='stylesheet' href='../assets/css/style.css'> \n</head>\n<body>\n<div id='containerAdmin'>\n<h1> <img class='logo' src='../assets/images/logo.png' width='200' height='43'> </h1> <a href='?logout' class='logout'> Logout </a>\n<h3> Open Tickets </h3>\n<hr />\n<?php foreach ($tickets as $id=>$subject):?>\n <div id='ticket'>\n <?=$subject?>\n <a href='?delete=<?=$id?>'><img style='float:right'src='../assets/images/delete.png' width='15px' height='15px'></a>\n <a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='?close=<?=$id?>'> Close </a>\n <span style='float:right; margin-right:10px;' id='responseMsg'><?=$messages[$id]?></span>\n </div>\n<?php endforeach?>\n<br />\n</div>\n</body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:05:24.427",
"Id": "47039",
"Score": "0",
"body": "Hey, what would a more secure alternative to storing the admin flag be? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:50:48.820",
"Id": "47042",
"Score": "0",
"body": "Right now I only have a nice [german tutorial](http://www.phpbuddy.eu/login-systeme-einfach-bis-profi.html) on this topic, but I guess Google will help you in translating or find a similar English one. Actually the login part is not that critical right now. As a first step you should focus on the layout/logic separation. This will also help you profiling your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T11:04:41.637",
"Id": "47043",
"Score": "0",
"body": "Should I use a templating engine such as Smarty? Or just use str_replace and make my own simple templating engine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T11:37:32.157",
"Id": "47044",
"Score": "1",
"body": "Don't make a templating engine at all...\nPhp is a template engine as is. Simply create all your variables and then include the correct file with html + php echo statements"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:15:41.200",
"Id": "47045",
"Score": "0",
"body": "@Exwolf I updated my post showing how to split your code using a separate template file."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:03:01.937",
"Id": "29719",
"ParentId": "29717",
"Score": "0"
}
},
{
"body": "<p>A few quick tips: </p>\n\n<ul>\n<li>premature optimization is the root of all evil</li>\n<li>use a profiling tool</li>\n<li>premature optimization is the root of all evil</li>\n<li>Don't echo markup, close php, write markup, open php tag again</li>\n<li>premature optimization is the root of all evil</li>\n<li>Dont query the DB, if you might have to change <code>header('Location:...')</code> a few lines further down. If you're going to have to redirect, do so ASAP.</li>\n<li>premature optimization is the root of all evil</li>\n<li>Avoid globals, they're error prone, hellish to debug and generally evil, but not as evil as premature optimization</li>\n<li>premature optimization is the root of all evil</li>\n</ul>\n\n<p>All in all, there's not enough code yet to squeeze any meaningful performance gain out of it. Not by altering the code alone, anyway.<br/>\nIf you do decide to use a profiling tool, also look into caching (google APC), and try your hand at bytecode caching. See how many ms you can shave off that way, but always remind yourself of one thing:</p>\n\n<ul>\n<li>premature optimization is the root of all evil</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:48:35.850",
"Id": "29730",
"ParentId": "29717",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T09:43:48.023",
"Id": "29717",
"Score": "1",
"Tags": [
"php",
"performance",
"beginner",
"mysql"
],
"Title": "Simple ticketing system"
}
|
29717
|
<p>This is my first MYSQL schema for caching location data (co-ordinates to place names) and referencing it with a country. </p>
<p>I was wondering what everyones feedback was on it, did I do a good job?</p>
<pre><code>CREATE TABLE location (
id INT AUTO_INCREMENT PRIMARY KEY,
locality VARCHAR(20),
administrative_area_level_1 VARCHAR(20),
administrative_area_level_2 VARCHAR(20),
administrative_area_level_3 VARCHAR(20),
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17),
updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE country (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
iso VARCHAR(20),
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17),
updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T17:26:52.393",
"Id": "52497",
"Score": "1",
"body": "are these two tables linked? I don't see a Foreign key or anything to link the tables together. I do see 2 columns that have the same name in both tables?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T05:09:47.980",
"Id": "88534",
"Score": "0",
"body": "Idem. Your query is ambiguous for Code Review. I would personally expect a `country.id` column as foreign key in `location` but may or may not be the case depending on your schema design."
}
] |
[
{
"body": "<p>For all it's worth, and this is pretty old but for the sake of clearing unanswered reviews, here is my take:</p>\n\n<ul>\n<li><p><code>id INT AUTO_INCREMENT PRIMARY KEY,</code></p>\n\n<p>I find that being more specific in column names makes the code easier to work with, especially when you are using <code>JOIN</code> and table aliases. Suppose the following:</p>\n\n<pre><code>SELECT l.*, c.*\nFROM location AS l\nLEFT JOIN country AS c\nON l.loc = c.loc\n</code></pre>\n\n<p>The result set would have column headers as <code>l.id</code> and <code>c.id</code> unless you took the time to make column aliases for everything. If your columns were instead named <code>location_id</code> and <code>country_id</code> the result set would be much easier to read to someone who is not a database programmer. </p></li>\n<li><p><code>name VARCHAR(20)</code></p>\n\n<p>I think 20 may be a bit short for country name. For instance: </p>\n\n<pre><code>SELECT CHAR_LENGTH('United States of America');\n</code></pre>\n\n<p>Result: 24</p></li>\n</ul>\n\n<p>Other than that I think it looks fine. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T22:53:24.373",
"Id": "51339",
"ParentId": "29724",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T11:22:36.040",
"Id": "29724",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "First Schema for Location and Countries"
}
|
29724
|
<blockquote>
<p>the Encoding scheme is given below:</p>
<p>Don't replace the characters in the even places. Replace the characters in the odd places by their place numbers . and if they exceed 'z', then again they will start from 'a'.</p>
<p>example: for a message "hello" would be "ieolt" and for message "maya" would be "naba"</p>
<p>how many lines of code [minimum] do we have to write in order to encode a lengthy string in <strong><em>python</em></strong> in the above format.?</p>
</blockquote>
<p>mycode is given below:</p>
<pre><code>def encode(msg):
encoded_message = ""
letters = "abcdefghijklmnopqrstuvwxyz"
index_of_msg = 0
for char in msg.lower():
if char.isalpha():
if index_of_msg%2 == 0 :
encoded_message += letters[((letters.rfind(char) )+ (index_of_msg+1))%26] # changed msg.rfind(char) to index_of_msg
else:
encoded_message += char
else:
encoded_message += char
index_of_msg +=1
return encoded_message
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:04:11.447",
"Id": "47051",
"Score": "1",
"body": "The examples seem strange, by the way. Does \"replace by their place number\" mean \"replace by the letter corresponding to their place number?\". And if yes, for ``hello``, shouldn't the first letter be replaced by ``a`` (place == 1)? **Edit:** oh, I get it, you *add* the place number to the letter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:08:11.327",
"Id": "47052",
"Score": "0",
"body": "@Bogdan in `hello` as h is in odd place ie 1 thus, it moved by its place number 1 ie h+1 = i\nSorry if my actual question confused you"
}
] |
[
{
"body": "<p>Here's a one liner for you (since the question asks for the minimum number of lines):</p>\n\n<pre><code>encode = lambda s: \"\".join([(c if (i+1) % 2 == 0 else chr(ord('a') + (ord(c) - ord('a') + i + 1) % 26)) for i, c in enumerate(s)])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:20:50.710",
"Id": "47054",
"Score": "0",
"body": "thnx fr tht @Bogdan?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:22:03.433",
"Id": "47056",
"Score": "0",
"body": "What if i have to get input from a file and output the enocoded string to another file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:25:26.197",
"Id": "47057",
"Score": "0",
"body": "@Sandeep: um, you would write another function that opens the file and reads its contents? The initial question did not say anything about files, and, in any case, the encoding function should not concern itself with file operations (easier to grasp, easier to test etc)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:28:07.773",
"Id": "47058",
"Score": "0",
"body": "yes its perfectly okay for me with out files, but im just curious about it.\nanyway thanks for one liner @Bogdan"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:17:02.453",
"Id": "29731",
"ParentId": "29727",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29731",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:29:26.660",
"Id": "29727",
"Score": "2",
"Tags": [
"python",
"strings"
],
"Title": "Python abilities on strings"
}
|
29727
|
<p><strong>The question is:</strong></p>
<p>Write the following pseudo in assembler code:</p>
<pre><code>if portC bit 3 == 0
(switch content of var1 and var2)
else
(add var1 with var2 and place the result in var1)
</code></pre>
<p><strong>My answer is:</strong></p>
<pre><code>btfsc portC,3
goto add
movf var1,w
movwf temp
movf var2,w
movwf var1
movf temp,w
movwf var2
return
add movf var2,w
addwf var1,f
</code></pre>
<p>Since I dont know the right answer, can you please help me and tell me if I wrote it correct?</p>
|
[] |
[
{
"body": "<p>A general disclaimer to this answer should be that I don't know the hardware you're working with, but most of this should be applicable to many architectures.</p>\n\n<h2>Potential optimization #1</h2>\n\n<p>Your code seems correct, but you can make it shorter and potentially more efficient by moving the first memory load before the branch:</p>\n\n<pre><code>movf var1, w ; We're going to load one of the variables anyway\n\nbtfsc portC, 3\ngoto add\n\nmovwf temp\nmovf var2, w\nmovwf var1\nmovf temp, w\nmovwf var2\nreturn\n\nadd addwf var2, f\n</code></pre>\n\n<p>Performing the load before the branch <em>might</em> mean the branch instruction could be executed at the same time as the load, since they don't share any data.</p>\n\n<h2>Potential optimization #2</h2>\n\n<p>Using a <a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"nofollow\">XOR swap</a> should be more efficient, like so:</p>\n\n<pre><code>movf var1, w ; load from var1 to w\nxorwf var2, w ; w = var1 xor var2\nxofwf var2, f ; var2 = w xor var2 = (var1 xor var2) xor var2 = var1\nxorwf var1, f ; var1 = w xor var1 = (var1 xor var2) xor var1 = var2\n</code></pre>\n\n<p>This should have several advantages:</p>\n\n<ol>\n<li>There is no temporary variable and therefore no reads or writes are associated with it.</li>\n<li>The first XOR doesn't perform a memory write so it should be completed faster.</li>\n<li>No moving memory around until the variables are assigned their final values, so if the hardware is able to cache the values of var1 and var2 from the first two instructions, the last two could gain a performance boost.</li>\n</ol>\n\n<p>I should state again that I don't know the hardware, so this is mostly educated speculation, but my code should be faster even without assumptions 2 and 3.</p>\n\n<p>Furthermore, there's nothing stopping you from combining both ideas, of course. You probably should.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:13:13.617",
"Id": "47060",
"Score": "0",
"body": "I see, that is an interesting method. But was the one that I had written correct too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:22:25.020",
"Id": "47061",
"Score": "0",
"body": "@visaxx: Added a few more thoughts. I just looked up the assembly language reference for your device and the code you wrote does seem correct."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:06:54.343",
"Id": "29736",
"ParentId": "29728",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T12:37:58.373",
"Id": "29728",
"Score": "1",
"Tags": [
"assembly"
],
"Title": "Assembler PIC programming, is this correct?"
}
|
29728
|
<p>I am trying to write a simple version of the unix tail utility in haskell to improve my understanding of monads. Here is what I have now. I am pretty sure that this is not quite "Haskell enough" yet. Can you please help me improve my code?</p>
<pre><code>import System.Environment
import System.Exit
import Control.Monad
main = getArgs >>= (parse' (10, [])) >>= \ (n_lines, ss) ->
putStr $ concatMap (tailFile n_lines) ss
tailFile :: Int -> (FilePath, String) -> String
tailFile n_lines (f, c) =
"==> " ++ f ++ " <==\n" ++
(unlines.reverse.(take n_lines).reverse.lines) c
parse' :: (Int, [(FilePath, String)])
-> [String]
-> IO (Int, [(FilePath, String)])
parse' _ ("-h":_) = putStrLn "usage: " >> exit
parse' _ ("-v":_) = putStrLn "version: 0.1" >> exit
parse' (_, ss) ("-n":num:f) = parse' (read num, ss) f
parse' (n, ss) (f:fs) = do
contents <- readFile f
parse' (n, ss ++ [(f,contents)]) fs
parse' (x, ss) [] = return (x, ss)
exit = exitWith ExitSuccess
die = exitWith (ExitFailure 1)
</code></pre>
|
[] |
[
{
"body": "<p>My first approach is to map the arguments to a list of IO actions and then execute them:</p>\n\n<pre><code>import Control.Monad\nimport System.Environment\n\nlastLines :: Int -> String -> [String]\nlastLines n = reverse.take n.reverse.lines\n\nprintLines :: [String] -> IO ()\nprintLines = flip forM_ $ putStrLn\n\nreadLastLines :: Int -> FilePath -> IO [String]\nreadLastLines n f = readFile f >>= return . (++) [\"==>\" ++ f ++ \"<==\"] . lastLines n\n\nargsToActions :: [String] -> [IO ()]\nargsToActions (\"-h\":_) = [print \"Usage\"]\nargsToActions (\"-v\":_) = [print \"V 1.0\"]\nargsToActions (\"-n\":n:f:_) = [readLastLines (read n) f >>= printLines]\nargsToActions (f:fs) = [readLastLines 10 f >>= printLines] ++ argsToActions fs\nargsToActions [] = []\n\nmain :: IO ()\nmain = getArgs >>= sequence_ . argsToActions\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-12T16:30:05.963",
"Id": "32602",
"ParentId": "29732",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:21:15.493",
"Id": "29732",
"Score": "5",
"Tags": [
"haskell"
],
"Title": "Unix tail in haskell"
}
|
29732
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.