body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I am not a big fan of JS, but have been forced to use it in this situation for various reasons.</p>
<p>My task: Download a URL to a target file, and update another part of the application with the current percentage.</p>
<p>I've run jslint and jshint over the code, and it seems happy, but I am sure there is still plenty of suboptimal stuff in my code. My code currently looks like this:</p>
<pre><code>Match.prototype.downloadURL = function (url, target, next) {
winston.info("Downloading url %s to %s", url, target);
var tmpFilename = target + ".tmp",
tmpFile = fs.createWriteStream(tmpFilename);
http.get(url, function (resp) {
var fullSize = +resp.headers["Content-Length"],
currentSize = 0,
currentPercentage = -1;
// Write the file
resp.pipe(tmpFile);
resp.on('end', function () {
tmpFile.close();
this.registerDownloadFinished();
fs.rename(tmpFilename, target, function (err) {
if (err !== null) {
return next(err);
}
next(null, target);
});
});
// Update when we hit a new percentage
resp.on('data', function (chunk) {
currentSize += chunk.length;
var percentage = parseInt(currentSize / fullSize * 100, 10);
if (percentage === currentPercentage) {
return;
}
currentPercentage = percentage;
this.updateDownloadingPercentage(percentage);
});
});
};
</code></pre>
<p>Problems I can see:</p>
<ol>
<li><code>updateDownloadingPercentage</code> and <code>registerDownloadFinished</code> are networked operations; I should probably be doing something to make sure these things arrive in order</li>
<li>I have a feeling I should be checking for errors a lot more; <code>createWriteStream</code> can fail, so where do I get its error message from.</li>
</ol>
<p>Again, I only ask because I am a very poor JavaScript coder. Please enlighten me as to any way I can improve this snippet.</p>
|
[] |
[
{
"body": "<p>From a once over and reading some docs:</p>\n\n<ul>\n<li>You need a <code>resp.on('error', function () {}</code> to deal with http errors</li>\n<li>You need a <code>tmpFile.on('error', function () {}</code> to deal with fs/stream errors</li>\n<li><code>tmpFile</code> is an unfortunate name, i would call it maybe <code>tmpStream</code> or <code>tmpFileStream</code></li>\n<li>You use both single and double quotes for strings, stick to one, preferably single quotes</li>\n<li><code>resp</code> should be <code>res</code> ( standard in Node ), or <code>response</code>, it bugs me every time I read the code ;)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:28:14.403",
"Id": "72618",
"Score": "0",
"body": "Death to single quotes :) Thanks for this, makes sense. Of course, I now have additional questions, but at least my code is correct now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:57:02.657",
"Id": "42170",
"ParentId": "41983",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42170",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:39:43.913",
"Id": "41983",
"Score": "8",
"Tags": [
"javascript",
"beginner",
"node.js",
"http"
],
"Title": "Download a file and update the current downloaded percentage"
}
|
41983
|
<p>I have created a simple class that maintains a pool (with maximum size) of objects. It acts like a connection pool (that is where the name came from - initially it was used just to maintain a pool of SMTP connections). When an item is retrieved - if the pool is not empty, a value is retrieved from it; if it is empty, then if the maximum number of objects have not been allocated, a new one is created.</p>
<p>The usage as it currently stands is:</p>
<pre><code>/// <summary>
/// A generic object pool for any data. A pool is automatically created based on the data type.
/// If the pool size is currently exceeded then the task will wait until an object is returned from the pool.
/// </summary>
public static class ConnectionPool
{
/// <summary>
/// Sets the maximum pool size. This method is *NOT* thread-safe and has to be called before the first item is retrieved from the pool.
/// </summary>
public static void SetPoolSize<TValue>(int maximumSize)
where TValue : class
{
ConnectionPoolWrapper<TValue>.SetPoolSize(maximumSize);
}
/// <summary>
/// Retrieves a new item from the pool. If the pool is empty and the maximum number of items are active, the task will delay
/// until an item is freed.
/// </summary>
/// <param name="initializer">Delegate that is used to create a new item if the pool is empty but maximum number of items have not been reached.</param>
public static Task<ConnectionPoolWrapper<TValue>> RetrieveAsync<TValue>(Func<TValue> initializer)
where TValue: class
{
return ConnectionPoolWrapper<TValue>.RetrieveFromPoolAsync(initializer);
}
/// <summary>
/// Retrieves a new item from the pool. If the pool is empty and the maximum number of items are active, the task will delay
/// until an item is freed.
/// </summary>
/// <remarks>The default constructor is used to create new objects when needed.</remarks>
public static Task<ConnectionPoolWrapper<TValue>> RetrieveAsync<TValue>()
where TValue : class, new()
{
return ConnectionPoolWrapper<TValue>.RetrieveFromPoolAsync(() => new TValue());
}
}
/// <summary>
/// An item in the object pool.
/// </summary>
public sealed class ConnectionPoolWrapper<TValue> : IDisposable
where TValue : class
{
/// <summary>
/// Contains the currently allocated and free objects.
/// </summary>
private static System.Collections.Concurrent.ConcurrentStack<TValue> _connectionPool = new System.Collections.Concurrent.ConcurrentStack<TValue>();
/// <summary>
/// The locking mechanism that makes sure only certain number of items can be allocated in parallel.
/// </summary>
private static volatile System.Threading.SemaphoreSlim _counter = null;
/// <summary>
/// The object on which a lock is created while <c>_counter</c> is initialized.
/// </summary>
private static object _syncRoot = new object();
/// <summary>
/// Sets the maximum pool size. This method is *NOT* thread-safe and has to be called before the first item is retrieved from the pool.
/// </summary>
public static void SetPoolSize(int maximumSize)
{
if (_counter != null)
throw new InvalidOperationException("The method can only be called once before the first value is retrieved from the pool.");
_counter = new System.Threading.SemaphoreSlim(maximumSize);
}
/// <summary>
/// Retrieves a new item from the pool. If the pool is empty and the maximum number of items are active, the task will delay
/// until an item is freed.
/// </summary>
/// <param name="initializer">Delegate that is used to create a new item if the pool is empty but maximum number of items have not been reached.</param>
public static async Task<ConnectionPoolWrapper<TValue>> RetrieveFromPoolAsync(Func<TValue> initializer)
{
if (initializer == null)
throw new ArgumentNullException("initializer");
if (_counter == null)
lock (_syncRoot)
if (_counter == null)
_counter = new System.Threading.SemaphoreSlim(5);
await _counter.WaitAsync();
TValue client;
if (_connectionPool.TryPop(out client))
return new ConnectionPoolWrapper<TValue>(client);
return new ConnectionPoolWrapper<TValue>(initializer());
}
private ConnectionPoolWrapper(TValue value)
{
this._value = value;
}
/// <summary>
/// The object that has been retrieved from the pool.
/// </summary>
private TValue _value;
/// <summary>
/// Specifies if this instance has been disposed. If it has been disposed then the value has been returned to the pool.
/// </summary>
/// <remarks>Type is <c>Int32</c> so that <c>Interlocked.Exchange</c> can be used.</remarks>
private volatile int _disposed;
/// <summary>
/// Gets the object that has been retrieved from the pool.
/// </summary>
public TValue Value
{
get
{
var value = this._value;
if (this._disposed != 0)
throw new ObjectDisposedException(this.GetType().Name);
return value;
}
}
/// <summary>
/// Returns the value in this wrapper to the pool.
/// </summary>
public void Dispose()
{
var disposed = System.Threading.Interlocked.Exchange(ref this._disposed, 1);
// if it was previously disposed, do nothing
if (disposed != 0)
return;
_connectionPool.Push(this._value);
this._value = null;
_counter.Release();
GC.SuppressFinalize(this);
}
~ConnectionPoolWrapper()
{
this.Dispose();
}
}
</code></pre>
<p>I think the first change should be to make it possible to create multiple pools for the same type, probably maintaining a default static one based on type as it is currently.</p>
<p>What else should be changed to make this class actually ready for general usage without prior knowledge?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:29:04.670",
"Id": "72346",
"Score": "1",
"body": "Given this is for .NET, I would make this connection pool behave the same as other connection pools in the framework. ConnectionType.Open() transparently creates a new connection or grabs one from the pool and ConnectionType.Close() or .Dispose() transparently returns the connection to the pool. Someone using the connection doesn't have to know about the connection pooling, just like you wouldn't for the myriad ADO.NET connection objects out there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:45:06.640",
"Id": "72348",
"Score": "0",
"body": "@DanLyons How would that work when you reach the maximum number of allowed connections? Would you make `Open()` `async` (similar to what the code in the question does)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:47:34.833",
"Id": "72507",
"Score": "0",
"body": "As far as I can see, `_connectionPool` is static and one gets one pool per object type. Ideally one has one pool per server. Say 10 connection pool for one SMTP server and a 20 connection pool for another."
}
] |
[
{
"body": "<ol>\n<li><p>I think that syntax like <code>ConnectionPool<SmtpClient>.RetrieveAsync()</code> is more natural than your syntax. If you switch to that, you can probably eliminate the <code>ConnectionPool</code>/<code>ConnectionPoolWrapper</code> separation when it comes to <code>static</code> methods, which doesn't seem to serve any other purpose.</p></li>\n<li><p>Use <code>using</code>s to make your code shorter, there is no reason to write the full <code>System.Threading.SemaphoreSlim</code> every time you want to use that type.</p></li>\n<li><p><code>new System.Threading.SemaphoreSlim(5)</code> the <code>5</code> here should be a named constant. Or it could be a property with default value, that can be modified. (Though in that case, I'm not sure what the property setter should do if it's invoked after the semaphore has already been created.)</p></li>\n<li><p>I think your initialization of <code>_counter</code> using double-checked locking is not actually thread-safe, the <code>_counter</code> variable would have to be <code>volatile</code>. For some more information, see <a href=\"http://csharpindepth.com/articles/general/singleton.aspx#dcl\" rel=\"nofollow\">Jon Skeet's article on implementing singletons</a>.</p></li>\n<li><p>What's the point of the <code>value</code> local variable in the <code>Value</code> getter? If it's trying to be thread-safe, then I don't see a reason for that: the instance of <code>ConnectionPoolWrapper</code> should never be accessed from multiple threads at the same time.</p></li>\n<li><p>Some people recommend always using <code>this.</code> for accessing fields, some people recommend using a prefix like <code>_</code>. But I don't see any reason to use <em>both</em> at the same time.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:04:22.370",
"Id": "72354",
"Score": "0",
"body": "Re: #5 - I made it thus because `_disposed` is volatile (making sure that CLR does not reorder operations) so if the instance gets accessed from multiple threads, the dispose check would still work. My goal was to make the wrapper itself thread-safe as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:10:20.937",
"Id": "72355",
"Score": "0",
"body": "Re: #4 - wow, I did not expect this pattern of all things to be wrong..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:14:50.450",
"Id": "72356",
"Score": "0",
"body": "@Knaģis In that case, I think you should either go fully-thread-safe or not try at all. As it is, the wrapper is not thread-safe, because calling `Dispose()` from two threads won't work correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:25:59.487",
"Id": "72358",
"Score": "0",
"body": "@svik - yes, I did miss that little detail. I edited the code in question, it does seem to be thread safe now but I must admit, I'm not 100% sure. In the end there is still the possible issue if the caller just caches the result from `.Value` property..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:00:14.350",
"Id": "41996",
"ParentId": "41986",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:20:16.477",
"Id": "41986",
"Score": "4",
"Tags": [
"c#",
"connection-pool"
],
"Title": "Generic object pool - what should be changed to make it easier to understand?"
}
|
41986
|
<p>I have a JPanel (mainPanel) with <code>CardLayout</code> which contains 4 JPanels (childPanel).</p>
<p>Each <code>childPanel</code> contains:</p>
<ul>
<li>a JPopupMenu with 4 JMenuItems to switch between the childPanels (First,Last,Next,Previous)</li>
<li>a label with the time when it got visible</li>
<li>a <code>toggleButton</code> that shows/hides the label</li>
</ul>
<p>I created <a href="http://pastebin.com/aNkARuEZ">this working version</a> but I think it can be optimized. Any advice is welcome.</p>
<pre><code>public final class Prozor extends JFrame
{
private static final Dimension SIZE = new Dimension(400, 300);
private final JPanel panelButtoni = new JPanel();
private JButton prvi;
private JButton zadnji;
private JButton sljedeci;
private JButton prethodni;
private CardLayout cardLayout = new CardLayout();
private JPanel panelCards = new JPanel(cardLayout);
private JPopupMenu crveniMeni= new JPopupMenu();
private JPanel crveniPanel= new JPanel();
private JPopupMenu crveniKontekstni= new JPopupMenu();
private JLabel crvenaLabelica = new JLabel();
private JToggleButton crveniButton;
private JPopupMenu plaviMeni= new JPopupMenu();
private JPanel plaviPanel = new JPanel();
private JPopupMenu plaviKontekstni = new JPopupMenu();
private JLabel plavaLabelica = new JLabel();
private JToggleButton plaviButton;
private JPopupMenu zeleniMeni = new JPopupMenu();
private JPanel zeleniPanel = new JPanel();
private JPopupMenu zeleniKontekstni = new JPopupMenu();
private JLabel zelenaLabelica = new JLabel();
private JToggleButton zeleniButton;
private JPopupMenu zutiMeni= new JPopupMenu();
private JPanel zutiPanel = new JPanel();
private JPopupMenu zutiKontekstni = new JPopupMenu();
private JLabel zutaLabelica = new JLabel();
private JToggleButton zutiButton;
public Prozor(String title)
{
super(title);
setPreferredSize(SIZE);
setMinimumSize(SIZE);
setMaximumSize(SIZE);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
kreirajbuttonAkcije();
kreirajCrveniPanel();
kreirajPlaviPanel();
kreirajZeleniPanel();
kreirajZutiPanel();
this.add(panelCards);
pack();
}
public static void main(String[] args)
{
Prozor p = new Prozor("ime");
p.setVisible(true);
}
private void kreirajCrveniPanel() {
crveniPanel.setBackground(Color.RED);
crveniButton = new JToggleButton("Prikazi vrijeme");
crveniButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
if (crveniButton.isSelected()) {
crvenaLabelica.setText(Calendar.getInstance().getTime().toString());
crvenaLabelica.setVisible(true);
}
else
{
crvenaLabelica.setVisible(false);
}
}
});
JMenuItem jmPrvi = new JMenuItem("Prvi");
jmPrvi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.first(panelCards);
}
});
JMenuItem jmZadnji = new JMenuItem("Zadnji");
jmZadnji.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.last(panelCards);
}
});
JMenuItem jmSljedeci = new JMenuItem("Sljedeći");
jmSljedeci.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.next(panelCards);
}
});
JMenuItem jmPrethodni = new JMenuItem("Prethodni");
jmPrethodni.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.previous(panelCards);
}
});
crveniPanel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
crveniMeni.show(me.getComponent(), me.getX(), me.getY());
}
}
});
crveniMeni.add(jmPrvi);
crveniMeni.add(jmZadnji);
crveniMeni.add(jmPrethodni);
crveniMeni.add(jmSljedeci);
crveniPanel.add(crveniMeni);
crveniPanel.add(crvenaLabelica);
crveniPanel.add(crveniButton);
panelCards.add(crveniPanel);
}
private void kreirajPlaviPanel() {
plaviPanel.setBackground(Color.BLUE);
plaviButton =new JToggleButton("Prikazi vrijeme");
plaviButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (plaviButton.isSelected()) {
plavaLabelica.setText(Calendar.getInstance().getTime().toString());
plavaLabelica.setVisible(true);
}else{
plavaLabelica.setVisible(false);
}
}
});
JMenuItem jmPrvi = new JMenuItem("Prvi");
jmPrvi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.first(panelCards);
}
});
JMenuItem jmZadnji = new JMenuItem("Zadnji");
jmZadnji.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.last(panelCards);
}
});
JMenuItem jmSljedeci = new JMenuItem("Sljedeći");
jmSljedeci.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.next(panelCards);
}
});
JMenuItem jmPrethodni = new JMenuItem("Prethodni");
jmPrethodni.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.previous(panelCards);
}
});
plaviPanel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
plaviMeni.show(me.getComponent(), me.getX(), me.getY());
}
}
});
plaviMeni.add(jmPrvi);
plaviMeni.add(jmZadnji);
plaviMeni.add(jmPrethodni);
plaviMeni.add(jmSljedeci);
plaviPanel.add(plaviMeni);
plaviPanel.add(plavaLabelica);
plaviPanel.add(plaviButton);
panelCards.add(plaviPanel);
}
private void kreirajZeleniPanel() {
zeleniPanel.setBackground(Color.GREEN);
zeleniButton=new JToggleButton("Prikazi vrijeme");
zeleniButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (zeleniButton.isSelected()) {
zelenaLabelica.setText(Calendar.getInstance().getTime().toString());
zelenaLabelica.setVisible(true);
}else{
zelenaLabelica.setVisible(false);
}
}
});
JMenuItem jmPrvi = new JMenuItem("Prvi");
jmPrvi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.first(panelCards);
}
});
JMenuItem jmZadnji = new JMenuItem("Zadnji");
jmZadnji.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.last(panelCards);
}
});
JMenuItem jmSljedeci = new JMenuItem("Sljedeći");
jmSljedeci.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.next(panelCards);
}
});
JMenuItem jmPrethodni = new JMenuItem("Prethodni");
jmPrethodni.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.previous(panelCards);
}
});
zeleniPanel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
zeleniMeni.show(me.getComponent(), me.getX(), me.getY());
}
}
});
zeleniMeni.add(jmPrvi);
zeleniMeni.add(jmZadnji);
zeleniMeni.add(jmPrethodni);
zeleniMeni.add(jmSljedeci);
zeleniPanel.add(zeleniMeni);
zeleniPanel.add(zelenaLabelica);
zeleniPanel.add(zeleniButton);
panelCards.add(zeleniPanel);
}
private void kreirajZutiPanel() {
zutiPanel.setBackground(Color.YELLOW);
zutiButton=new JToggleButton("Prikazi vrijeme");
zutiButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (zutiButton.isSelected()) {
zutaLabelica.setText(Calendar.getInstance().getTime().toString());
zutaLabelica.setVisible(true);
}else{
zutaLabelica.setVisible(false);
}
}
});
JMenuItem jmPrvi = new JMenuItem("Prvi");
jmPrvi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.first(panelCards);
}
});
JMenuItem jmZadnji = new JMenuItem("Zadnji");
jmZadnji.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.last(panelCards);
}
});
JMenuItem jmSljedeci = new JMenuItem("Sljedeći");
jmSljedeci.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.next(panelCards);
}
});
JMenuItem jmPrethodni = new JMenuItem("Prethodni");
jmPrethodni.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
cardLayout.previous(panelCards);
}
});
zutiPanel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
zutiMeni.show(me.getComponent(), me.getX(), me.getY());
}
}
});
zutiMeni.add(jmPrvi);
zutiMeni.add(jmZadnji);
zutiMeni.add(jmPrethodni);
zutiMeni.add(jmSljedeci);
zutiPanel.add(zutiMeni);
zutiPanel.add(zutaLabelica);
zutiPanel.add(zutiButton);
panelCards.add(zutiPanel);
}
private void kreirajbuttonAkcije() {
prvi= new JButton("Prvi");
prvi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
cardLayout.first(panelCards);
}
});
zadnji= new JButton("Zadnji");
zadnji.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
cardLayout.last(panelCards);
}
});
sljedeci= new JButton("Sljedeći");
sljedeci.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
cardLayout.next(panelCards);
}
});
prethodni= new JButton("Prethodni");
prethodni.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
cardLayout.previous(panelCards);
}
});
panelButtoni.add(prvi);
panelButtoni.add(zadnji);
panelButtoni.add(prethodni);
panelButtoni.add(sljedeci);
this.add(panelButtoni,BorderLayout.NORTH);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:38:06.150",
"Id": "72333",
"Score": "0",
"body": "kreirajCrveniPanel()\nkreirajPlaviPanel() \nand so on are identical for the different panels, but i would like to make 1 function that handles all 4 since the code is the same"
}
] |
[
{
"body": "<p>I found the answer and have posted it in case someone has a similar problem:</p>\n\n<p>I created a class that extends JPanel like this:</p>\n\n<pre><code>public class CardPanel extends JPanel{\n private JPopupMenu menu;\n private JLabel label;\n private JToggleButton button;\n private final CardLayout layout;\n private final JPanel parent;\n\n public CardPanel(CardLayout layout,Color color,JPanel parent)\n {\n super();\n this.layout = layout;\n this.parent=parent;\n setBackground(color);\n\n kreirajKontekstni();\n\n\n }\n\n private void kreirajKontekstni() {\n button =new JToggleButton(\"Prikazi vrijeme\");\n button.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n if (button.isSelected()) {\n label.setText(Calendar.getInstance().getTime().toString());\n label.setVisible(true);\n }else{\n label.setVisible(false);\n }\n }\n });\n JMenuItem jmPrvi = new JMenuItem(\"Prvi\");\n jmPrvi.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n layout.first(parent);\n }\n });\n JMenuItem jmZadnji = new JMenuItem(\"Zadnji\");\n jmZadnji.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n layout.last(parent);\n }\n });\n JMenuItem jmSljedeci = new JMenuItem(\"Sljedeći\");\n jmSljedeci.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n layout.next(parent);\n }\n });\n JMenuItem jmPrethodni = new JMenuItem(\"Prethodni\");\n jmPrethodni.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n layout.previous(parent);\n }\n });\n\n addMouseListener(new MouseAdapter() \n {\n\n @Override\n public void mouseReleased(MouseEvent me) {\n if (me.isPopupTrigger()) {\n menu.show(me.getComponent(), me.getX(), me.getY());\n }\n }\n\n\n });\n\n menu.add(jmPrvi);\n menu.add(jmZadnji);\n menu.add(jmPrethodni);\n menu.add(jmSljedeci);\n add(menu);\n add(label);\n add(button);\n parent.add(this);\n }\n\n}\n</code></pre>\n\n<p>and changed the code in the main Window to:</p>\n\n<pre><code>public class SimpleProzor extends JFrame\n{\n private static final Dimension SIZE = new Dimension(400, 300);\n\n private final JPanel panelButtoni = new JPanel();\n private JButton prvi;\n private JButton zadnji;\n private JButton sljedeci;\n private JButton prethodni;\n\n private CardLayout cardLayout = new CardLayout();\n private JPanel panelCards = new JPanel(cardLayout);\n\n private CardPanel crveniPanel;\n private CardPanel plaviPanel;\n private CardPanel zeleniPanel;\n private CardPanel zutiPanel;\n\n public SimpleProzor(String title)\n {\n super(title);\n setPreferredSize(SIZE);\n setMinimumSize(SIZE);\n setMaximumSize(SIZE);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n this.setLayout(new BorderLayout());\n kreirajbuttonAkcije();\n\n crveniPanel = new CardPanel(cardLayout, Color.RED, panelCards);\n plaviPanel = new CardPanel(cardLayout, Color.BLUE, panelCards);\n zeleniPanel = new CardPanel(cardLayout, Color.GREEN, panelCards);\n zutiPanel= new CardPanel(cardLayout, Color.YELLOW, panelCards);\n\n this.add(panelCards);\n\n pack();\n }\n\n public static void main(String[] args)\n {\n Prozor p = new Prozor(\"ime\");\n p.setVisible(true);\n }\n\n private void kreirajbuttonAkcije() {\n prvi= new JButton(\"Prvi\");\n prvi.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) \n {\n cardLayout.first(panelCards);\n }\n });\n\n zadnji= new JButton(\"Zadnji\");\n zadnji.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) \n {\n cardLayout.last(panelCards);\n }\n });\n\n sljedeci= new JButton(\"Sljedeći\");\n sljedeci.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) \n {\n cardLayout.next(panelCards);\n }\n });\n\n prethodni= new JButton(\"Prethodni\");\n prethodni.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent ae) \n {\n cardLayout.previous(panelCards);\n }\n });\n\n panelButtoni.add(prvi);\n panelButtoni.add(zadnji);\n panelButtoni.add(prethodni);\n panelButtoni.add(sljedeci);\n this.add(panelButtoni,BorderLayout.NORTH); \n } \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:51:45.577",
"Id": "41995",
"ParentId": "41988",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:28:46.327",
"Id": "41988",
"Score": "7",
"Tags": [
"java",
"swing"
],
"Title": "Card layout in Java"
}
|
41988
|
<p>I currently have a <code>ResourceManager</code> class which is responsible for searching for resources with a given identifier, returning a reference counted pointer to the resource if a valid resource is found, and instantiating a new object if none has been found. Often a resource itself depends on other resources, which are requested from the resource manager. For example, Window may depend on <code>SdlMain</code> (which initializes and shuts down SDL), and thus the constructor of Window would ask <code>ResourceManager</code> for the <code>SdlMain</code> object.</p>
<p>Example:</p>
<pre><code>ResourceManager resources;
//the return type is std::shared_ptr<Window>, the first argument "MainWindow" is the
//..ID to search for, the rest of the arguments are simply forwarded to the constructor
//..of class Window if needed.
auto mainWindow = resources.make<Window>("MainWindow", "Hello World",
512, 512, SDL_WINDOW_SHOWN, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
//The Window object contains the renderer, too, so the ID of the current window
//"MainWindow" must be passed to the texture's constructor
auto tex1 = resources.make<Texture>("tex/tex1.png", "tex/tex1.png", "MainWindow");
//This renders the texture to the screen.
tex1->renderToBuffer(0,0);
mainWindow->bufferToDisplay();
</code></pre>
<p>However, the requirement of knowing the actual ID of the Window when creating a texture becomes a problem when writing a sprite class, if multiple window objects are to be supported:</p>
<pre><code>//Unlike Texture, a Sprite is not a resource but it's lifetime is bound to the object
//..owning it (and there may be many sprites using the same Texture). Thanks to
//..how Texture is implemented, now everything that wishes to use a sprite must be
//..aware of the ID of the window "MainWindow" in order to initialize a Sprite.
Sprite sprite(resources, "tex/tex1.png", "MainWindow");
</code></pre>
<p>I recently came up a solution for this. I would give the identifiers a <em>context</em>, similar to the "scope" of programming languages. SdlMain would be found in <em>global</em> context, with it's ID "SdlMain" available and meaningful anywhere, while one window may reside in context <em>Game</em>, and a second window may reside in the context <em>Editor</em>. Both Window instances would have the name "Window", but there would be no conflict since they reside in a different contexts. The resulting system might look somewhat like this:</p>
<pre><code>ResourceManager resources;
//Set the scope to "Game"
resources.setContext("Game");
auto mainWindow = resources.make<Window>("Window", "Hello World",
512, 512, SDL_WINDOW_SHOWN, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
//Texture asks ResourceManager simply for a "Window", with no idea about the current
//context.
Sprite sprite(resources, "tex/tex1.png");
sprite.draw();
mainWindow->bufferToDisplay();
//Set the context back to global
resources.setContext();
</code></pre>
<p>The actual ID search would function as follows: First the ID is searched for in the current context, if there are no matches the preceding context is evaluated too, until the search arrives at the global context. </p>
<p>Note that the final version would use integer ID:s instead of strings. I do realize that this might be the best example of overengineering ever, but I'm mostly doing this for its learning value.</p>
<p>Before fully committing to such a system, I would like to know some opinions on the matter from more experienced programmers:</p>
<p>Is this a practicable solution? Are there any blatant flaws in this concept? Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:19:33.580",
"Id": "72339",
"Score": "0",
"body": "I'm not certain if this question should be on Programmers StackOverflow. I only mention that since you might get more answers there. I voted you up since it was a good question and well thought-out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:23:30.937",
"Id": "72342",
"Score": "0",
"body": "Originally this was posted on GameDev/StackExchange, but it was soon flagged (admittedly correctly) as too broad, so I deleted the original one. Thanks for the suggestion. I guess cross posting on programmers is not a good idea at this point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:06:13.517",
"Id": "72361",
"Score": "0",
"body": "I like the idea of \"scoping\", because it allows you to create multiple identical object hierarchies which are separated from each other. Each scope could have resources and sub-scopes (which in turn are a scope). I thought about suggesting something like boost.property_tree for this, but it doesn't provide a `parent()` method which you would need for lookup in the next more general scope."
}
] |
[
{
"body": "<p><strong>Preface:</strong> these are just my personal opinions based on experience.</p>\n\n<h2>Don't force the user of the class to remember to do stuff</h2>\n\n<p>The <code>setContext(const char*)</code> method is a method which the user of the class is required to call to have proper operation. As such the user is at risk of forgetting to call this method and thus introduce a bug in the software. Further more the user must remember to be consistent in spelling of the context name or face the risk of introducing subtle bugs where different contexts are used by mistake. </p>\n\n<p>If you wish to go with the concept of contexts (say that 10 time quickly), I would make a \"context\" a first class object which is required for creating instances of resources. Like this:</p>\n\n<pre><code>class ResourceContext{\npublic:\n template<typename... Arg>\n std::shared_ptr<Resource> make(Arg... args);\n};\n\nclass ResourceManager{\npublic:\n std::shared_ptr<ResourceContext> createContext(const char*);\n std::shared_ptr<ResourceContext> findContext(const char*);\nprivate:\n friend class ResourceContext;\n};\n\n\nResourceManager mgr;\nauto gameContext = mgr.createContext(\"Game\");\nSprite sprite(gameContext, \"tex/tex1.png\");\n</code></pre>\n\n<p>This approach solves my two worries</p>\n\n<ol>\n<li><p>You can not forget to change context. You are forced to find the correct context.</p></li>\n<li><p>You can not silently introduce a typo, either you explicitly create a new context or you look up an existing one (with an error if it doesn't exist).</p></li>\n</ol>\n\n<h2>Lookup by reference when possible</h2>\n\n<p>If your texture/sprite class is dependent on the window they are displayed in (as opposed to the SDL context) then it is quite reasonable to expect them to be created from a context where the window is available. Why not simply pass an instance of the <code>resource<Window></code> to the constructor of the sprite/texture instead of doing a lookup by string ID?</p>\n\n<p>Your current approach implicitly reserves \"magic\" names for specific instances of specific classes the risk here is that an unknowing user may create some kind of conflict because they didn't know of all the reserved names in your system.</p>\n\n<h2>One size doesn't fit all (Stop sugar coating my globals)</h2>\n\n<p>In general I believe that this kind of resource manager should only be used for obtaining external resources such as textures, sounds etc. To me it looks like you're trying to sugar coat having global variables, because that's essentially what this is being used like in your example. Using it for SDL context is overkill, why would you want to shutdown SDL during any point of your program's lifetime? What is the point of having it managed as a resource over just a simple global?</p>\n\n<p>In all honesty, I think you are over-engineering this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:16:07.253",
"Id": "72384",
"Score": "0",
"body": "The resource manager itself is necessary since the list of textures, sounds etc. is loaded at startup, and the managed resources are only loaded when needed. Then I thought that I could extend it to external API concepts too, like SDL initialization and window management, into a single uniform system. This is **not** going to be used for managing anything internal to the program. I do realize that this is basically a second, runtime type system (without type safety) that has the equivalent of globals, and I will end up in a header full of ID constants that is included everywhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:22:51.433",
"Id": "72386",
"Score": "0",
"body": "Yes, that's the typical use of this kind of resource manager (as well as keeping recently freed objects in memory for a while just in case they are requested again soon). Yes, so *why* do you want this system over a global for those external APIs? What would you gain other than engineering satisfaction? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:40:12.220",
"Id": "72393",
"Score": "0",
"body": "I found that the general idea as used in your proof-of-concept solution addresses the problem very nicely, packaging the whole context system behind a rather simple front-end with very little overhead. Would \"scope\", \"namespace\" or \"domain\" be a more suitable name than \"context\"? At this stage the only thing that I'm really striving for is just that, engineering satisfaction :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:50:19.613",
"Id": "72399",
"Score": "0",
"body": "Uhm, \"scope\" has more of a temporary sense as in scope of variables on the stack. And \"domain\" isn't quite it either. I think \"context\" is good, or possibly \"namespace\"... actually I think I prefer \"context\" :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:36:08.477",
"Id": "42005",
"ParentId": "41989",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42005",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:51:04.010",
"Id": "41989",
"Score": "7",
"Tags": [
"c++",
"game",
"c++11",
"sdl"
],
"Title": "Using ID's with a \"scope\" -like hierarchy"
}
|
41989
|
<p>This block of code is already somewhat optimized thanks to <a href="https://stackoverflow.com/q/21269833/68063">some</a> <a href="https://stackoverflow.com/questions/21838278/improve-performance-of-function-without-parallelization">answers</a> given over at Stack Overflow. In the last question I made (<a href="https://stackoverflow.com/questions/21838278/improve-performance-of-function-without-parallelization">Improve performance of function without parallelization</a>) the code was marginally improved but I later had to re-write a little bit of it and the changes proposed didn't apply anymore.</p>
<p>I'm looking at optimizing this block of code without resorting to parallelization, other than that I'm pretty much open to using any package out there.</p>
<p>I think this is perhaps the correct site to post this since it's really more of a question about how can I improve my code rather than something not working with it.</p>
<p>Here's the MWE (minimum working example):</p>
<pre><code>import numpy as np
import timeit
def random_data(N):
# Generate some random data.
return np.random.uniform(0., 10., N)
# Data lists.
array1 = np.array([random_data(4) for _ in range(1000)])
array2 = np.array([random_data(4) for _ in range(2000)])
def func():
lst = []
for elem in array1:
# Define factors.
a_01, a_11 = max(elem[1], 1e-10), max(elem[3], 1e-10)
a_02, a_12 = array2[:,1], array2[:,3]
# Combine the factors defined above.
a_0 = a_01**2 + a_02**2
a_1 = a_11**2 + a_12**2
Bs, Cs = -0.5/a_0, -0.5/a_1
# Perform operations.
A = 1./(np.sqrt(a_0*a_1))
B = Bs*(elem[0]-array2[:,0])**2
C = Cs*(elem[2]-array2[:,2])**2
ABC = A*np.exp(B+C)
lst.append(max(ABC.sum(), 1e-10))
return lst
# Time function.
func_time = timeit.timeit(func, number=10000)
print func_time
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:55:37.560",
"Id": "72350",
"Score": "1",
"body": "What is this code supposed to do? What problem are you solving?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:58:41.157",
"Id": "72352",
"Score": "0",
"body": "@GarethRees it's a bit hard to explain since this is a tiny part of a much larger code I'm working on. In short, it calculates the probability that each element of `array1` \"belongs\" (or \"is related\") to `array2`."
}
] |
[
{
"body": "<p>Well, some things I noticed:</p>\n\n<pre><code> # Define factors.\n a_01, a_11 = max(elem[1], 1e-10), max(elem[3], 1e-10)\n a_02, a_12 = array2[:,1], array2[:,3]\n</code></pre>\n\n<p><code>a_02</code> and <code>a_12</code> are static across the loop, no need to redefine them every time. <code>a_01</code> and <code>a_12</code> could be defined array-wise using <code>np.maximum</code>:</p>\n\n<pre><code>a_01 = np.maximum(array1[:,1], np.array(1e-10 for _ in xrange(len(array1))\na_11 = np.maximum(array1[:,3], np.array(1e-10 for _ in xrange(len(array1))\n</code></pre>\n\n<p>However, these are trivial improvements; function call overhead is often blamed for much in the Python optimisation world, but there is no way that removing 2n calls to max will improve things here. With that said, following the static data path further, we come across an instance of</p>\n\n<pre><code>a_0 = a_01**2 + a_02**2\na_1 = a_11**2 + a_12**2\n</code></pre>\n\n<p>If we instead define </p>\n\n<pre><code>a_022 = a_02**2\na_122 = a_12**2\n</code></pre>\n\n<p>at the beginning of the function, we can avoid n multiplications by replacing later occurrences of <code>a_02**2</code> with <code>a_022</code> (and likewise for <code>a_12</code>), which reduces the running time of the program by about 5% on my machine. That isn't too impressive, though I'm sure you should be able to knock that down a fair bit by doing more thing using numpy functions. However, my numpy skills evaporate when it comes to 2d arrays, so I can't help.</p>\n\n<p>It is worth mentioning that the algorithm you are using is <code>O(n^2)</code> at least, so wouldn't get your hopes up too high. Otherwise, I'd recommend looking at Cython as this seems like a problem it would excel at, though you've mentioned that parallelism isn't an option, so I assume using C extensions won't be either. However, if it is, I think you will find great time savings there.</p>\n\n<p>This was the final code I came up with:</p>\n\n<pre><code>def func2():\n lst = []\n # Define factors.\n a_02, a_12 = array2[:,1], array2[:,3]\n a_022 = a_02 ** 2\n a_122 = a_12 ** 2\n e10 = np.array([1e-10 for _ in xrange(len(array1))])\n a_01 = np.maximum(array1[:,1], e10)\n a_11 = np.maximum(array1[:,3], e10)\n for i, elem in enumerate(array1):\n # Combine the factors defined above.\n a_0 = a_01[i]**2 + a_022\n a_1 = a_11[i]**2 + a_122\n Bs, Cs = -0.5/a_0, -0.5/a_1\n # Perform operations.\n A = 1./(np.sqrt(a_0*a_1))\n B = Bs*(elem[0]-array2[:,0])**2\n C = Cs*(elem[2]-array2[:,2])**2\n ABC = A*np.exp(B+C)\n lst.append(max(ABC.sum(), 1e-10))\n return lst\n\nN = 100\nfunc_time = timeit.timeit(func, number=N)\nprint \"Original\\t\", func_time / N\nprint \"-\" * 50\n\nfunc2_time = timeit.timeit(func2, number=N)\nprint \"Revision 1\\t\", func2_time / N\nprint \"Improvement\\t\", str(int((func_time - func2_time) / func_time * 100)) + \"%\"\nprint \"-\" * 50\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:21:15.847",
"Id": "72385",
"Score": "0",
"body": "I'm getting a result of `Improvement -90015%` with this new function. Can you confirm this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:27:26.720",
"Id": "72388",
"Score": "2",
"body": "I think that might be because the indentation of the `return lst` in the original function is incorrect; I presumed that was a typo as most people don't want to exit a loop after only one iteration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:32:24.597",
"Id": "72390",
"Score": "0",
"body": "This was the exact code I tested: https://gist.github.com/bluepeppers/9080540"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:34:25.367",
"Id": "72391",
"Score": "1",
"body": "You are right @BluePeppers, the indent was incorrect in my original code (now fixed) With the correct code I get a ~4% improvement. Thank you very much! I'll wait a bit to see if someone else can top your code otherwise I'll mark your answer as accepted. Cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:31:03.770",
"Id": "72488",
"Score": "0",
"body": "Take advantage of [broadcasting](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) and write `np.maximum(X, 1e-10)` instead of `np.maximum(X, np.array([1e-10 for _ in range(len(X))]))`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:03:14.087",
"Id": "42013",
"ParentId": "41993",
"Score": "5"
}
},
{
"body": "<p>I couldn't make much improvement on this, sorry. Since you didn't explain what the code is supposed to do, there was no opportunity for algorithmic insight, so the only changes I could make were purely mechanical transformations with no understanding.</p>\n\n<p>One obvious thing to do is to replace:</p>\n\n<pre><code>def random_data(N):\n # Generate some random data.\n return np.random.uniform(0., 10., N)\n\narray1 = np.array([random_data(4) for _ in range(1000)])\narray2 = np.array([random_data(4) for _ in range(2000)])\n</code></pre>\n\n<p>with</p>\n\n<pre><code>array1 = np.random.uniform(0, 10, (1000, 4))\narray2 = np.random.uniform(0, 10, (2000, 4))\n</code></pre>\n\n<p>which is about 50 times faster. (Note that you don't have to write <code>0.</code> and <code>10.</code> here: if you read the documentation for <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html\" rel=\"nofollow\"><code>numpy.random.uniform</code></a> you'll see that the parameters <em>low</em> and <em>high</em> have type \"<em>float</em>\", so which whatever values you provide will be coerced to floats.)</p>\n\n<p>Other observations are:</p>\n\n<ul>\n<li>Operations on <code>array2</code> don't depend on <code>elem</code> and so can be hoisted out of the loop.</li>\n<li>It's quicker to make one call to <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html\" rel=\"nofollow\"><code>numpy.split</code></a> than to slice <code>array2</code> four times.</li>\n<li>It's quicker to call <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.square.html\" rel=\"nofollow\"><code>numpy.square</code></a> than use the expression <code>A ** 2</code>.</li>\n<li>The multiplication by <code>-0.5</code> can be saved until after <code>B+C</code>, reducing the number of operations.</li>\n<li>A single division <code>X / Y</code> is cheaper than calculating a reciprocal <code>A = 1 / Y</code> and multiplying <code>A * X</code>.</li>\n</ul>\n\n<p>Applying all of these, my best effort is as follows:</p>\n\n<pre><code>def func2():\n lst = []\n\n epsilon = 1e-10\n\n P = np.split(array1, 4, axis=1)\n P[1] = np.square(np.maximum(P[1], epsilon))\n P[3] = np.square(np.maximum(P[3], epsilon))\n P = np.hstack(P)\n\n Q = np.split(array2, 4, axis=1)\n Q[1] = np.square(Q[1])\n Q[3] = np.square(Q[3])\n\n for elem in P:\n a_0 = elem[1] + Q[1]\n a_1 = elem[3] + Q[3]\n\n B = np.square(elem[0] - Q[0]) / a_0\n C = np.square(elem[2] - Q[2]) / a_1\n ABC = np.exp(-0.5 * (B + C)) / np.sqrt(a_0 * a_1)\n\n lst.append(max(ABC.sum(), epsilon))\n\n return lst\n</code></pre>\n\n<p>This is about 25% faster than your code:</p>\n\n<pre><code>>>> timeit(func2, number=100) / timeit(func, number=100)\n0.7512780299658295\n</code></pre>\n\n<p>For comparison, here's the fully-vectorized version of your code:</p>\n\n<pre><code>def func3():\n epsilon = 1e-10\n P = array1.reshape(-1, 1, 4)\n Q = array2\n R = np.square(np.maximum(P[...,(1,3)], epsilon))\n S = np.square(Q[:,(1,3)])\n T = R + S\n U = np.square(P[...,(0,2)] - Q[:,(0,2)]) / T\n V = np.exp(-0.5 * U.sum(axis=2)) / np.sqrt(T.prod(axis=2))\n return np.maximum(V.sum(axis=1), epsilon)\n</code></pre>\n\n<p>This is about 25% slower than your code because it's O(<em>n</em><sup>2</sup>) in space as well as time, but it's substantially simpler, so it might be a better place to start when making algorithmic improvements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:42:19.597",
"Id": "72539",
"Score": "0",
"body": "Thank you very much for your answer @Gareth, I'll try it right now and report back the results. I'm sorry I can't go into much detail but my actual code is _really_ large, I did comment on what this block does in any case (right below your comment in the original question)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:50:31.207",
"Id": "72544",
"Score": "0",
"body": "@Gabriel: I was hoping for a more technical explanation like \"this computes the radial basis function kernel\" or whatever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:12:13.540",
"Id": "72551",
"Score": "0",
"body": "Gareth this article http://goo.gl/7krj3L can give you an idea of what I'm after, particularly eq. 4. Sorry I can't be more succinct but it really is quite a large issue to be able to discuss it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:14:36.817",
"Id": "72552",
"Score": "1",
"body": "@Gabiel: Thank you, that's more like it. I was wondering why the input arrays seemed to consist of multiple kinds of interleaved data."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:53:42.720",
"Id": "42130",
"ParentId": "41993",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42130",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:25:18.960",
"Id": "41993",
"Score": "10",
"Tags": [
"python",
"performance",
"array",
"numpy"
],
"Title": "Improve performance of math function applied to arrays"
}
|
41993
|
<p>The goals for the code below are in the class summary below. Can anyone see that the code fails at any of those goals? I'm unsure how to thoroughly test it. Is there a way to keep the Queue method thread-safe and remove the lock? Is that lock even necessary?</p>
<pre><code>/// <summary>
/// The goals: only run the most recently queued action.
/// Do not run any actions simultaneously.
/// Skip any tasks that were unstarted if we get a new one.
/// Cancel the currently running task (without aborting the thread).
/// (Rely upon the code in the action to bail early).
/// Support the "IsCanceled" flag on any task that was canceled or skipped.
/// </summary>
public class SingleTaskQueue
{
private Task _task = TaskUtilities.FromResult(false); // using Task.FromResult in .NET 4.5
private CancellationTokenSource _cts = new CancellationTokenSource();
private Action<CancellationToken> _action;
public Task Queue(Action<CancellationToken> action) // this needs to be thread-safe
{
lock (_task) // yes, this changes with each call to Queue
{
_action = action;
var newSource = new CancellationTokenSource();
var tokenSource = Interlocked.Exchange(ref _cts, newSource);
tokenSource.Cancel();
var ret = _task.ContinueWith(justFinished => ProcessLastAction(newSource.Token), newSource.Token);
_task = ret;
return ret;
}
}
private void ProcessLastAction(CancellationToken token)
{
if (!token.IsCancellationRequested)
{
Action<CancellationToken> last = Interlocked.Exchange(ref _action, null);
if (last != null)
last.Invoke(token);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Don't change the locks</strong> - You lock on <code>_task</code>, but inside the synchronized block - you change the reference to <code>_task</code> to a new object! This means that if <code>threadA</code> is in the block, <code>threadB</code> is waiting for the lock to release, and <code>threadC</code> calls the method exactly <em>after</em> <code>threadA</code> has run <code>_task = ret;</code> - <code>threadC</code> will be able to enter the block! This makes your lock mechanism fail.</p>\n\n<p>If you want to lock a block - find a lock which defines the <strong>scope</strong> of your lock - and maintain it accordingly. In your example, the scope seems to be the instance of <code>SingleTaskQueue</code>. Since it is <a href=\"https://stackoverflow.com/questions/251391/why-is-lockthis-bad\">not advisable</a> to do <code>lock(this)</code>, create a <code>private object _lock = new object();</code> and use it as your lock.</p>\n\n<p><strong>Mind your state</strong> - in <code>ProcessLastAction</code> you take your action from <code>_action</code>, to take only the last one, <em>but</em> you take the <code>token</code> as a parameter. This means that if two threads queue a new message before the last task finishes - the second <code>_action</code> may be invoked with the first token - which is already cancelled!</p>\n\n<p>If the two objects are dependent of each other - maintain them together. Create a <code>KeyValuePair<CancellationToken, Action></code> or a custom class to hold them both.</p>\n\n<p><strong>Is that lock necessary?</strong> I can't say if you really need the lock, as I don't know how would <code>Task</code> behave if <code>ContinueWith</code> is called twice on it: </p>\n\n<ul>\n<li><p>If the last call <em>overrides</em> the previous call (in a thread-safe manner) - you could do away with your whole solution - it could come down to a one-liner :)</p></li>\n<li><p>If calls are <em>aggregated</em> in an internal queue, and your manual maintenance of the last action is needed, you would have to synchronize your work.</p></li>\n</ul>\n\n<p>Also, if you have only a single <strong>producer</strong> thread (only one thread which calls <code>Queue</code>) - you don't need to synchronize.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:21:43.747",
"Id": "73122",
"Score": "0",
"body": "Apparently there is some 1%-of-the-time situation in my code where the last _action is not executed. I think you're on to that with the comment about the next-to-last task actually getting the action."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:43:26.933",
"Id": "73126",
"Score": "0",
"body": "On my last comment, I found an issue elsewhere in code. I believe my original code works 100% of the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T05:18:13.223",
"Id": "73172",
"Score": "0",
"body": "To see if your lock works properly - put a `System.Threading.Thread.Sleep(1000);` after `_task = ret;`, and see if other threads cannot enter the block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:55:06.223",
"Id": "73214",
"Score": "0",
"body": "Second `ContinueWith()` doesn't override the first one; both of them will be executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:52:05.790",
"Id": "73237",
"Score": "0",
"body": "If the lock doesn't work, and the code works without it - you don't need it..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:39:39.480",
"Id": "42194",
"ParentId": "41997",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:06:20.683",
"Id": "41997",
"Score": "2",
"Tags": [
"c#",
"thread-safety",
"task-parallel-library"
],
"Title": "Run the most recently requested action after finishing current, skip middle tasks"
}
|
41997
|
<p>The function itself is just returning as <code>void</code>. But, the point of the posted code is not about what the function is returning. It is the code related to using T-SQL and C# to return data from a SQL database that I would like reviewed. Especially the way the <code>using</code> statements are structured.</p>
<pre><code> public void GetOffice(int syncID)
{
string strQry = @"
Select so.SyncID,
so.title
From Offices o
Left Outer Join SyncOffices so On so.id = o.SyncID
Where o.SyncID = @syncID
";
using (SqlConnection conn = new SqlConnection(Settings.ConnectionString))
{
using (SqlCommand objCommand = new SqlCommand(strQry, conn))
{
objCommand.CommandType = CommandType.Text;
objCommand.Parameters.AddWithValue("@syncID", syncID);
conn.Open();
SqlDataReader rdr = objCommand.ExecuteReader();
if (rdr.Read())
{
this.OfficeName= rdr.GetString(1);
}
rdr.Close();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, kudos for using a <code>Parameter</code> and not concatenating the value into your T-SQL string.</p>\n\n<p>You're not disposing all <code>IDisposable</code> objects. <code>SqlDataReader</code> should be disposed as well. Now this makes it quite a bunch of nested <code>using</code> scopes, which you could rework like this:</p>\n\n<pre><code> using (var connection = new SqlConnection(Settings.ConnectionString))\n using (var command = new SqlCommand(sql, connection))\n {\n command.CommandType = CommandType.Text;\n command.Parameters.AddWithValue(\"@syncID\", syncId);\n connection.Open();\n\n using (var reader = command.ExecuteReader())\n {\n if (reader.Read())\n {\n this.OfficeName = reader.GetString(1);\n }\n }\n }\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>Usage of <code>var</code> for implicit typing makes the code easier to read (IMO), if you're using C# 3.0+</li>\n<li>Disemvoweling is bad. There's no reason to call a variable <code>rdr</code> over <code>reader</code>. Use meaningful names, always.</li>\n<li>Hungarian notation is evil. There's no reason to prefix a <code>string</code> with <code>str</code>.</li>\n<li>Stick to camelCasing for locals - that includes parameters, so <code>syncID</code> becomes <code>syncId</code>.</li>\n</ul>\n\n<p>The code assumes the query only returns 1 row, but the query isn't written to explicitly select a single row. This could lead to unexpected results.</p>\n\n<p>Given some <code>IList<string> results = new List<string>();</code>:</p>\n\n<pre><code> using (var reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n results.Add(reader.GetString(1));\n }\n }\n</code></pre>\n\n<p>You could then do <code>this.OfficeName = results.Single();</code> (which would blow up if no rows were returned). One thing that strikes me, is that you're selecting 2 fields, but only using 1, which makes this <code>reader.GetString(1)</code> statement look surprising. If you don't need to select the <code>SyncID</code> field, remove it from your query and do <code>reader.GetString(0)</code> instead.</p>\n\n<p>Finally, the T-SQL itself:</p>\n\n<pre><code>Select so.SyncID, so.title\nFrom Offices o\nLeft Outer Join SyncOffices so On so.id = o.SyncID\nWhere o.SyncID = @syncID\n</code></pre>\n\n<p>Could look like this:</p>\n\n<pre><code>SELECT so.Title\nFROM Offices o\nLEFT JOIN SyncOffices so ON so.id = o.SyncID\nWHERE o.SyncID = @syncID\n</code></pre>\n\n<p>Or, in a string:</p>\n\n<pre><code>var sql = \"SELECT so.Title FROM Offices o LEFT JOIN SyncOffices so ON so.Id = o.SyncId WHERE o.SyncId = @syncId\";\n</code></pre>\n\n<p>The line breaks make it look weird, and since it's not too long of a query, I think it would make the code better to have it on a single line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:51:32.583",
"Id": "72360",
"Score": "0",
"body": "Thank you for the response. Everything makes sense. I want to point out that I am only expecting 1 row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:32:45.757",
"Id": "72368",
"Score": "1",
"body": "If you're going to use `FirstOrDefault()` then I don't see any reason to retrieve the extra rows. (It would be different if you used `SingleOrDefault()` or `Single()`, which I usually prefer.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:34:04.997",
"Id": "72369",
"Score": "0",
"body": "Also, if you make the string into a single-line, you can drop the `@` before the `\"`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:41:18.333",
"Id": "41999",
"ParentId": "41998",
"Score": "8"
}
},
{
"body": "<p>I notice that <code>GetOffice</code> returns <code>void</code> and that the result of the query is written into <code>this.OfficeName</code>.</p>\n\n<p>I usually have one (separate) file which contains/encapsulates all my SQL statements. So I'd have something like,</p>\n\n<pre><code>public void GetOffice(int syncID)\n{\n this.OfficeName = Sql.GetOfficeName(syncID);\n}\n</code></pre>\n\n<p>... where <code>GetOfficeName</code> is a static method of my <code>Sql</code> class.</p>\n\n<p>Having all my SQL in one (separate file) makes it easier to do a code review of all the ways in which I use SQL; for example to ensure that I'm using the same 'best practices' (e.g. using transactions, disposing objects) in all SQL-related methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:07:33.407",
"Id": "42000",
"ParentId": "41998",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41999",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:12:08.283",
"Id": "41998",
"Score": "3",
"Tags": [
"c#",
"sql-server",
"ado.net"
],
"Title": "Return office details from multiple tables"
}
|
41998
|
<pre><code>public class Office
{
private Int32 _SyncID;
private string _OfficeName;
#region Properties
public Int32 SyncID
{
get { return _SyncID; }
set { _SyncID = value; }
}
public string OfficeName
{
get { return _OfficeName; }
set { _OfficeName = value; }
}
#endregion
public void GetOffice(int syncID)
{
List<Office> results = new List<Office>();
var sql = @"
Select so.SyncID,
so.title
From Offices o
Left Outer Join SyncOffices so On so.id = o.SyncID
Where o.SyncID = @syncID
";
using (var connection = new SqlConnection(Settings.ConnectionString))
using (var command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@syncID", syncID);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var office = new Office();
office.SyncID = reader.GetInt32(0);
office.OfficeName = reader.GetString(1);
results.Add(office);
}
}
}
this.SyncID = results.FirstOrDefault().SyncID;
this.OfficeName = results.FirstOrDefault().OfficeName;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The current code will ensure that the list has only one entry (i.e. the last one) ...</p>\n\n<pre><code>results = new List<Office>();\nresults.Add(office);\n</code></pre>\n\n<p>... because invoking <code>results = new List<Office>()</code> will discard any previous list elements.</p>\n\n<p>If you expect your SQL <code>join where</code> to produce exactly one (or, zero or one but not more than one) element then you can assert that; perhaps something like ...</p>\n\n<pre><code>if (reader.Read())\n ... get the data ...\nif (reader.Read())\n throw new Exception(\"Too many rows\");\n</code></pre>\n\n<p>... or ...</p>\n\n<pre><code>string rc = null;\nwhile (reader.Read())\n{\n if (rc != null)\n throw new Exception(\"Too many rows\");\n rc = reader.GetString(1);\n}\n</code></pre>\n\n<p>Perhaps your <code>GetOffice</code> method could be the <code>Office</code> constructor; or be a static factory method of Office.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:38:10.157",
"Id": "42007",
"ParentId": "42001",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "42007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:14:20.227",
"Id": "42001",
"Score": "-1",
"Tags": [
"c#",
"sql-server",
"asp.net-mvc-4"
],
"Title": "Class for Managing Office Details"
}
|
42001
|
<p>Simple post and download web app in Bottle:</p>
<p><strong>server.py</strong></p>
<pre class="lang-python prettyprint-override"><code>import sys
import bottle
from bottle import request, response
import pymongo
import gridfs
from bson.objectid import ObjectId
import mimetypes
mimetypes.init()
# Mongo Connection
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.pacman
test_col = db.test
fs = gridfs.GridFS(db)
# Static Routes
@bottle.get('/<filename:re:.*\.js>')
def javascripts(filename):
return bottle.static_file(filename, root='static/js')
@bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
return bottle.static_file(filename, root='static/css')
@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
return bottle.static_file(filename, root='static/img')
@bottle.get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
return bottle.static_file(filename, root='static/fonts')
@bottle.route('/')
def home_page():
result = db.fs.files.find({"filename": {"$exists": True}})
return bottle.template('files_test/home', files=list(result))
@bottle.route('/add')
def add_page():
return bottle.template('files_test/add')
@bottle.route('/upload', method='POST')
def do_upload():
data = request.files.data
if data:
raw = data.file.read() # This is dangerous for big files
file_name = data.filename
try:
newfile_id = fs.put(raw, filename=file_name)
except:
return "error inserting new file"
print(newfile_id)
return bottle.redirect('/')
@bottle.route('/download')
def download():
file_id = ObjectId(bottle.request.query.id)
if file_id:
try:
file_to_download = fs.get(file_id)
except:
return "document id not found for id:" + file_id, sys.exc_info()[0]
file_extension = str(file_to_download.name)[(str(file_to_download.name).index('.')):]
response.headers['Content-Type'] = (mimetypes.types_map[file_extension])
response.headers['Content-Disposition'] = 'attachment; filename=' + file_to_download.name
response.content_length = file_to_download.length
# print response
return file_to_download
bottle.debug(True)
bottle.run(host='localhost', port=8080)
</code></pre>
<p><strong>add.tpl</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<!-- pass in files (dict)-->
<html>
<head>
<title>Preformance and Capacity Management</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="data" /><br>
<input type="submit"/>
</form>
</body>
</html>
</code></pre>
<p><strong>home.tpl</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<!-- pass in files (dict)-->
<html>
<head>
<title>Preformance and Capacity Management</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br><br><br><br>
%for fileobj in files:
Filename: {{fileobj['filename']}}<br>
Size: {{fileobj['length']}}<br>
Date Uploaded: {{fileobj['uploadDate']}}<br>
md5: {{fileobj['md5']}}<br>
<a href="download?id={{fileobj['_id']}}">&lt--Download File--&gt</a>
<br><br><br><br>
%end
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:17:40.657",
"Id": "72396",
"Score": "1",
"body": "It's on-topic now, but would be a better question if you edited it to include some of the information described in [What makes a good question?](http://meta.codereview.stackexchange.com/a/76/34757)"
}
] |
[
{
"body": "<h2>Global</h2>\n\n<p>You're hard coding the URL to your Mongo instance; it might be better to load it from a settings file. You're also not performing any authentication, though we'll assume that you have your firewalls properly set up, I guess. Some people prefer opening a new connection per request, up to you I guess. I would say that global variables suck, but if you don't think your program will expand beyond a single script, then it could be OK.</p>\n\n<h2>Static views</h2>\n\n<p>You could combine all of the static views fairly simply; have one view that captures everything matching <code><filename:re:.*\\.(.+)></code> (or whatever the correct regexp would be), and then have a dictionary mapping from extensions to directories:</p>\n\n<pre><code>STATIC_DIRS = {\n \"jpg\": \"static/images\",\n \"gif\": \"static/images\",\n ... # etc\n}\n</code></pre>\n\n<p>That said, I don't see the advantage of being able to do <code>/foo.jpg</code> over <code>/static/images/foo.jpg</code>. Also, you could always eliminate the entire set of views and just serve your static content straight from the Nginx/Apache instance that is reverse proxying your application.</p>\n\n<h2>Do Upload</h2>\n\n<p>I would <strong>strongly</strong> suggest you look into reading the file in chunks; as it is, your server would be trivial to DOS.</p>\n\n<p>It might create nicer code if you reversed your <code>if</code> condition, so the code looked more like</p>\n\n<pre><code>@bottle.route('/upload', method='POST')\ndef do_upload():\n data = request.files.data\n if not data:\n return bottle.redirect(\"/\")\n\n raw = data.file.read() # This is dangerous for big files\n file_name = data.filename\n try:\n newfile_id = fs.put(raw, filename=file_name)\n except:\n return \"error inserting new file\"\n print(newfile_id)\n return bottle.redirect('/')\n</code></pre>\n\n<p>This is known as a guard statement, and they are very nice.</p>\n\n<p>Avoid using <code>try: ... except: ...</code> without specifying the type of the exception you wish to catch. In this case, it's particularly bad as you are not even logging the error; someone could come along, shoot a bullet through the hard drive of the machine you were running this on, and your service wouldn't note that anything of interest had happened. I'd suggest that when a request fails, you return a non-200 status code; at the moment, your bullet ridden hard drive will not cause a single non-200 status code.</p>\n\n<h2>Download</h2>\n\n<p>If the file exists in Mongo, but not in the FS, currently you say <code>document id not found for id</code>. However, due to the <code>except</code> statement which doesn't specify exception types, your code also says that no matter what else goes wrong (recall the hard drive with a gun wound). I'd find out what class of errors come under the file not found category, and then treat them differently to others.</p>\n\n<p>Currently, if the user looks up a file that doesn't exist, you return <code>None</code>, which I think bottle will complain about. It'd probably be better to add a guard clause along the lines of</p>\n\n<pre><code>if not file_id:\n # I don't know the bottle api for returning a particular status code, but something like this\n return bottle.abort(404)\n... # otherwise serve the file\n</code></pre>\n\n<p>You don't handle the case that someone gives you a file you don't know the mimetype for, I'd recommend checking before you try and set the header.</p>\n\n<h2>General</h2>\n\n<p>It's best to include a guard at the bottom of the file so that you can import the file without starting the webserver. I'd modify the last few lines to read</p>\n\n<pre><code>if __name__ == '__main__':\n bottle.debug(True)\n bottle.run(host='localhost', port=8080)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T22:51:32.187",
"Id": "72663",
"Score": "0",
"body": "Thank you for all the comments. I haven't been able to configure a nginx reverse proxy and get it to work. Also, any suggestions on where I can learn some of the things you suggested? As I said, I'm not a full time coder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T23:35:43.117",
"Id": "72668",
"Score": "1",
"body": "Frankly setting up nginx/gunicorn is the part of python web development I hate the most. I usually refer to the gunicorn documentation (http://docs.gunicorn.org/en/latest/deploy.html), but I wouldn't worry too much in this case; if you're just developing an application, then I wouldn't worry about it. I'd focus on getting the application working correctly before worrying about stuff like performance :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:52:12.163",
"Id": "72814",
"Score": "0",
"body": "Thanks for the input! I decided to upload the project to Github and try to make your changes. Feel free to look in / contribute if you wanted. https://github.com/jdell64/IPACS"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:18:37.147",
"Id": "80424",
"Score": "0",
"body": "One more follow-up, you mentioned reading in chunks -- how do you do that?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:55:57.877",
"Id": "42197",
"ParentId": "42006",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42197",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:37:19.060",
"Id": "42006",
"Score": "0",
"Tags": [
"python",
"python-2.x",
"web-services",
"mongodb",
"bottle"
],
"Title": "Upload document to mongodb"
}
|
42006
|
<p>An interval is a data structure that represents a range (start & end, from & to, or min & max, etc.). An <a href="http://en.wikipedia.org/wiki/Interval_tree" rel="noreferrer">Interval Tree</a> stores these intervals in a sorted tree structure that makes searching for range intersections much faster. Interval trees help answer questions like: <em>"find all stored intervals that at least partially overlap with the range <code>a</code> to <code>b</code>"</em></p>
<p>Typical interval trees store the intervals using the start of the range as the key to a binary search tree.</p>
<p>This code implements the interval tree and has two methods:</p>
<ul>
<li><code>add(start, end)</code> - inserts an interval to the tree</li>
<li><code>overlap(start, end)</code> - identifies if any interval in the tree overlaps with the input values.</li>
</ul>
<p>The implemented algorithm follows an <a href="http://en.wikipedia.org/wiki/Interval_tree#Augmented_tree" rel="noreferrer"><code>Augmented</code> Interval Tree</a> approach where each node maintains the maximum value contained in any of its child nodes. This maximum value is kept in sync by the <code>add(start,end)</code> method. Other details of the algorithm are:</p>
<ul>
<li><p>intervals are added to a binary tree with the start of interval as index to sort on.</p></li>
<li><p>when intervals are added the maximum values of all parent nodes are updated to ensure they are in sync. </p></li>
<li><p>to check for overlap it performs a descending scan of the tree using iteration, not recursion. It checks each node it descends to, and if the node:</p>
<ol>
<li>intersects the input arguments, it returns true.</li>
<li><code>if (leftsubtree != null && leftsubtree.max > low)</code> search left</li>
<li>else search right</li>
</ol></li>
<li><p><strong>Note</strong>, ranges only overlap if the ranges do more than just touch. The range <code>[10,20]</code> does not overlap with the range <code>[20,30]</code>.</p></li>
</ul>
<p>Despite of a brief stint in explaining my problem, more details can be obtained on this link <a href="http://www.youtube.com/watch?v=q0QOYtSsTg4" rel="noreferrer">here</a>.</p>
<p>I'm looking for code review, best practices, optimizations etc. Also verifying complexity to be <em>O(log(n))</em> to <code>add</code> and <em>O(log(n))</em> to look for <code>overlap.</code> Do correct me if wrong.</p>
<pre><code>public class IntervalSearchTree {
private IntervalNode root;
private class IntervalNode {
IntervalNode left;
int start;
int end;
int maxEnd;
IntervalNode right;
public IntervalNode(IntervalNode left, int start, int end, int maxEnd, IntervalNode right) {
this.left = left;
this.start = start;
this.end = end;
this.maxEnd = maxEnd;
this.right = right;
}
}
/**
* Adds an interval to the the calendar
*
* @param start the start of interval
* @param end the end of the interval.
*/
public void add (int start, int end) {
if (start >= end) throw new IllegalArgumentException("The end " + end + " should be greater than start " + start);
IntervalNode inode = root;
while (inode != null) {
inode.maxEnd = (end > inode.maxEnd) ? end : inode.maxEnd;
if (start < inode.start) {
if (inode.left == null) {
inode.left = new IntervalNode(null, start, end, end, null);
return;
}
inode = inode.left;
} else {
if (inode.right == null) {
inode.right = new IntervalNode(null, start, end, end, null);
return;
}
inode = inode.right;
}
}
root = new IntervalNode(null, start, end, end, null);
}
/**
* Tests if the input interval overlaps with the existing intervals.
*
* Rules:
* 1. If interval intersects return true. obvious.
* 2. if (leftsubtree == null || leftsubtree.max <= low) go right
* 3. else go left
*
* @param start the start of the interval
* @param end the end of the interval
* return true if overlap, else false.
*/
public boolean overlap(int start, int end) {
if (start >= end) throw new IllegalArgumentException("The end " + end + " should be greater than start " + start);
IntervalNode intervalNode = root;
while (intervalNode != null) {
if (intersection(start, end, intervalNode.start, intervalNode.end)) return true;
if (goLeft(start, end, intervalNode.left)) {
intervalNode = intervalNode.left;
} else {
intervalNode = intervalNode.right;
}
}
return false;
}
/**
* Returns if there is an intersection in the two intervals
* Two intervals such that one of the points coincide:
* eg: [10, 20] and [20, 40] are NOT considered as intersecting.
*/
private boolean intersection (int start, int end, int intervalStart, int intervalEnd) {
return start < intervalEnd && end > intervalStart;
}
private boolean goLeft(int start, int end, IntervalNode intervalLeftSubtree) {
return intervalLeftSubtree != null && intervalLeftSubtree.maxEnd > start;
}
public static void main(String[] args) {
IntervalSearchTree intervalSearchTree = new IntervalSearchTree();
intervalSearchTree.add(17, 19);
intervalSearchTree.add(5, 8);
intervalSearchTree.add(21, 24);
intervalSearchTree.add(5, 8);
intervalSearchTree.add(4, 8);
intervalSearchTree.add(15, 18);
intervalSearchTree.add(7, 10);
intervalSearchTree.add(16, 22);
System.out.println("Expected true, Actual: " + intervalSearchTree.overlap(23, 25));
System.out.println("Expected false, Actual: " + intervalSearchTree.overlap(12, 14));
System.out.println("Expected true, Actual: " + intervalSearchTree.overlap(21, 23));
// testing adjoint
System.out.println("Expected false, Actual: " + intervalSearchTree.overlap(10, 15));
System.out.println("Expected false, Actual: " + intervalSearchTree.overlap(10, 14));
System.out.println("Expected false, Actual: " + intervalSearchTree.overlap(11, 15));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T18:26:48.250",
"Id": "81200",
"Score": "2",
"body": "You are misusing the range notation. The range `[10,20]` does in fact intersect with `[20,30]`. What you probably mean is that the range `(10,20]` does not intersect with `(20,30]`, which is true. In range notations, the square bracket means the range includes the value, and the parenthesis means it does not include the value."
}
] |
[
{
"body": "<p>If you are testing the functionality of your code, you should create unit test. I am referencing this part of your code :</p>\n\n<pre><code>public static void main(String[] args) {\n IntervalSearchTree intervalSearchTree = new IntervalSearchTree();\n intervalSearchTree.add(17, 19);\n intervalSearchTree.add(5, 8);\n intervalSearchTree.add(21, 24);\n intervalSearchTree.add(5, 8);\n intervalSearchTree.add(4, 8);\n intervalSearchTree.add(15, 18);\n intervalSearchTree.add(7, 10);\n intervalSearchTree.add(16, 22);\n\n System.out.println(\"Expected true, Actual: \" + intervalSearchTree.overlap(23, 25));\n System.out.println(\"Expected false, Actual: \" + intervalSearchTree.overlap(12, 14));\n System.out.println(\"Expected true, Actual: \" + intervalSearchTree.overlap(21, 23));\n // testing adjoint\n System.out.println(\"Expected false, Actual: \" + intervalSearchTree.overlap(10, 15));\n System.out.println(\"Expected false, Actual: \" + intervalSearchTree.overlap(10, 14));\n System.out.println(\"Expected false, Actual: \" + intervalSearchTree.overlap(11, 15));\n }\n</code></pre>\n\n<p>You could use JUnit to create test classes that you could run whenever you're modifying your code. This will separate the \"production\" code from testing the code. A main method is typically to run your application, not test it. </p>\n\n<p>I've write a test quickly out of your main :</p>\n\n<pre><code>import static org.junit.Assert.*;\n\nimport org.junit.Test;\n\npublic class IntervalSearchTreeTest {\n\n @Test\n public void testOverlapNormalCases() {\n IntervalSearchTree intervalSearchTree = new IntervalSearchTree();\n intervalSearchTree.add(17, 19);\n intervalSearchTree.add(5, 8);\n intervalSearchTree.add(21, 24);\n intervalSearchTree.add(5, 8);\n intervalSearchTree.add(4, 8);\n intervalSearchTree.add(15, 18);\n intervalSearchTree.add(7, 10);\n intervalSearchTree.add(16, 22);\n\n assertTrue(intervalSearchTree.overlap(23, 25));\n assertFalse(intervalSearchTree.overlap(12, 14));\n assertTrue(intervalSearchTree.overlap(21, 23));\n assertFalse(intervalSearchTree.overlap(10, 15));\n assertFalse(intervalSearchTree.overlap(10, 14));\n assertFalse(intervalSearchTree.overlap(11, 15));\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testRule1Overlap() {\n IntervalSearchTree intervalSearchTree = new IntervalSearchTree();\n intervalSearchTree.add(17, 19);\n intervalSearchTree.add(5, 8);\n intervalSearchTree.add(21, 24);\n\n intervalSearchTree.overlap(21, 8);\n }\n\n}\n</code></pre>\n\n<p>Quick tips when doing tests.</p>\n\n<ul>\n<li><p>I'll have the same package structure in my tests folder than in my sources folder. </p></li>\n<li><p>What I always do is naming my class with the name of the class I want to test, in this case <code>IntervalSearchTreeTest</code>.</p></li>\n<li><p>You're documentating 3 rules in overlap, there should be at least 3 tests method that verify thoses rules.</p></li>\n<li><p>Name you tests method with relevant name to the test. You're testing the rule 1 of overlap, well the test name should reflect it.</p></li>\n<li><p>Test should cover one thing only. Right now, <code>testOverlapNormalCases</code> looks big to me. You should shrink this one in two or more. I would probably first test when it should return <code>true</code> then have another test when it return <code>false</code>.</p></li>\n</ul>\n\n<p>I'm not familiar with the algorithm so I only added the test you were doing in you main method and another one that test the obvious <code>IllegalArgumentException</code> throw by overlap. You should add test cases for the <code>add</code> method.</p>\n\n<p>PS: If you're not familiar with JUnit, I strongly recommend you to read on that library. </p>\n\n<p>Little note on your code :</p>\n\n<p><code>if (intersection(start, end, intervalNode.start, intervalNode.end)) return true;</code></p>\n\n<p>I find this line hard to read. You could at least add a newline for the return statement. It would help to see at first glance that there is an exit point at this place in the code. However, I recommend that you always add brackets.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:48:45.440",
"Id": "72374",
"Score": "0",
"body": "I do agree with you, at this moment I am only prepping up for interviews and any semi-professional testing is solving my purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:52:22.877",
"Id": "72376",
"Score": "1",
"body": "Well if it parts of your application, then you could always keep it in your main, but I strongly suggest that actually convert those into real JUnit tests either way. This will ensure that your application have some set of rules and will add value to your project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:53:52.963",
"Id": "72377",
"Score": "0",
"body": "Would note this point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:44:21.317",
"Id": "72397",
"Score": "4",
"body": "@JavaDeveloper: My last interview I was asked to write unit (JUnit) tests. There was another one with a couple of unit tests and I had to write the application which made them green."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:42:15.890",
"Id": "72410",
"Score": "2",
"body": "@JavaDeveloper Test Driven Development (TDD) is becoming a major way of producing code. So you should be ready to make good tests."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:47:43.653",
"Id": "42010",
"ParentId": "42008",
"Score": "10"
}
},
{
"body": "<p>Personally, I think </p>\n\n<pre><code> if (leftsubtree != null && leftsubtree.max > low) {\n</code></pre>\n\n<p>is much easier to read than </p>\n\n<pre><code> if (goLeft(start, end, intervalNode.left)) {\n</code></pre>\n\n<p>Also, a minor thing, you could avoid duplicating code by creating </p>\n\n<pre><code>private void checkInterval(int start, int end) {\n if (start >= end) \n {\n throw new IllegalArgumentException(\"The end \" + end + \" should be greater than start \" + start);\n }\n}\n</code></pre>\n\n<p>Finally also a small thing: for performance sake, in overlap() you could add before the while loop a line like</p>\n\n<pre><code>if (root == null || start >= root.maxEnd || end <= root.start)\n return false;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:31:12.963",
"Id": "46494",
"ParentId": "42008",
"Score": "3"
}
},
{
"body": "<p>It looks like <code>IntervalSearchTree</code> is not self-balancing. If it is not self-balancing, it will not be \\$O(log(n))\\$.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-24T06:36:10.907",
"Id": "278208",
"Score": "0",
"body": "(not balanced (neither self balancing nor amortising partial rebuilds -nothing): no _O(log n)_ operations.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-29T12:10:25.990",
"Id": "129605",
"ParentId": "42008",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:38:19.127",
"Id": "42008",
"Score": "8",
"Tags": [
"java",
"algorithm",
"tree",
"interval"
],
"Title": "Interval search tree"
}
|
42008
|
<pre><code>public class MergeSort {
public static void sort(int[] array, int lo, int hi) {
if (hi <= lo) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(array, lo, mid);
sort(array, mid + 1, hi);
mergesort(array, lo, mid, hi);
}
private static void mergesort(int[] array, int lo, int mid, int hi) {
int[] aux = new int[array.length];
for (int i = 0; i < array.length; i++) {
aux[i] = array[i];
}
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
array[k] = aux[j++];
} else if (j > hi) {
array[k] = aux[i++];
} else if (aux[i] > aux[j]) {
array[k] = aux[j++];
} else {
array[k] = aux[i++];
}
}
}
public static void main(String[] args) {
int[] a = { 3, 1, 5, 1, 8, 23, 55, 54, 10, 12, 5 };
MergeSort.sort(a, 0, a.length - 1);
show(a);
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
</code></pre>
<p>It took me a whole day and a half to understand the code but I did a quick test and it worked. One thing I am concerned with is that the coursera class I am taking does it differently, instead of creating aux in mergesort they create aux in a helper class and pass around BOTH arrays in the sort and mergesort method. It looked like this:</p>
<pre><code>private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length-1);
assert isSorted(a);
}
</code></pre>
<p>and when it got to the merge sort method it finally copies the aux array, what is the point of this route? It looks like it just takes more code.</p>
|
[] |
[
{
"body": "<h2>General comments</h2>\n\n<ul>\n<li><p>you have 'good' mid-finding code: <code>int mid = lo + (hi - lo) / 2;</code> This is fancy code, and, if you have not learned why it is done this way, then you should <a href=\"http://googleresearch.blogspot.ca/2006/06/extra-extra-read-all-about-it-nearly.html\">read up on the midpoint bug in Java</a>.</p></li>\n<li><p>your algorithm generally looks sound. It works</p></li>\n</ul>\n\n<p>The basic premise of your sort is good. The code is neat, and, if you <a href=\"http://en.wikipedia.org/wiki/Merge_sort\">know the merge-sort</a>, it is readable, and does the right sort of things at the right times.</p>\n\n<p>With just your code in front of me, I would say 'good job'. To make it better, I would recommend that:</p>\n\n<ul>\n<li><p>you make your code conform to the standard usage in Java, where you would have two methods:</p>\n\n<pre><code>MergeSort.sort(int[] data);\nMergeSort.sort(int[] data, offset, length);\n</code></pre>\n\n<p>Java typically uses a 'length' argument, instead of a 'high' argument. In the case of the MergeSort, the 'high' variation is more useful, so I would recommend making your current method <code>private</code>, and then adding a new recursion-wrapping frontend to the code that makes it conform to typical Java method calls.</p></li>\n</ul>\n\n<h2>About the <code>aux</code></h2>\n\n<p>This is the second reason to consider wrapping your current sort-entry method in to a calling method.... something like:</p>\n\n<pre><code>public static void sort(int[] data) {\n sort(data, 0, data.length);\n}\n\npublic static void sort(int[] data, int offset, int length) {\n int[] aux = new int[data.length]; // smarter implementation can be used for if length != data.length\n recursiveSort(data, aux, offset, offset + length);\n}\n</code></pre>\n\n<p>Where the method <code>recursiveSort</code> is the method you currently have as <code>sort</code>.</p>\n\n<p>The reason for doing the <code>aux</code> in the calling method is for memory efficiency. At some point you will need to do the final merge, which will require the entire data array to fit in to a memory 'copy', the <code>aux</code>. You will also do many more smaller merge sorts requiring a smaller size of memory. If you are going to need the large space anyway, you may as well create it in the beginning, and reuse it many times, which is better than creating many small <code>aux</code> which never get reused.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:27:33.960",
"Id": "72389",
"Score": "1",
"body": "Thanks, couldn't have asked for a better response, really helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:08:21.870",
"Id": "42015",
"ParentId": "42009",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "42015",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:40:47.963",
"Id": "42009",
"Score": "5",
"Tags": [
"java",
"sorting",
"mergesort"
],
"Title": "Is this merge sort code good enough?"
}
|
42009
|
<p>I am building an Administration web site for the Office details in my database. Right now, I am just trying to display the office details.</p>
<pre><code>public class OfficeRepository
{
public static Office GetOffice(int syncID)
{
List<Office> results = new List<Office>();
var sql = @"Select so.SyncID, so.title From Offices o Left Outer Join SyncOffices so On so.id = o.SyncID Where o.SyncID = @syncID";
using (var connection = new SqlConnection(Settings.ConnectionString))
using (var command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@syncID", syncID);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var office = new Office();
office.SyncID = reader.GetInt32(0);
office.OfficeName = reader.GetString(1);
results.Add(office);
}
}
}
Office returnOffice = new Office();
returnOffice.SyncID = results.FirstOrDefault().SyncID;
returnOffice.OfficeName = results.FirstOrDefault().OfficeName;
return returnOffice;
}
}
public class HomeController : Controller
{
public ActionResult Index(int id = 0)
{
Office currentOffice = OfficeRepository.GetOffice(id);
var officeMgrViewModel = new OfficeMgrViewModel();
officeMgrViewModel.Office = currentOffice;
return View(officeMgrViewModel);
}
}
public class OfficeMgrViewModel
{
public Office Office { get; set; }
}
public class Office
{
public Int32 SyncID { get; set; }
public string OfficeName { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:59:38.317",
"Id": "72378",
"Score": "0",
"body": "Could you include a short description of what this code does? It will help with the reviewing process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:01:02.613",
"Id": "72379",
"Score": "0",
"body": "I am building an Administration web site for the Office details in my database. Right now, I am just trying to display the office details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:02:06.123",
"Id": "72380",
"Score": "1",
"body": "You should also have these descriptions in the question itself, not just as comments here."
}
] |
[
{
"body": "<p>You may want your properties to be <code>private set</code> so that they can't be changed from the outside:</p>\n\n<pre><code>public class Office\n{\n public Int32 SyncID { get; private set; }\n public string OfficeName { get; private set; }\n}\n</code></pre>\n\n<p>To do that you can make GetOffice a member of Office instead of OfficeRepository.</p>\n\n<p>Or you can define a constructor ...</p>\n\n<pre><code>// Logically immutable\npublic class Office\n{\n public Office(Int32 SyncID, string OfficeName)\n {\n this.SyncID = SyncID;\n this.OfficeName = OfficeName;\n }\n public Int32 SyncID { get; private set; }\n public string OfficeName { get; private set; }\n}\n</code></pre>\n\n<p>... and change your GetOffice method to invoke the constructor instead of invoking the <code>set</code> properties.</p>\n\n<p>Similarly, OfficeMgrViewModel needn't have a <code>public set</code> property if it had a constructor.</p>\n\n<p>See also <a href=\"https://codereview.stackexchange.com/a/42007/34757\">this answer</a> which mentions how to simplify your GetOffice method to not use a <code>List</code>, if you expect that your <code>join where</code> will never produce more than one record.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:05:24.373",
"Id": "42014",
"ParentId": "42012",
"Score": "4"
}
},
{
"body": "<p>In addition to ChrisW's suggestion, I would change your repository method a bit:</p>\n\n<pre><code>public static Office GetOffice(int syncID)\n{\n //remove this List<Office> results = new List<Office>();\n\n var sql = @\"Select so.SyncID, so.title From Offices o Left Outer Join SyncOffices so On so.id = o.SyncID Where o.SyncID = @syncID\";\n\n using (var connection = new SqlConnection(Settings.ConnectionString))\n using (var command = new SqlCommand(sql, connection))\n {\n command.CommandType = CommandType.Text;\n command.Parameters.AddWithValue(\"@syncID\", syncID);\n connection.Open();\n\n using (var reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n //simply return the first result here (using ChrisW's suggested constructor)\n return new Office(reader.GetInt32(0), reader.GetString(1));\n }\n }\n }\n\n return null; //return null here and handle within calling code\n}\n</code></pre>\n\n<p>By returning null, you can handle a null office in your controller code (show an error and allow the user to select a different syncId, for example). In the old code, if no results were found, the FirstOrDefault().SyncId would throw an exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:17:13.437",
"Id": "72707",
"Score": "0",
"body": "+1 However throwing from inside the SQL method would be better, if the passed-in SyncID was supposed to be valid and not fail, and therefore the calling code is NOT coded to expect/handle a null Office."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:39:19.777",
"Id": "72845",
"Score": "0",
"body": "Agreed - I think it depends on a) how the front-end is set up to handle failures and b) where the syncIDs come from."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T22:20:16.960",
"Id": "42204",
"ParentId": "42012",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42014",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:56:38.690",
"Id": "42012",
"Score": "2",
"Tags": [
"c#",
"sql-server",
"asp.net-mvc-4"
],
"Title": "Returns Office Details from Database"
}
|
42012
|
<p>In the following contrived example, I have a collection of <code>PropertyManager</code>s that each contains selector and assigner delegates to read from and write to a property on the generic type. It feels clunky for lots of reasons, not least of which is that both delegates are basically there to serve the same purpose: To identify the property on the generic that I want to read from then write back into.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public class ReadWritePropertySelectorTests
{
public void Round<T>(IEnumerable<T> collection,
params PropertyManager<T>[] propertyManagers)
{
foreach (var item in collection)
{
foreach (var propertyManager in propertyManagers)
{
var valueToRound = propertyManager.Selector(item);
propertyManager.Assigner(item, Math.Round(valueToRound, 1));
}
}
}
public class PropertyManager<T>
{
public Func<T, decimal> Selector { get; set; }
public Action<T, decimal> Assigner { get; set; }
}
public class Combatant
{
public decimal Attack { get; set; }
public decimal Defense { get; set; }
public decimal Health { get; set; }
}
[Test]
public void Test()
{
// Arrange
var combatants = new[]
{
new Combatant { Attack = 33.12M, Defense = 12.771M, Health = 60.1181M }
};
// Act
Round(combatants,
new PropertyManager<Combatant>
{
Selector = c => c.Attack, Assigner = (c, v) => c.Attack = v
},
new PropertyManager<Combatant>
{
Selector = c => c.Defense, Assigner = (c, v) => c.Defense = v
},
new PropertyManager<Combatant>
{
Selector = c => c.Health, Assigner = (c, v) => c.Health = v
});
// Assert
var array = combatants.ToArray();
Assert.AreEqual(33.1M, array[0].Attack);
Assert.AreEqual(12.8M, array[0].Defense);
Assert.AreEqual(60.1M, array[0].Health);
}
}
}
</code></pre>
<p>Is there any way to redo this to make the call to <code>Round()</code> more concise, preferably removing the need for a strongly typed <code>PropertyManager</code>? I think ultimately calling it as follows would be awesome, but I can't figure out the language constructs to use to get there:</p>
<pre><code>Round(combatants, c => c.Attack, c => c.Defense, c => c.Health);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:02:22.503",
"Id": "73241",
"Score": "0",
"body": "Why are you testing a function of your test class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:14:22.593",
"Id": "73704",
"Score": "0",
"body": "Because it's a \"contrived example\"."
}
] |
[
{
"body": "<p>Yup, it is possible, but you'll have to delve into the dark world of <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"nofollow\">Expression Trees</a>.</p>\n\n<p>This function creates getter and setter functions using the <code>out</code> parameters. It's ugly, and you usually don't want to use two <code>out</code> parameters, but hopefully it'll get you moving in the right direction.</p>\n\n<pre><code>public static bool CreateGetterSetter<T, V>(Expression<Func<T, V>> getterExpression, out Func<T, V> getter, out Action<T, V> setter)\n{\n if (getterExpression == null)\n throw new ArgumentNullException(\"getterExpression\");\n\n var memberExpression = getterExpression.Body as MemberExpression;\n if (memberExpression == null || memberExpression.NodeType != ExpressionType.MemberAccess || memberExpression.Member == null)\n throw new ArgumentException(\"The expression must get a member (property or field).\", \"getterExpression\");\n\n // The expression passed in is the getter, so just compile it.\n getter = getterExpression.Compile();\n\n // The setter function takes two parameters as input.\n var paramT = Expression.Parameter(typeof(T));\n var paramV = Expression.Parameter(typeof(V));\n\n // Create the setter function\n if (memberExpression.Member.MemberType == MemberTypes.Field)\n {\n // The getter retrieves a field. \n var field = memberExpression.Member as FieldInfo;\n if (field == null)\n throw new ArgumentException(\"Could not get field info for member \" + memberExpression.Member.ToString());\n\n // This expression represents the field on the parameter.\n var fieldExpr = Expression.Field(paramT, field);\n\n // This expression is what the field will be set to.\n Expression rightExpr;\n if (paramV.Type == field.FieldType)\n rightExpr = paramV;\n else\n rightExpr = Expression.Convert(paramV, field.FieldType);\n\n // This is the assignment expression (sets the field to the parameter value).\n var assign = Expression.Assign(fieldExpr, rightExpr);\n\n // Compile the expressions into a lambda.\n setter = Expression.Lambda<Action<T, V>>(assign, paramT, paramV).Compile();\n }\n else if (memberExpression.Member.MemberType == MemberTypes.Property)\n {\n // The getter retrieves a property.\n var property = memberExpression.Member as PropertyInfo;\n if (property == null)\n throw new ArgumentException(\"Could not get property info for member \" + memberExpression.Member.ToString());\n\n // This expression represents what the property will be set to.\n Expression paramSet;\n if (paramV.Type == property.PropertyType)\n paramSet = paramV;\n else\n paramSet = Expression.Convert(paramV, property.PropertyType);\n\n // Handle read-only properties (have no setter).\n if (!property.CanWrite)\n {\n setter = (t, v) => Debug.Write(\"Cannot set read-only property: \" + property.ToString());\n return false;\n }\n\n // This expression represents calling the property setter.\n var call = Expression.Call(paramT, property.SetMethod, paramSet);\n\n // Compile the expressions into a lambda.\n setter = Expression.Lambda<Action<T, V>>(call, paramT, paramV).Compile();\n }\n else\n {\n // The member was not a field or a property.\n setter = (t, v) => Debug.Write(\"Setter invoked for invalid expression\");\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public class A\n{\n public string Property { get; set;}\n}\n\n// Define the variables to hold the out parameters.\nFunc<A, string> getter;\nAction<A, string> setter;\n\n// Call function to use expression trees to create the getter and setter.\nCreateGetterSetter<A, string>(a => a.Property, out getter, out setter);\n\n// Now you can use \"getter\" to get A.Property...\nvar inst = new A { Property = \"value\" };\nvar value = getter(inst); // value = \"value\"\n\n// ... and \"setter\" to set A.Property...\nsetter(inst, \"new\"); // inst.Property = \"new\"\nvalue = getter(inst); // value = \"new\";\n</code></pre>\n\n<p>And to implement Round this way...</p>\n\n<pre><code>public static void Round<T>(IEnumerable<T> collection, params Expression<Func<T, decimal>>[] getterExpressions)\n{\n // Create all the lambdas up-front. This is expensive, so you should cache this somewhere rather than \n // re-compiling all the expressions every time.\n var gettersSetters = new Tuple<Func<T, decimal>, Action<T, decimal>>[getterExpressions.Length]; \n for(int i=0;i<getterExpressions.Length;i++)\n {\n Func<T, decimal> getter;\n Action<T, decimal> setter;\n CreateGetterSetter<T, decimal>(getterExpressions[i], out getter, out setter);\n gettersSetters[i] = Tuple.Create(getter, setter);\n }\n\n foreach (var item in collection)\n {\n foreach (var tuple in gettersSetters)\n {\n var getter = tuple.Item1;\n var setter = tuple.Item2;\n\n var value = getter(item);\n value = Math.Round(value, 1);\n setter(item, value);\n }\n }\n}\n</code></pre>\n\n<p>Hope that helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:43:25.877",
"Id": "73311",
"Score": "0",
"body": "You could combine the branches for property and field using `Expression.PropertyOrField()`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:13:22.260",
"Id": "42024",
"ParentId": "42016",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T21:38:44.133",
"Id": "42016",
"Score": "2",
"Tags": [
"c#",
"generics",
"delegates"
],
"Title": "Delegate that selects a writable property on a generic"
}
|
42016
|
Pathfinding or pathing is the plotting of the shortest route between two points. It is a more practical variant on solving mazes. This field of research is based heavily on Dijkstra's algorithm for finding the shortest path on a weighted graph.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:11:35.493",
"Id": "42022",
"Score": "0",
"Tags": null,
"Title": null
}
|
42022
|
<p>I threw together a small solution for my organization today for some basic data review and approval procedures. This particular application will likely not change or add functionality at any time.</p>
<p>My question as I was coding the application was, does this need to be decoupled? Are there any opportunities for a Factory Pattern or Dependency Injection? Is following those patterns just adding too much to a program that doesn't really <em>need</em> it? (YAGNI?)</p>
<p>I kept coming to the conclusion that adding any of the above would be overkill, but I am a Lone Ranger developer at my company so I thought I would get the opinion of the community at large.</p>
<p>The application consists of two domain level classes and a <code>Form</code>.</p>
<p><strong>MAIN FORM</strong></p>
<pre><code>using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace StockoutReasonReview
{
public partial class StockoutReasonReviewForm : Form
{
private ReasonData ReasonData { get; set; }
public StockoutReasonReviewForm()
{
InitializeComponent();
this.ReasonData = new ReasonData();
SetupDgv();
}
private void CloseButton_Click(object sender, EventArgs e)
{
this.ReasonData.ReasonTable.Dispose();
this.Close();
}
private void SubmitButton_Click(object sender, EventArgs e)
{
this.ReasonData.Submit();
}
private void SetupDgv()
{
dgvReasons.DataSource = this.ReasonData.ReasonTable;
dgvReasons.DefaultCellStyle.BackColor = Color.LightBlue;
dgvReasons.AlternatingRowsDefaultCellStyle.BackColor = Color.LightCyan;
dgvReasons.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
var approvedColumn = new DataGridViewCheckBoxColumn
{
Name = "approved_check",
DataPropertyName = "approved",
TrueValue = "Y",
FalseValue = "N"
};
var changeReasonColumn = new DataGridViewComboBoxColumn
{
Name = "approved_category_combo",
DataPropertyName = "approved_category",
DataSource = this.ReasonData.DropDownItems
};
if (dgvReasons.Columns["approved_check"] == null)
{
dgvReasons.Columns.Insert(0, approvedColumn);
}
if (dgvReasons.Columns["approved_category_combo"] == null)
{
dgvReasons.Columns.Insert(1, changeReasonColumn);
}
dgvReasons.Columns["note"].HeaderText = "Note";
dgvReasons.Columns["note"].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dgvReasons.Columns["note"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dgvReasons.Columns["buyer_name"].HeaderText = "Buyer";
dgvReasons.Columns["buyer_name"].Width = 80;
dgvReasons.Columns["location_id"].HeaderText = "Loc";
dgvReasons.Columns["location_id"].Width = 50;
dgvReasons.Columns["item_id"].HeaderText = "Item Id";
dgvReasons.Columns["reason_category"].HeaderText = "Original Category";
dgvReasons.Columns["approved_category_combo"].HeaderText = "Approved Category";
dgvReasons.Columns["approved_category_combo"].Width = 125;
dgvReasons.Columns["approved_check"].HeaderText = "Approve";
dgvReasons.Columns["approved_check"].Width = 50;
dgvReasons.Columns["stockout_reason_uid"].Visible = false;
dgvReasons.Columns["date_created"].Visible = false;
dgvReasons.Columns["buyer_id"].Visible = false;
dgvReasons.Columns["date_last_modified"].Visible = false;
dgvReasons.Columns["approved"].Visible = false;
dgvReasons.Columns["approved_category"].Visible = false;
foreach (var col in dgvReasons.Columns.Cast<DataGridViewColumn>().Where(col => !col.Name.Contains("approved")))
{
col.ReadOnly = true;
}
}
}
}
</code></pre>
<p><strong>BUSINESS LOGIC</strong></p>
<pre><code>using System;
using System.Data;
namespace StockoutReasonReview
{
class ReasonData
{
public DataTable ReasonTable { get; set; }
public readonly string[] DropDownItems =
{
"",
"New Item",
"Supplier Issue",
"Carrier Issue",
"Didn't Order/Transfer in time",
"Sales Spike",
"Large Qty Order",
"Other"
};
public ReasonData()
{
this.ReasonTable = new DatabaseTransaction().GetReasons();
GenerateAdditionalColumns();
PopulateCategories();
}
public void Submit()
{
new DatabaseTransaction().SubmitReasons(this.ReasonTable);
}
private void GenerateAdditionalColumns()
{
this.ReasonTable.Columns.Add("approved"); //Temp column to be used during approval process
//this.ReasonTable.Columns.Add("approved_category"); //Testing Only - Need to add the column to the actual database after today's reviews are complete
}
private void PopulateCategories()
{
foreach (DataRow row in this.ReasonTable.Rows)
{
row["approved_category"] = row["approved_category"] == DBNull.Value
? row["reason_category"]
: row["approved_category"];
}
}
}
}
</code></pre>
<p><strong>DATA ACCESS</strong></p>
<pre><code>using System;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using StockoutReasonReview.Properties;
using WPD_Common_Library;
namespace StockoutReasonReview
{
public class DatabaseTransaction
{
public DataTable GetReasons()
{
using (var dt = new DataTable())
using (var conn = new SqlConnection(ConnectionStrings.P21ConnectionString))
using (var cmd = new SqlCommand(Resources.GetReasonString, conn))
{
conn.Open();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
public void SubmitReasons(DataTable dtSubmit)
{
foreach (var row in dtSubmit.Rows.Cast<DataRow>().Where(row => row["approved"].ToString() == "Y"))
{
using (var conn = new SqlConnection(ConnectionStrings.P21ConnectionString))
using (var cmd = new SqlCommand(Resources.SubmitReasonString, conn))
{
cmd.Parameters.AddWithValue("@Uid", row["stockout_reason_uid"]);
cmd.Parameters.AddWithValue("@Category", row["approved_category"]);
cmd.Parameters.AddWithValue("@Modified", DateTime.Now);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
}
}
</code></pre>
<p>Obviously I am open to other suggestions in a more general sense, but I am specifically focused on my question regarding further decoupling. </p>
|
[] |
[
{
"body": "<p>I think the answer to you question mainly lies in the level of faith you have in your statement that \"this particular application will likely not change or add functionality at any time.\" In my experience, its only a matter of time before somebody asks \"wouldn't it be nice if...\" or the business requirements that drive the application change. That said, it doesn't look like there is a lot of immediate gain in decoupling this much further at this point. There may be in the future, but if it does the job right now the addition effort in refactoring might be a little bit premature. I would ask yourself how many use cases there conceivably are at this point - if this is basically just a one-off office automation type project I'm guessing there aren't that many right now.</p>\n\n<p>That said, what has bitten me on projects like this in the past are \"simple\" changes that are easy to implement but require the source to be recompiled and redeployed. This makes the following code section leap out:</p>\n\n<pre><code>public readonly string[] DropDownItems =\n{\n \"\",\n \"New Item\",\n \"Supplier Issue\",\n \"Carrier Issue\",\n \"Didn't Order/Transfer in time\",\n \"Sales Spike\",\n \"Large Qty Order\",\n \"Other\"\n}; \n</code></pre>\n\n<p>This is a maintenance hassle waiting to happen, because <em>every</em> manager that I've ever worked with would ask at some point for another item to be added to this list. I would be to pull these items out of a table in the database (if the DB is normalized they should be in a separate table anyway).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:43:56.963",
"Id": "72424",
"Score": "3",
"body": "+1 for no other reason that using the word \"hassle\" ...ok for sportsmanship, too :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:55:42.883",
"Id": "72567",
"Score": "1",
"body": "Funny thing? When I walked into the office this morning, the manager said: \"I think it would be nice to add more categories\" ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:36:38.450",
"Id": "42087",
"ParentId": "42023",
"Score": "7"
}
},
{
"body": "<blockquote>\n<p><strong>Is decoupling necessary for very small applications?</strong></p>\n</blockquote>\n<h1>YES!!</h1>\n<p>However I'd correct your statement here:</p>\n<blockquote>\n<p>Is following those patterns just adding too much to a program that doesn't really need it? (YAGNI?)</p>\n</blockquote>\n<p>It's not so much about YAGNI, than it is about <a href=\"http://en.wikipedia.org/wiki/Cargo_cult_programming\" rel=\"noreferrer\"><em>Cargo Cult Programming</em></a>. However in practice, any <em>small application</em> has the potential to grow and <a href=\"http://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"noreferrer\">spaghettify</a> (I know, that's not quite a verb) beyond repair; building small applications with <em>clean, testable code</em> as a goal can be great practice for when the day comes where you need to work on a large system where untested/untestable code isn't an option.</p>\n<p><code></opinion></code></p>\n<hr />\n<h1>Actual Review</h1>\n<h3>Main Form</h3>\n<p>I think the name should be <code>InitializeDataGridView()</code>, but that's not the reason why I don't like the <code>SetupDgv</code> method. There <em>has to be a way</em> to leverage some databinding here, isn't there? Also I think <code>ReasonData</code> should be assigned from the outside, probably <em>property-injected</em> (since <em>constructor injection</em> would either not be pretty, or would break the designer).</p>\n<h3>Business Logic</h3>\n<p>I don't think it's normal to see <code>new DatabaseTransaction()</code> more than once, and even if it were only once, you've coupled your "business logic" with a very specific piece of code that the <code>ReasonData</code> class is instanciating at will.</p>\n<h3>Data Access</h3>\n<p>Your class is lying. When I first saw <code>new DatabaseTransaction()</code> I expected a <em>database transaction</em> to actually happen. But what you have here is really just a service class that works with boilerplate-level ADO.NET constructs... which is probably fine, but if this application grows you'll want to reduce the boilerplate clutter and perhaps use an ORM, like Entity Framework.. or at least Linq-to-SQL, the goal being to abstract all these <code>IDisposable</code> instances away.</p>\n<p>I think <code>SubmitReasons()</code> can afford to use the same connection for all commands:</p>\n<pre><code> using (var conn = new SqlConnection(ConnectionStrings.P21ConnectionString))\n {\n conn.Open();\n foreach (var row in dtSubmit.Rows.Cast<DataRow>().Where(row => row["approved"].ToString() == "Y"))\n {\n using (var cmd = new SqlCommand(Resources.SubmitReasonString, conn))\n {\n cmd.Parameters.AddWithValue("@Uid", row["stockout_reason_uid"]);\n cmd.Parameters.AddWithValue("@Category", row["approved_category"]);\n cmd.Parameters.AddWithValue("@Modified", DateTime.Now);\n\n cmd.ExecuteNonQuery();\n }\n }\n }\n</code></pre>\n<hr />\n<p>Bottom line, always strive to write clean code, regardless of app size. That doesn't mean to blindly implement a whole <code>IRepository<TEntity></code> "thing" with injected <code>IContextManagerFactory<TContext></code> (<code></sarcasm></code>) just for the heck of it! If ADO.NET suits your small app needs, it's a totally valid approach! However by writing your small apps in <em>testable code</em> (decoupled), you're making your own life easier, and you can always consider those as a "practice" for larger systems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:52:36.370",
"Id": "72564",
"Score": "0",
"body": "Great Answer! Thank you so much! The majority of your suggestions are clear, but can you expand a bit on \"There has to be a way to leverage some data binding\"? The `SetupDGV()` method sets hard coded values for the grid, is there a better place to do this? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:24:52.860",
"Id": "72572",
"Score": "0",
"body": "@EvanL Thanks! I'm not very familiar with data binding in WinForms, but I'm sure there's a way to just set the grid's `DataSource` to some `IBindingList`, so you'd get all the columns for free... but this might be just me getting used to WPF's data bindings, anyway check this out: http://stackoverflow.com/questions/16695885/binding-listt-to-datagridview-in-winform"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:33:44.527",
"Id": "72576",
"Score": "0",
"body": "Unfortunately I think we are getting WPF mixed up with WinForms. In my case the columns are a result of the columns in the database, I am just setting header text and size properties on each, as well as making several read only. I'm not actually adding any columns except for the custom controls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:39:04.503",
"Id": "72579",
"Score": "0",
"body": "Final bit of curiosity. You mentioned cargo cult programming, were you saying that my code seems to follow this paradigm? Or that deciding to implement further decoupling elements could potentially lead to that? If the former, what makes you think that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:51:00.537",
"Id": "72581",
"Score": "1",
"body": "I mentioned Cargo Cult Programming because you mentioned YAGNI, referring to further refinement of the code. It's the trap one can fall into when implementing design patterns for the sake of implementing design patterns - can lead to having a *Factory-Factory-Aggregation-Disposer-Delegate-Handler*... I didn't imply that's *necessarily* what you would end up with though :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:38:04.877",
"Id": "42094",
"ParentId": "42023",
"Score": "25"
}
},
{
"body": "<p>No - decoupling is not necessary at this stage. The very fact that you have doubts about its usefulness indicates that your application will work fine as it is. </p>\n\n<p>Instead, spend the effort on some good automated tests that will support you if the need comes in the future to refactor to a more complex implementation. </p>\n\n<p>Don't forget that every line of code you write brings with it future maintenance costs. By adding unnecessary complexity at this stage, it is quite possible that the overall cost is greater than if you only add the complexity when it's needed. Furthermore, if you ever actually get a use-case that justifies the complexity, it will come with requirements that allow you to do a better job of deciding <em>what</em> complexity to add.</p>\n\n<p>Trust your own judgement on this... or you could just use a Factory-Factory-Aggregation-Disposer-Delegate-Handler ... that should work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:54:51.133",
"Id": "72566",
"Score": "1",
"body": "Lol at the Factory-Facotry-Aggreation-Disposer-Delegate-Handler ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:58:43.700",
"Id": "72582",
"Score": "2",
"body": "*spend the effort on some good automated tests* - this is exactly where *low coupling / high cohesion*, DI and IoC come into play. Not all \"works fine\" code is *testable*. With the business logic tightly coupled with the data access, in my opinion *\"No - decoupling is not necessary at this stage\"* contradicts the idea of spending the effort on writing some good automated tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:27:08.873",
"Id": "72589",
"Score": "1",
"body": "It's a fair point Mat's Mug - decoupling is not justified for the code itself, but *may* be helpful for testability. In that case, writing the tests might lead to the refactoring - and yes - I accept that you probably want to design for testing in the first place, but then you have *something* that triggers the need for the extra complexity."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T08:47:39.857",
"Id": "42117",
"ParentId": "42023",
"Score": "3"
}
},
{
"body": "<p>Mainly not about decoupling:</p>\n\n<p>I agree with the idea that <code>SubmitReasons</code> should reuse the same connection, but it should possibly even set up a new <code>SqlTransaction</code> that includes all <code>ExecuteNonQuery</code> calls. I would go further and re-use the same <code>SqlCommand</code>, prepare the statement and re-use the same parameters.</p>\n\n<pre><code>public void SubmitReasons(DataTable dtSubmit)\n{\n using (var conn = new SqlConnection(ConnectionStrings.P21ConnectionString))\n {\n conn.Open();\n using (var transaction = conn.BeginTransaction())\n using (var cmd = new SqlCommand(Resources.SubmitReasonString, conn, transaction))\n {\n // I assume that ids are ints and that a category is referenced by an id.\n var uid = cmd.Parameters.Add(\"@Uid\", SqlDbType.Int);\n var category = cmd.Parameters.Add(\"@Category\", SqlDbType.Int);\n var modified = cmd.Parameters.Add(\"@Modified\", SqlDbType.DateTime2);\n\n cmd.Prepare();\n\n foreach (var row in dtSubmit.Rows.Cast<DataRow>().Where(row => row.Field<string>(\"approved\") == \"Y\"))\n {\n uid.Value = row.Field<int>(\"stockout_reason_uid\");\n category.Value = row.Field<int>(\"approved_category\");\n modified.Value = DateTime.Now;\n\n cmd.ExecuteNonQuery();\n }\n\n transaction.Commit();\n }\n }\n}\n</code></pre>\n\n<p>What I still do not like about the design is that you leak fake booleans into your data layer by using \"Y/N\" instead of true/false. I really do not see why using a <code>string</code> would have any benefit over a real <code>bool</code>, especially since the actual value is not event surfaced to the user. Having a <code>== \"Y\"</code> check in a data access method should be avoided IMHO.</p>\n\n<p><code>ReasonData</code> should be the class in charge of disposing it's <code>ReasonTable</code> if you want it to be disposed (in general, that <a href=\"https://stackoverflow.com/a/913286/11963\" title=\"Should I Dispose() DataSet and DataTable?\">does not seem to be necessary</a>). Also, there is currently no reason to have that set accessor to be public.</p>\n\n<pre><code>class ReasonData : IDisposable\n{\n public DataTable ReasonTable { get; private set; }\n // … \n public ReasonData()\n {\n this.ReasonTable = new DatabaseTransaction().GetReasons();\n GenerateAdditionalColumns();\n PopulateCategories();\n }\n\n public void Dispose()\n {\n this.Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (disposing && this.ReasonTable != null)\n {\n this.ReasonTable.Dispose();\n }\n }\n\n // …\n }\n}\n</code></pre>\n\n<p>Do not dispose <code>ReasonData.ReasonTable</code> or <code>ReasonData</code> in <code>CloseButton_Click</code>, but in the <a href=\"https://stackoverflow.com/a/1052186/11963\" title=\"How do I extend a WinForm's Dispose method?\">form's <code>Dispose</code> method</a>.</p>\n\n<p>You should not wrap the returned <code>DataTable</code> in <code>GetReasons</code> in a <code>using</code> block. Even though that <a href=\"https://stackoverflow.com/a/913286/11963\" title=\"Should I Dispose() DataSet and DataTable?\">probably does not do anything</a>, you are actually returning a fully disposed object, so it is not really obvious that the <code>dt</code> object is supposed to be used after it is returned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-15T12:03:38.567",
"Id": "57081",
"ParentId": "42023",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "42094",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:13:13.890",
"Id": "42023",
"Score": "16",
"Tags": [
"c#",
"design-patterns",
".net",
"winforms"
],
"Title": "Is decoupling necessary for very small applications?"
}
|
42023
|
Computer data logging is the process of recording events in a computer program, usually with a certain scope, in order to provide an audit trail that can be used to understand the activity of the system and to diagnose problems.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:17:03.080",
"Id": "42026",
"Score": "0",
"Tags": null,
"Title": null
}
|
42026
|
<p>An umbrella term for methods and algorithms to synchronize multithreaded environments or other forms of distributed system without using locks.</p>
<p>The necessity for lock-free software architectures arises mainly from performance and scalability issues with using locks for synchronization: Because of the atomicity requirements, Locks involve slow system calls and if used improperly, can easily lead to race conditions and frequent wait conditions.</p>
<p>Examples of lock-free system architectures include <a href="https://en.wikipedia.org/wiki/Hardware_transactional_memory" rel="nofollow noreferrer">Hardware-Transactional Memory</a> (the software variant <a href="https://en.wikipedia.org/wiki/Software_transactional_memory" rel="nofollow noreferrer">STM</a> might use locks for synchronization) or the <a href="https://en.wikipedia.org/wiki/Communicating_sequential_processes" rel="nofollow noreferrer">Communicating sequential processes</a> first described by <a href="https://en.wikipedia.org/wiki/C._A._R._Hoare" rel="nofollow noreferrer">C. A. R. Hoare</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-18T23:41:38.963",
"Id": "42028",
"Score": "0",
"Tags": null,
"Title": null
}
|
42028
|
An umbrella term for methods and algorithms to synchronize multithreaded environments or other forms of distributed system without using locks.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:41:38.963",
"Id": "42029",
"Score": "0",
"Tags": null,
"Title": null
}
|
42029
|
<p>I wrote the following simple Perl script to read lines from <code>stdin</code> that are the output from a <code>psql</code> call that returns lines of the form <code>key1 | key2 | long text field</code> and create a separate output file for each line, whose name is key1_key2_NNN.txt, where NNN is just a counter to ensure unique file names.</p>
<pre><code>my $count = 0;
while (<>) {
if (/(.*)\|(.*)\|(.*)/) {
$count++;
my $outname = "$1_$2_$count.txt";
my $text = $3;
$outname =~ s/\s+//g;
my $outfile = new IO::File("> $outname");
$outfile->print("$text");
}
}
</code></pre>
<p>This does the trick, but there are 2 things I'm not thrilled about</p>
<ol>
<li><p>I'd like to be able to do the <code>$count++</code> inline while putting the incremented number into the string, but I'm not sure how to not just get <code>0++</code> plugged in (i.e. how to make it know that the <code>++</code> is a command and not part of the literal string).</p></li>
<li><p>I don't like that I have to save <code>$3</code> to another variable, but if I don't, it gets cleared out before I need it.</p></li>
</ol>
<p>Anyhow, any suggestions on making this a bit more slick?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:58:48.040",
"Id": "72411",
"Score": "4",
"body": "Why would you want to parse `psql` output instead of using `DBI` to query the database directly?"
}
] |
[
{
"body": "<p>I don't know if this is the complete script, but the absence of <code>use strict; use warnings</code> is pretty noticeable. Always use these as a basic safety net, no matter how small or simple your program.</p>\n\n<hr>\n\n<p>Your usage of the regex <code>/(.*)\\|(.*)\\|(.*)/</code> can be improved in some ways:</p>\n\n<ul>\n<li><p>Don't use a regex to extract the data. Instead: <code>my @cols = split /[|]/, $_, 3;</code>. This really is the correct way to go, the following points however deal with normal regex usage.</p></li>\n<li><p>Some guides recommend putting special characters into a character class <code>[|]</code> instead of escaping them <code>\\|</code>. It's my experience that this makes complicated regexes easier to read.</p></li>\n<li><p><em>Immediately</em> after matching, assign the values of the captures to permanent variables. Otherwise, they could be modified by a subroutine you call – the next match can clear those values. Note also that ways exist to booby trap such an innocent-looking operation like incrementing an integer to clear the last match.</p>\n\n<p>So we either write code such as:</p>\n\n<pre><code>if (/(.*)[|](.*)[|](.*)/) {\n my @fields = ($1, $2, $3);\n ...\n}\n</code></pre>\n\n<p>or we don't use the capture variables at all, and use the regex in list context instead:</p>\n\n<pre><code>if (my @fields = /(.*)[|](.*)[|](.*)/) { ... }\n</code></pre>\n\n<p>Technically, this isn't absolutely equivalent (e.g. in case you aren't using any captures, or if some captures are conditional, or …), but it's far better style.</p>\n\n<p>If course, you'd assign to a list of names rather than an array:</p>\n\n<pre><code>my ($name_a, $name_b, $text) = ...\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>The substitution <code>s/\\s+//g</code> might be considered slightly silly, as it's equivalent to <code>s/\\s//g</code>. The former variant has the advantage of less substitution operations, so it might actually be preferable. But why are you sanitizing the <code>$outname</code> rather than the parts of which it's made up? Note that you can apply a substitution to multiple variables like</p>\n\n<pre><code> s/\\s+//g for $x, $y;\n</code></pre>\n\n<p>If you don't want to remove all space in those strings (remember that most filesystems can deal with spaces in filenames all right) but only at the start or beginning of the string, you might want to <code>split</code> with a different separator instead:</p>\n\n<pre><code>split /\\s*[|]\\s*/, ...\n</code></pre>\n\n<hr>\n\n<p>The expression <code>\"$1_$2_$count.txt\"</code> does not contain a bug, but this is accidental. For example, <code>\"$foo_$bar\"</code> is equivalent to <code>$foo_ . $bar</code> – underscores can be part of variable names, but variables can't start with numbers, so the problem isn't visible here (variable names can consist solely of numbers, and all such variables are reserved for capture groups).</p>\n\n<p>As a fix, use curly braces to delimit the variable names: <code>\"${1}_${2}_$count.txt\"</code>, or use <code>sprintf</code>:</p>\n\n<pre><code>sprintf '%s_%s_%d.txt', $1, $2, $count\n</code></pre>\n\n<hr>\n\n<p>The line <code>my $outfile = new IO::File(\"> $outname\");</code> is a big no-no for two reasons:</p>\n\n<ol>\n<li><p>Don't use the “indirect object notation” <code>method $object @arglist</code>. Instead use <code>$object->method(@arglist)</code>. The former variant may look nicer, but is often ambiguous, has rather confusing precedence, and widely considered to be a syntactic mistake.</p>\n\n<p>If you need help to get rid of that habit, you may enjoy the <a href=\"https://metacpan.org/pod/indirect\" rel=\"nofollow\"><code>no indirect</code></a> pragma.</p></li>\n<li><p>What you're doing is basically <code>open my $outfile, \"> $outname\"</code>. Use the three-argument form of open:</p>\n\n<pre><code>open my $outfile, \">\", $outname\n</code></pre>\n\n<p>or in the object-oriented wrapper: <code>IO::File->new($outname, '>')</code>.</p>\n\n<p>The next problem here is that you aren't doing any error handling! Check the return value of the constructor to assert that you could actually open the file. Well, calling a method on an undefined value will <code>die</code>, but checking manually allows you to output a sensible error message.</p></li>\n</ol>\n\n<hr>\n\n<p>The <code>$outfile->print(\"$text\")</code> would usually be written <code>print { $outfile } $text</code>. For one thing, the object-oriented interface to file handles is used very rarely. You can use the normal interface directly. Also, you are unnecessarily stringifying the <code>$text</code>. If it isn't already a string, that will be managed by <code>print</code>. Note that explicit stringification creates a copy of that value, something which you would usually (but not always) want to avoid.</p>\n\n<p>Then, you are using <code>print</code>, not <code>say</code>. This means (together with the fact that in a regex, <code>.</code> does not match newlines), that you won't end your output to the file with a newline. This is probably an oversight.</p>\n\n<hr>\n\n<p>Another aspect that just came to my mind is that your input file could contain slashes, allowing a filename like <code>/you/were/pwned/_key2_1234.txt</code> to be created (assuming the path already exists). Let's put in a bit of validation.</p>\n\n<hr>\n\n<p>The script now looks like:</p>\n\n<pre><code>use strict;\nuse warnings;\nuse autodie; # easier than explicit, manual error handling\nuse feature qw/say/; # say is like print, but appends newline\n\nmy $count = 0;\nwhile (my $line = <>) {\n chomp $line;\n my ($name_a, $name_b, $text) = split /[|]/, $line, 3\n or next;\n for ($name_a, $name_b) {\n s/\\s+//g;\n die qq(The first two columns in \"$line\" may not contain slashes) if m[/];\n }\n my $filename = sprintf '%s_%s_%d.txt', $name_a, $name_b, ++$count;\n open my $fh, \">\", $filename;\n say { $fh } $text;\n}\n</code></pre>\n\n<p>How did this solve your problems?</p>\n\n<ul>\n<li>Use <code>sprintf</code> to format a string with a variable you want to increment at the same time</li>\n<li>Assigning captures to variables is a best practice, and should <em>always</em> be done.</li>\n</ul>\n\n<p>As <a href=\"https://codereview.stackexchange.com/questions/42030/parsing-psql-output-into-multiple-files#comment72411_42030\">200_success mentioned</a>, it is rather suspect that you are using a command-line tool to interface with a database. Perl has the excellent <a href=\"https://codereview.stackexchange.com/questions/42030/parsing-psql-output-into-multiple-files#comment72411_42030\"><code>DBI</code> modules</a> which provides a common frontend for various SQL databases. The docs have some simple examples which should get you rapidly started. Using such a module is safer (less escaping levels) and faster (no extra process, no tempfiles, prepared statements, …). Have fun exploring all the great DBI features!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:46:47.807",
"Id": "42088",
"ParentId": "42030",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "42088",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:41:47.143",
"Id": "42030",
"Score": "3",
"Tags": [
"parsing",
"perl"
],
"Title": "Parsing psql output into multiple files"
}
|
42030
|
<p>Modules are simply just a convenient way to break down the main problem and divided into many sub problems/solutions. This way the main problem can be broken down into solutions that a team can work on. A module could consist of a the printing functionality of program. This can be handed to one programmer. The GUI (Graphical User Interface) could be another module, handed to another programmer, and so forth.</p>
<p>Modular design is meant to improve efficiency and speed of development by allowing programmers to work on specific aspects of the program independently of each other.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:42:25.467",
"Id": "42031",
"Score": "0",
"Tags": null,
"Title": null
}
|
42031
|
A logical subdivision of a larger, more complex system.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:42:25.467",
"Id": "42032",
"Score": "0",
"Tags": null,
"Title": null
}
|
42032
|
Code that handles a condition (normally an error condition) triggered when an event fails to occur within a predefined time limit. For discussing inefficient code that takes an unreasonable amount of time to finish, use the [time-limit-exceeded] tag instead.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:42:56.937",
"Id": "42034",
"Score": "0",
"Tags": null,
"Title": null
}
|
42034
|
<p><strong>Property</strong>, in some object-oriented programming languages, is a special sort of class member, intermediate between a field (or data member) and a method. </p>
<p>Properties are read and written like fields, but property reads and writes are (usually) translated to get and set method calls. The field-like syntax is said to be easier to read and write than lots of method calls, yet the interposition of method calls allows for data validation, active updating (as of GUI visuals), or read-only 'fields'. That is, properties are intermediate between member code (methods) and member data (instance variables) of the class, and properties provide a higher level of encapsulation than public fields.</p>
<p><strong>See:</strong> </p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Property_%28programming%29" rel="nofollow">Property (programming)</a></li>
<li><a href="http://en.wikipedia.org/wiki/Bound_property" rel="nofollow">Bound property</a> </li>
<li><a href="http://en.wikipedia.org/wiki/Field_%28computer_science%29" rel="nofollow">Field (computer science)</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/65zdfbdt%28v=vs.110%29.aspx" rel="nofollow">Properties in .NET</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:43:31.987",
"Id": "42035",
"Score": "0",
"Tags": null,
"Title": null
}
|
42035
|
<p>Pagination is the process of dividing information into discrete pages. Pagination is often used for the purpose of printing or searching information.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:44:06.257",
"Id": "42037",
"Score": "0",
"Tags": null,
"Title": null
}
|
42037
|
Pagination is the process of dividing information into discrete pages.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:44:06.257",
"Id": "42038",
"Score": "0",
"Tags": null,
"Title": null
}
|
42038
|
<p><strong><a href="https://developers.google.com/appengine/" rel="nofollow">Google App Engine</a></strong> is a cloud computing technology for hosting web applications in Google-managed data centers.</p>
<p>Google App Engine lets you run your web applications on Google's infrastructure;
applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow:</p>
<ul>
<li><strong>Zero to sixty</strong>: Scale your app automatically without worrying about managing machines.</li>
<li><strong>Supercharged APIs</strong>: Supercharge your app with services such as Task Queue, XMPP, and Cloud SQL, all powered by the same infrastructure that powers the Google services you use every day.</li>
<li><strong>You're in control</strong>: Manage your application with a simple, web-based dashboard allowing you to customize your app's performance.</li>
</ul>
<p>With App Engine, there are no servers to maintain: You just upload your application, and it's ready to serve your users.</p>
<p>As of March 5th, 2012, <a href="https://groups.google.com/forum/#!topic/google-appengine-java/8zQtq_m9W5w" rel="nofollow">Stack Overflow is Google's official community support channel for technical App Engine questions</a> under the <a href="/questions/tagged/google-app-engine" class="post-tag" title="show questions tagged 'google-app-engine'" rel="tag">google-app-engine</a> tag. Developers should continue to use the <a href="https://groups.google.com/forum/#!forum/google-appengine" rel="nofollow">discussion forum</a> for topics that are not a good fit for the Stack Overflow format and the <a href="https://code.google.com/p/googleappengine/wiki/FilingIssues" rel="nofollow">AppEngine Google Code page</a> for reporting defects.</p>
<p>Many <a href="/questions/tagged/google-app-engine" class="post-tag" title="show questions tagged 'google-app-engine'" rel="tag">google-app-engine</a> questions are specific to their SDK for <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a>, <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a>, <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a> or <a href="/questions/tagged/go" class="post-tag" title="show questions tagged 'go'" rel="tag">go</a>. Please include the appropriate language tag with those questions.</p>
<h3>More information</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Google_App_Engine" rel="nofollow">Google App Engine Wikipedia Article</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:45:30.997",
"Id": "42039",
"Score": "0",
"Tags": null,
"Title": null
}
|
42039
|
Google App Engine is a cloud computing technology for hosting web applications in Google-managed data centers. Google App Engine is a Platform as a Service (PaaS) offering for Java, Python, Go (experimental) and PHP (beta).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:45:30.997",
"Id": "42040",
"Score": "0",
"Tags": null,
"Title": null
}
|
42040
|
Data is any form of information that can be used by a process, service, or application. This is generic terminology - consider a more specific taxonomy when posting.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:46:19.360",
"Id": "42042",
"Score": "0",
"Tags": null,
"Title": null
}
|
42042
|
A software application that services requests from clients using a data transfer protocol.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:47:21.347",
"Id": "42044",
"Score": "0",
"Tags": null,
"Title": null
}
|
42044
|
<p>Transmission Control Protocol (TCP) is a transport layer protocol that provides a connection-oriented data stream service with guaranteed, in-order delivery on top of the underlying packet-oriented, unreliable IP layer. TCP is referred to as a <em>connection-oriented</em> protocol. This is opposed to UDP, which offers a relatively bare-bones unreliable all-or-nothing delivery of discrete packets and referred to as a <em>connection-less</em> protocol.</p>
<p>There is more information at the <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" rel="nofollow">Wikipedia article on TCP</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:47:51.473",
"Id": "42045",
"Score": "0",
"Tags": null,
"Title": null
}
|
42045
|
Transmission Control Protocol (TCP) is a transport layer protocol that provides a connection-oriented data stream service with guaranteed, in-order delivery.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:47:51.473",
"Id": "42046",
"Score": "0",
"Tags": null,
"Title": null
}
|
42046
|
Event handling is a coding pattern related to acting on messages between a source and one or more subscribers. A point listener in the source provides a way in which subscribed code can consume messages raised from the source.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:49:02.277",
"Id": "42048",
"Score": "0",
"Tags": null,
"Title": null
}
|
42048
|
<p>Express is a minimal and flexible Node.js web application framework, providing a robust set of features (regex-based routing, sessions, multiple view / templating engines) for building single and multi-page, and hybrid web applications.</p>
<p>It uses <a href="http://www.senchalabs.org/connect/" rel="nofollow">Connect</a> to provide a powerful middleware layer.</p>
<p>The official website of Express is <a href="http://expressjs.com" rel="nofollow">expressjs.com</a>.</p>
<p><strong>Useful links:</strong></p>
<ul>
<li><a href="https://github.com/visionmedia/express/tree/master/examples" rel="nofollow">Express examples on GitHub</a></li>
<li><a href="http://nodetuts.com/" rel="nofollow">Node Tuts</a></li>
<li><a href="http://howtonode.org/getting-started-with-express" rel="nofollow">Getting Started with Express</a></li>
<li><a href="http://www.hacksparrow.com/express-js-tutorial.html" rel="nofollow">Express.js Tutorial</a></li>
<li><a href="http://runnable.com/express" rel="nofollow">Express Code Examples on Runnable</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:51:02.690",
"Id": "42049",
"Score": "0",
"Tags": null,
"Title": null
}
|
42049
|
Express is a minimal and flexible Node.js web application framework, providing a robust set of features (regex-based routing, sessions, multiple view / templating engines) for building single and multi-page, and hybrid web applications.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:51:02.690",
"Id": "42050",
"Score": "0",
"Tags": null,
"Title": null
}
|
42050
|
<p><em>Authentication</em> is the process of determining whether someone or something is, in fact, who or what it is declared to be - the act of confirming the truth of an attribute of a datum or entity. This might involve confirming the identity of a person or software program, tracing the origins of an artifact, or ensuring that a product is what its packaging and labeling claims to be. Authentication often involves verifying the validity of at least one form of identification.</p>
<p>The <strong>first type</strong> of authentication is accepting proof of identity given by a credible person who has evidence on the said identity, or on the originator and the object under assessment as the originator's artifact respectively.</p>
<p>The <strong>second type</strong> of authentication is comparing the attributes of the object itself to what is known about objects of that origin. For example, an art expert might look for similarities in the style of painting, check the location and form of a signature, or compare the object to an old photograph</p>
<p>The <strong>third type</strong> of authentication relies on documentation or other external affirmations. </p>
<h2>Resources</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Authentication" rel="nofollow">Authentication - Wikipedia</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:00:51.090",
"Id": "42052",
"Score": "0",
"Tags": null,
"Title": null
}
|
42052
|
Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:00:51.090",
"Id": "42053",
"Score": "0",
"Tags": null,
"Title": null
}
|
42053
|
<p>Operator overloading is a feature of some programming languages that allows custom implementations for operators depending on the types of the operands involved. Some languages allow new operators to be defined while others only allow redefinition of existing ones.</p>
<p>More information on <a href="http://en.wikipedia.org/wiki/Operator_overloading" rel="nofollow">Wikipedia</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:04:05.700",
"Id": "42054",
"Score": "0",
"Tags": null,
"Title": null
}
|
42054
|
Operator overloading is a feature of some programming languages that allows custom implementations for operators depending on the types of the operands involved. Some languages allow new operators to be defined while others only allow redefinition of existing ones.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:04:05.700",
"Id": "42055",
"Score": "0",
"Tags": null,
"Title": null
}
|
42055
|
<h2>Wiki</h2>
<p><strong><code>Electronic mail</code></strong>, commonly called email or <strong><code>e-mail</code></strong>, is a method of exchanging digital messages from an author to one or more recipients.</p>
<p>Modern email operates <strong>across the Internet</strong> or other computer networks. Some early email systems required that the author and the recipient both be online at the same time, also known as <strong><code>Instant messaging</code></strong>. Today's email systems are based on a <strong>store-and-forward</strong> model. Email servers accept, forward, deliver and store messages. Neither the users nor their computers are required to be online simultaneously; they need connect only briefly, typically to an email server, for as long as it takes to send or receive messages.</p>
<p>In other words <strong><code>e-mail</code></strong> is an <strong>Internet service</strong> that allows those people who have an e-mail address (accounts) to send and receive electronic letters. Those are much like postal letters, except that they are delivered much <strong>faster</strong> than snail mail when sending over long distances, and are usually free.</p>
<h2>Source</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Email" rel="nofollow">Email (Wikipedia)</a></li>
<li><a href="http://simple.wikipedia.org/wiki/E-mail" rel="nofollow">http://simple.wikipedia.org/wiki/E-mail</a></li>
<li><a href="http://computer.howstuffworks.com/e-mail-messaging/email.htm" rel="nofollow">http://computer.howstuffworks.com/e-mail-messaging/email.htm</a></li>
</ul>
<h2>Tag usage</h2>
<p>The tag <a href="/questions/tagged/email" class="post-tag" title="show questions tagged 'email'" rel="tag">email</a> can be used for all web based programming related problems in implementing feature of emailing a message from one client to another client. The tag can also be used for setting up a simple mail server. Please note that <strong><a href="http://serverfault.com/">http://serverfault.com/</a></strong> is another stackexchange website where you can ask <strong><code>e-mail</code></strong> server related specific problems.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:05:22.970",
"Id": "42056",
"Score": "0",
"Tags": null,
"Title": null
}
|
42056
|
Method of exchanging digital messages from an author to one or more recipients.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:05:22.970",
"Id": "42057",
"Score": "0",
"Tags": null,
"Title": null
}
|
42057
|
<p>The <code>.htaccess</code> file is a configuration file for the Apache web server, allowing configuration settings to be made at a directory-specific level, overriding the server-wide or site-level settings in the main Apache server-level configuration. It must be enabled in the server-level configuration to work.</p>
<p>Most directory-specific (though not all) Apache settings can be configured in <code>.htaccess</code>. One of the most common usages for it is URL redirection using mod_rewrite, which is used by many sites for SEO purposes and to provide easier-to-read URLs. The Apache documentation also has <a href="http://httpd.apache.org/docs/current/mod/mod_rewrite.html" rel="nofollow">further information about mod_rewrite</a> as well as <a href="http://wiki.apache.org/httpd/WhenNotToUseRewrite" rel="nofollow">simpler solutions for many common use cases</a>.</p>
<p><code>.htaccess</code> files can also be used for specifying custom error pages (e.g. for 404 errors); directory-specific security and user authentication; configuring the PHP installation; file handlers and MIME types; output compression, and more.</p>
<p>For more information on <code>.htaccess</code> files and how to use them, see the <a href="http://httpd.apache.org/docs/current/howto/htaccess.html" rel="nofollow">Apache documentation</a>.</p>
<h3>More information</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/.htaccess" rel="nofollow">.htaccess Wikipedia Article</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:06:14.770",
"Id": "42058",
"Score": "0",
"Tags": null,
"Title": null
}
|
42058
|
<p>cURL is primarily a command-line tool for transferring data using several protocols such as HTTP, HTTPS, FTP, FTPS, TFTP, SCP, SFTP, IMAP, POP3, IMAP and FILE. For example, cURL can be used to download a web page and save it to a file:</p>
<pre><code>curl -o curltest.html www.example.com
</code></pre>
<p>curl is powered by the libcurl library, which provides the underlying protocol transfer abilities.</p>
<p><a href="/questions/tagged/libcurl" class="post-tag" title="show questions tagged 'libcurl'" rel="tag">libcurl</a> has <a href="http://curl.haxx.se/libcurl/" rel="nofollow">bindings</a> for a number of languages. The PHP binding is known as PHP/CURL, or sometimes just as CURL (which can be confusing).</p>
<h2>Questions:</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/28395/passing-post-values-with-curl">http://stackoverflow.com/questions/28395/passing-post-values-with-curl</a></li>
<li><a href="http://stackoverflow.com/questions/871431/raw-post-using-curl-in-php">http://stackoverflow.com/questions/871431/raw-post-using-curl-in-php</a></li>
<li><a href="http://stackoverflow.com/questions/728274/php-curl-post-to-login-to-wordpress">http://stackoverflow.com/questions/728274/php-curl-post-to-login-to-wordpress</a></li>
</ul>
<h2>Resources:</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/CURL" rel="nofollow">cURL Wikipedia Article</a></li>
<li><a href="http://curl.haxx.se/" rel="nofollow">cURL Website</a></li>
<li><a href="http://curl.haxx.se/docs/manpage.html" rel="nofollow">cURL Document</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:06:44.727",
"Id": "42060",
"Score": "0",
"Tags": null,
"Title": null
}
|
42060
|
cURL is a library and command-line tool for transferring data using several protocols such as HTTP, FTP and Telnet.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:06:44.727",
"Id": "42061",
"Score": "0",
"Tags": null,
"Title": null
}
|
42061
|
<p>In computing, <a href="http://en.wikipedia.org/wiki/Layout_%28computing%29" rel="nofollow">layout</a> is the process of calculating the position of objects in space subject to various constraints. This functionality can be part of an application or packaged as a reusable component or library.</p>
<p><strong>Examples:</strong></p>
<ul>
<li><a href="http://developer.android.com/guide/topics/ui/layout/linear.html" rel="nofollow">Linear Layout</a></li>
<li><a href="http://developer.android.com/guide/topics/ui/layout/relative.html" rel="nofollow">Relative Layout</a></li>
<li><a href="http://developer.android.com/guide/topics/ui/layout/listview.html" rel="nofollow">List View</a></li>
<li><a href="http://developer.android.com/guide/topics/ui/layout/gridview.html" rel="nofollow">Grid</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:07:12.680",
"Id": "42062",
"Score": "0",
"Tags": null,
"Title": null
}
|
42062
|
The layout tag is for questions about the placement, alignment and justification of objects with respect to a containing element.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:07:12.680",
"Id": "42063",
"Score": "0",
"Tags": null,
"Title": null
}
|
42063
|
<h2>DataTable in .NET</h2>
<p>A DataTable is a .NET class that represents one table of in-memory data. Unlike other programming languages and platforms, a .NET DataTable is not a GUI control but rather a representation of a SQL table directly accessible in code and a source of data for other controls.</p>
<p>A <code>DataTable</code> may exist as part of a <code>DataSet</code>, which represents an in-memory relational data store. In that context, they can be connected through instances of the <code>DataRelation</code> class, and constrained by <code>ForeignKeyConstraint</code> or <code>UniqueConstraint</code> instances.</p>
<p>A <code>DataTable</code> has a set of <code>DataColumn</code> instances, which describe its schema. Data is stored in <code>DataRow</code> instances. </p>
<p>A <code>DataTable</code> may be sorted and filtered without changing the data by attaching it to a <code>DataView</code>. The sorted and filtered rows are then accessed as instances of the <code>DataRowView</code> class.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:07:48.590",
"Id": "42064",
"Score": "0",
"Tags": null,
"Title": null
}
|
42064
|
In .NET, DataTable is a class that represents a table of in-memory data. For the jQuery DataTables plugin, please use [jquery-datatables] tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:07:48.590",
"Id": "42065",
"Score": "0",
"Tags": null,
"Title": null
}
|
42065
|
<p><a href="http://d3js.org/" rel="nofollow">D3.js</a> (or D3 for Data-Driven Documents) is a small, open-source JavaScript visualization library for manipulating HTML and SVG documents based on arbitrary data attached to the <a href="/questions/tagged/dom" class="post-tag" title="show questions tagged 'dom'" rel="tag">dom</a>. Instead of being an all encompassing library, D3 solves the basis of the problem: efficient manipulation of documents based on data. The project is led by <a href="http://bost.ocks.org/mike/" rel="nofollow">Mike Bostock</a>. Additional information and <a href="https://github.com/mbostock/d3/wiki/Gallery" rel="nofollow">examples</a> can be found at the project home page.</p>
<p>References:</p>
<ul>
<li><a href="http://d3js.org/" rel="nofollow">Project home page</a></li>
<li><a href="https://github.com/mbostock/d3" rel="nofollow">GitHub Repository</a></li>
<li><a href="https://github.com/mbostock/d3/wiki" rel="nofollow">GitHub Wiki</a></li>
<li><a href="http://en.wikipedia.org/wiki/D3.js" rel="nofollow">Wikipedia Article</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:08:44.390",
"Id": "42066",
"Score": "0",
"Tags": null,
"Title": null
}
|
42066
|
D3.js is a small, open-source JavaScript visualization library for manipulating HTML and SVG documents based on data
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:08:44.390",
"Id": "42067",
"Score": "0",
"Tags": null,
"Title": null
}
|
42067
|
<p><a href="http://wiki.python.org/moin/TkInter" rel="nofollow">Tkinter</a> is the standard Python interface to the Tk graphical user interface (GUI) toolkit. Tkinter runs on all common Mac, Windows and Unix/Linux platforms, making it easy to create rich, cross-platform desktop applications with Python. </p>
<p><a href="/questions/tagged/tk" class="post-tag" title="show questions tagged 'tk'" rel="tag">tk</a>, the toolkit upon which Tkinter is based, is a mature, robust toolkit that has its roots in the <a href="/questions/tagged/tcl" class="post-tag" title="show questions tagged 'tcl'" rel="tag">tcl</a> language, but which can be used with many modern languages including <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a>, <a href="/questions/tagged/ruby" class="post-tag" title="show questions tagged 'ruby'" rel="tag">ruby</a>, <a href="/questions/tagged/perl" class="post-tag" title="show questions tagged 'perl'" rel="tag">perl</a> and others. Tk provides a native look and feel on Windows, Mac and Unix platforms. For more information about the cross-platform and cross-language features of Tk visit <a href="http://www.tkdocs.com" rel="nofollow">tkdocs.com</a>.</p>
<p>The following is a Python 2 sample program loosely based on the <a href="http://docs.python.org/2.7/library/tkinter.html#a-simple-hello-world-program" rel="nofollow">documentation example</a> but modified to avoid a global import. In Python 3 it is needed to change the import statement, since the module was renamed to <code>tkinter</code>.</p>
<pre><code>import Tkinter as tk
class Application(tk.Frame):
def say_hi(self):
print("Hello, world!")
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.quit = tk.Button(self, text="QUIT", command=self.quit, fg="red")
self.quit.pack(side="left")
self.hello = tk.Button(self, text="Hello", command=self.say_hi)
self.hello.pack(side="left")
root = tk.Tk()
app = Application(root)
app.pack(side="top", fill="both", expand=True)
app.mainloop()
</code></pre>
<p>Due to its power and maturity, tools such as <a href="http://easygui.sourceforge.net/" rel="nofollow">EasyGUI</a> (no longer maintained) have been written on top of Tkinter to make it even easier to use.</p>
<p><strong>References</strong>:</p>
<ul>
<li><a href="http://docs.python.org/3.3/library/tk.html" rel="nofollow">Graphical User Interfaces with Tk</a></li>
<li><a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html" rel="nofollow">Tkinter 8.5 reference: a GUI for Python</a></li>
<li><a href="http://effbot.org/tkinterbook/" rel="nofollow">An Introduction to Tkinter</a></li>
<li><a href="http://www.pythonware.com/library/tkinter/introduction/index.htm" rel="nofollow">Fredrik Lundh’s introduction to Tkinter</a></li>
<li><a href="http://www.tcl.tk/man/tcl8.5/" rel="nofollow">Tcl/Tk 8.5 Manual</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:09:20.877",
"Id": "42068",
"Score": "0",
"Tags": null,
"Title": null
}
|
42068
|
Tkinter is the standard Python interface to the "Tk" graphical user interface toolkit.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:09:20.877",
"Id": "42069",
"Score": "0",
"Tags": null,
"Title": null
}
|
42069
|
<p>A monad in programming is a <em>composable computation description</em>. Monads are an important construct in functional languages like Haskell.</p>
<p>In Haskell, a Monad is simply any type <code>m</code> with two functions following several algebraic laws:</p>
<pre><code>return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
</code></pre>
<p>These types can be used for a wide variety of different tasks including: IO, continuations, coroutines, non-determinism, error-handling, mutable state and even parsing. In addition, they are particularly useful for embedding simple DSLs within a functional language like Haskell.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:10:35.413",
"Id": "42070",
"Score": "0",
"Tags": null,
"Title": null
}
|
42070
|
A monad in programming is a composable computation description. Monads are an important construct in functional programming languages like Haskell.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:10:35.413",
"Id": "42071",
"Score": "0",
"Tags": null,
"Title": null
}
|
42071
|
<h1>Active Record</h1>
<p>The active record pattern, which was named by Martin Fowler in 2003, is an architectural pattern that describes how objects relate to database records or entries in other forms of storage. The interface to such an object would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the attributes in the underlying stored entity.</p>
<h2>Ruby library ambiguity</h2>
<p>The Ruby library ActiveRecord, created by David Heinemeier Hansson in 2004 as part of the Ruby on Rails framework, is an implementation of the pattern with the same name. However, it is important that the pattern and the Ruby library should not be considered synonyms. For the Ruby-specific Stack Overflow tag, check <a href="http://stackoverflow.com/questions/tagged/rails-activerecord">rails-activerecord</a>.</p>
<h2>Resources</h2>
<ul>
<li><a href="http://books.google.co.id/books?id=FyWZt5DdvFkC&lpg=PA1&dq=Patterns%20of%20Enterprise%20Application%20Architecture%20by%20Martin%20Fowler&pg=PT187&redir_esc=y#v=onepage&q=active%20record&f=false" rel="nofollow">Fowler, Martin (2003)</a></li>
<li><a href="http://en.wikipedia.org/wiki/Active_record" rel="nofollow">Wikipedia</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:12:19.530",
"Id": "42072",
"Score": "0",
"Tags": null,
"Title": null
}
|
42072
|
Active Record is a pattern that combines domain logic with storage abstraction in single object.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:12:19.530",
"Id": "42073",
"Score": "0",
"Tags": null,
"Title": null
}
|
42073
|
<h1>Framework</h1>
<p>A framework is a set of code or libraries which provide functionality common to a whole class of applications. While one library will usually provide one specific piece of functionality, frameworks will offer a broader range which are all often used by one type of application. Rather than rewriting commonly used logic, a programmer can leverage a framework which provides often used functionality, limiting the time required to build an application and reducing the possibility of introducing new bugs.</p>
<h2>Resources</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Software_framework" rel="nofollow">Wikipedia</a></li>
<li><a href="http://docforge.com/wiki/Framework" rel="nofollow">DocForge</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:12:59.237",
"Id": "42074",
"Score": "0",
"Tags": null,
"Title": null
}
|
42074
|
A framework is an existing library or set of libraries to help you complete a common task faster and more easily. Use this tag if you're writing a framework, not if you're just using one. When using a framework the specific framework should be used instead of this tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:12:59.237",
"Id": "42075",
"Score": "0",
"Tags": null,
"Title": null
}
|
42075
|
<p>"Null" has different meanings depending on context.</p>
<h3>Set theory</h3>
<p>Null is another name for the empty set, denoted by the symbol ∅. For this reason, some programming languages use <code>null</code> or <code>nil</code> for the empty list or empty tuple. Lisp uses <code>nil</code> to mean the empty list and the boolean value false.</p>
<h3>Pointers and References</h3>
<p><code>Null</code>, in programming languages that support it, is the value of an uninitialized variable, a pointer that doesn't point to a meaningful memory address, or an object that fails to respond to any message.</p>
<blockquote>
<p>Nullable references were invented by C.A.R. Hoare in 1965 as part of the Algol W language. Hoare later described his invention as a "billion-dollar mistake".</p>
</blockquote>
<p>For more information, see <a href="http://en.wikipedia.org/wiki/Null_pointer#Null_pointer" rel="nofollow">this Wikipedia article</a>.</p>
<h3>Relational Databases</h3>
<p><code>NULL</code> as a special marker in SQL or a relational database stands in place of a value that is missing, or in a join means "no corresponding row." The operators <code>IS NULL</code> and <code>IS NOT NULL</code> are required for comparisons to a literal <code>null</code>: other comparisons between <code>NULL</code> and any value evaluate to "unknown."</p>
<p>For more information, see <a href="http://en.wikipedia.org/wiki/Null_%28SQL%29" rel="nofollow">this Wikipedia article</a>.</p>
<h3>ASCII</h3>
<p><code>Null</code> or <code>NUL</code> is the name given to the character with ASCII code zero (<code>0</code>) - i.e. hex <code>00</code>. In some languages, notably C, <code>NUL</code> is used to mark the end of a character string.</p>
<p>For more information, see <a href="http://en.wikipedia.org/wiki/Null_character" rel="nofollow">this Wikipedia article</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:18:44.993",
"Id": "42076",
"Score": "0",
"Tags": null,
"Title": null
}
|
42076
|
This tag should be used for questions where you are handling null variables or values.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:18:44.993",
"Id": "42077",
"Score": "0",
"Tags": null,
"Title": null
}
|
42077
|
<p>a proxy server is a server that acts as an intermediary for requests from clients seeking resources from other servers. A client connects to the proxy server, requesting some service, such as a file, connection or a web page available from a different server and the proxy server evaluates the request as a way to simplify and control its complexity. </p>
<hr>
<h2>Purpose</h2>
<p>Many users worry about what kind of information can be traced back to them. Internet proxy servers can be used, as an intermediary so that the sites never directly connect to the host network. Some websites block certain Internet users by geography, so using a Web proxy located in the Web host's country will allow foreign users to use the website.</p>
<hr>
<h2>References</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Proxy_server" rel="nofollow">Proxy server on Wikipedia</a></li>
<li><a href="http://techtips.salon.com/proxy-definition-computers-12574.html" rel="nofollow">Proxy Definition</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:19:13.933",
"Id": "42078",
"Score": "0",
"Tags": null,
"Title": null
}
|
42078
|
A proxy is a device or program that stands between two or more interconnected programs or devices. Reasons for a proxy include one or more connected parties only wanting the other to access specific data. A proxy provides a method for this.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:19:13.933",
"Id": "42079",
"Score": "0",
"Tags": null,
"Title": null
}
|
42079
|
<p>SSE, first introduced with the Pentium III in 1999, was Intel's reply to AMD's 3DNow extension in 1998.</p>
<p>SSE can be considered somewhat half-hearted insofar as it only covered the most basic operations and suffered from severe limitations both in functionality and performance, making it mostly useful for a few select applications, such as audio or raster image processing.</p>
<p>Early SSE-enabled CPUs would share execution resources between the SSE and FPU unit which meant that there was no parallelism when both were used, current generation processors no longer have such limitations. Also, first generation SSE required a FPU mode change when interleaving operations with X87 arithmetic as a MMX legacy.</p>
<p>Most of SSE's limitations have been leveraged with the SSE2 instruction set, the only notable limitation remaining to date is the lack of horizontal addition or a dot product operation in both an efficient way and widely available. While SSE3 and SSE4.1 added horizontal add and dot product instructions, these exhibit huge latencies (often rivalling manual shuffle-add pairs) and do not yet have sufficient support among manufacturers.</p>
<p>The lack of cross-manufacturer support made software development with SSE a challenge during the initial years. With AMD's adoption of SSE2 into its 64bit processors during 2003/2004, this problem gradually disappeared. As of today, there exist virtually no processors without SSE/SSE2 support.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:20:57.787",
"Id": "42080",
"Score": "0",
"Tags": null,
"Title": null
}
|
42080
|
Streaming SIMD Extensions (SSE) is the first generation of SIMD Intel's instruction sets available on modern x86-compatible CPUs. SSE offers single-precision floating point arithmetic and integer arithmetic (excluding division) and logical operations on packed or single operands of sizes from 8 to 64 bits.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:20:57.787",
"Id": "42081",
"Score": "0",
"Tags": null,
"Title": null
}
|
42081
|
<p>The <a href="http://en.wikipedia.org/wiki/Windows_API" rel="nofollow">Windows API</a>, informally WinAPI, is Microsoft's core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. It was formerly called the Win32 API; however, the name Windows API more accurately reflects its roots in 16-bit Windows and its support on 64-bit Windows. Almost all Windows programs interact with the Windows API. You can find more help on the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff818516%28v=vs.85%29.aspx" rel="nofollow">Windows API Documentation</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:22:10.667",
"Id": "42082",
"Score": "0",
"Tags": null,
"Title": null
}
|
42082
|
<p><a href="http://docs.unity3d.com/Documentation/ScriptReference/index.html" rel="nofollow">Unity</a> (also called <code>Unity3D</code>) is a cross-platform game engine with a built-in IDE developed by <a href="http://unity3d.com/company/" rel="nofollow">Unity Technologies</a>. It is used to develop video games for web plugins, desktop platforms, consoles and mobile devices. The game engine was developed in C/C++. It is able to support code written in C#, Unity implementation of JavaScript (also known as UnityScript) and BooScript (an implementation of Python).</p>
<p>The latest update supports development for Windows, OS X, Linux, iOS, Android, Blackberry OS 10, Windows Phone 8, web browsers, PlayStation 3, Xbox 360, and Wii.</p>
<p><strong>Useful links:</strong></p>
<ul>
<li><a href="http://unity3d.com/unity/download" rel="nofollow">Unity3D Engine Download</a></li>
<li><a href="http://docs.unity3d.com/Documentation/Manual/index.html" rel="nofollow">Unity Manual</a></li>
<li><a href="http://docs.unity3d.com/Documentation/ScriptReference/index.html" rel="nofollow">Scripting Reference</a></li>
<li><a href="http://unity3d.com/gallery/made-with-unity/game-list" rel="nofollow">Games made with Unity3D</a></li>
<li><a href="http://www.unity3dstudent.com/" rel="nofollow">Unity3DStudent</a> (Non-official learning resources)</li>
<li><a href="http://unitygems.com/" rel="nofollow">Unity Gems</a> (A collection of tips and tricks on using Unity)</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:22:42.760",
"Id": "42084",
"Score": "0",
"Tags": null,
"Title": null
}
|
42084
|
Unity, also referred to as Unity3D, is a cross-platform game engine with a built-in IDE developed by Unity Technologies. It is a commercial development platform for creating games, interactive 3D applications, training simulations, and medical and architectural visualizations.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:22:42.760",
"Id": "42085",
"Score": "0",
"Tags": null,
"Title": null
}
|
42085
|
<p>I'm writing some simple emacs tools for visual studio solutions.</p>
<p>I've got a function <code>sln-process-csproj-file</code>. This function takes the path to a project, and returns a tuple that's just a data model of the innards of the project.</p>
<p>Right now the return value on the last line of that function is <code>`(,project-name ,project-path ,project-files)</code>.</p>
<p>I have written three getter functions to use with the list:</p>
<pre><code>(defun sln-project-name (project)
(nth 0 project))
(defun sln-project-path (project)
(nth 1 project))
(defun sln-project-files (project)
(nth 2 project))
</code></pre>
<p>Does this getter and setter boilerplate code match best practices? Is there a shorter way to write it?</p>
|
[] |
[
{
"body": "<p>Yes, it can be shortened by using <a href=\"http://www.gnu.org/software/emacs/manual/html_node/cl/Structures.html\"><code>defstruct</code></a>. An example from the docs:</p>\n\n<pre><code> (cl-defstruct person name age sex)\n (setq dave (make-person :name \"Dave\" :sex 'male))\n ⇒ [cl-struct-person \"Dave\" nil male]\n (setq other (copy-person dave))\n ⇒ [cl-struct-person \"Dave\" nil male]\n (eq dave other)\n ⇒ nil\n (eq (person-name dave) (person-name other))\n ⇒ t\n (person-p dave)\n ⇒ t\n (person-p [1 2 3 4])\n ⇒ nil\n (person-p \"Bogus\")\n ⇒ nil\n (person-p '[cl-struct-person counterfeit person object])\n ⇒ t\n</code></pre>\n\n<p>Alternatively, if you want something more heavy weight, there is a <a href=\"https://www.gnu.org/software/emacs/manual/html_mono/eieio.html\">CLOS-like object system</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:05:11.237",
"Id": "42091",
"ParentId": "42086",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "42091",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:35:42.147",
"Id": "42086",
"Score": "5",
"Tags": [
"lisp",
"elisp"
],
"Title": "Accessor functions in elisp"
}
|
42086
|
<p>I’m trying to make a simple gui app that starts a “long” process that can be started and stopped. The process generates random numbers and displays them in a JList. As numbers are being displayed (i.e. process is started), user can select a number from JList and delete.
<a href="http://mypages.valdosta.edu/dgibson/courses/cs4322/post.jpg" rel="noreferrer">gui and uml http://mypages.valdosta.edu/dgibson/courses/cs4322/post.jpg</a></p>
<p>I'm interested to know what improvements I could make to my approach. (And yes, I need to read TrashGod's posts on EDT and SwingWorker, I will!)</p>
<pre><code>public class MVC {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
create();
}
});
}
private static void create() {
RandomNumberModel model = new RandomNumberModel();
Controller controller = new Controller(model);
View view = new View(controller);
controller.setView(view);
JFrame f = new JFrame("EDT & Long Thread");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(view);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
public class View extends JPanel {
JList list;
DefaultListModel<Double> listModel;
JTextArea area;
JTextField field;
JButton btnGenerate = new JButton("Start Generation");
JButton btnStop = new JButton("Stop Generation");
JButton btnDelete = new JButton("Delete selected");
Controller controller;
public View(Controller controller) {
this.controller = controller;
this.setSize(new Dimension(600, 300));
// Create GUI components
listModel = new DefaultListModel<Double>();
list = new JList(listModel);
area = new JTextArea();
btnStop.setEnabled(false);
btnGenerate.addActionListener(controller);
btnStop.addActionListener(controller);
btnDelete.addActionListener(controller);
// Assemble GUI components
JPanel buttonPanel = new JPanel();
buttonPanel.add(btnGenerate);
buttonPanel.add(btnStop);
JPanel listPanel = new JPanel();
listPanel.setLayout(new BorderLayout());
listPanel.add(new JScrollPane(list));
listPanel.add(btnDelete, BorderLayout.SOUTH);
this.setLayout(new BorderLayout());
this.add(listPanel, BorderLayout.WEST);
this.add(buttonPanel, BorderLayout.SOUTH);
this.add(new JScrollPane(area));
}
}
public class Controller implements ActionListener {
static class ControlException extends Exception {}
static class StopGenException extends ControlException {}
View view;
RandomNumberModel model;
Thread thread = null;
volatile boolean isStopGen = false;
public Controller(RandomNumberModel model) {
this.model = model;
}
public void setView(View view) {
this.view = view;
}
public void actionPerformed(ActionEvent e) {
try {
if (view.btnGenerate.getActionCommand().equals(
e.getActionCommand())) {
view.listModel.clear();
startNumGen();
} else if (view.btnStop.getActionCommand().equals(
e.getActionCommand())) {
stopNumGen();
} else if (view.btnDelete.getActionCommand().equals(
e.getActionCommand())) {
deleteElement();
}
}
catch (ControlException exc) {
System.out.println(exc);
}
}
public void startNumGen() throws ControlException {
thread = new Thread(new Runnable() {
public void run() {
try {
doGeneration();
}
catch (ControlException exc) {
System.out.println("Stopped " + exc);
}
catch (InterruptedException exc) {
System.out.println("Interrupted " + exc);
}
finally {
view.btnGenerate.setEnabled(true);
view.btnStop.setEnabled(false);
isStopGen = false;
}
}
});
view.btnGenerate.setEnabled(false);
view.btnStop.setEnabled(true);
thread.start();
}
private void doGeneration() throws StopGenException, InterruptedException {
for(int i=0; i<10; i++) {
if( isStopGen) {
throw new StopGenException();
}
final double val = model.getRandomNum();
EventQueue.invokeLater(new Runnable() {
public void run() {
view.listModel.addElement(val);
}
});
}
}
public void stopNumGen() {
System.out.println("Stop generation");
isStopGen = true;
}
public void deleteElement() {
System.out.println("Delete number");
int indices[] = view.list.getSelectedIndices();
for (int i = 0; i < indices.length; i++) {
final int index = indices[indices.length - 1 - i];
System.out.print("Index: " + index);
double val = view.listModel.get(index);
System.out.println(", Deleted val: " + val);
EventQueue.invokeLater(new Runnable() {
public void run() {
view.listModel.remove(index);
}
});
}
}
}
public class RandomNumberModel {
public double getRandomNum() throws InterruptedException {
Thread.sleep(500);
return Math.random();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:09:38.317",
"Id": "72446",
"Score": "0",
"body": "For reference, several complete examples may be found [here](http://stackoverflow.com/search?tab=votes&q=user%3a230513%20SwingWorker)."
}
] |
[
{
"body": "<p>Your code is well structured, and nice to read. This is a good thing.</p>\n\n<p>You appear, from what I can see, to be using the appropriate threads for doing swing, and non-swing work. This is good.</p>\n\n<p>There are a few thread-safe issues I can see:</p>\n\n<ul>\n<li><p><strong>Daemon Threads</strong> - where possible, you <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon%28boolean%29\" rel=\"nofollow\">should use Daemon threads for background tasks</a>. This makes the JVM shutdown easier, and is good practice for those times when you are not in a Swing environment (which does a 'hard' shutdown).</p>\n\n<pre><code>thread.setDaemon(true);\nthread.start();\n</code></pre></li>\n<li><p>There is a possible race condition in the action-listener... there could conceptually be multiple action events queued up for the <code>view.btnGenerate</code>. These actions could be queued <strong>before</strong> the button is disabled. This would result in you having two generator threads running at once. I would recommend something like:</p>\n\n<pre><code>private final AtomicBoolean generatorRunning = new AtomicBoolean(false);\n</code></pre>\n\n<p>then, in your <code>startNumGen</code> thread I would have:</p>\n\n<pre><code>if (!generatorRunning.compareAndSet(false, true)) {\n // already running....\n return false;\n}\n</code></pre>\n\n<p>this will gate the method explicitly... only one thread can start the generator (until it is stopped), and a thread can only start one of them (in case there are multiple queued events)...</p></li>\n<li><p>additionally, I would replace the <code>volatile isStopGen</code> with this <code>generatorRunning</code> AtomicBoolean. Volatile is a complicated concept, and the AtomicBoolean does the same thing, but with better semantics....</p>\n\n<p>you would replace the volatile <code>isStopGen</code> setting in the finally block with:</p>\n\n<pre><code> finally {\n view.btnGenerate.setEnabled(true);\n view.btnStop.setEnabled(false);\n generatorRunning.set(false);\n }\n</code></pre>\n\n<p>speaking of these semantics, you should check the <code>generatorRunning.get()</code> after the sleep, and before the set, rather than before the sleep. You have the risk here that you stop the generator, and then it still generates a value half a second later.... Your code could look like:</p>\n\n<pre><code>private void doGeneration() throws StopGenException, InterruptedException {\n for(int i=0; i<10; i++) {\n final double val = model.getRandomNum();\n\n // check after sleep... \n if( !generatorRunning.get()) {\n throw new StopGenException();\n }\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n // potential double-check in a slow-to-schedule thread....\n if (generatorRunning.get()) {\n view.listModel.addElement(val);\n }\n }\n });\n }\n }\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T23:02:17.183",
"Id": "72664",
"Score": "0",
"body": "As I understand, since my thread is not in EDT, I **should** use invokeLater for adding to the view: `view.listModel.addElement(val);` however I took it out and it runs fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T23:10:17.657",
"Id": "72665",
"Score": "0",
"body": "@drg ... yes, you should use invokeLater... I am just suggesting you check the atomic-boolean in that invokeLater thread as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:44:09.180",
"Id": "72748",
"Score": "0",
"body": "@rolfl-re: daemon threads. I believe the idea you are suggesting is that if my long running process (make it a daemon thread) is the only thing left and the program ends, it should discontinue the long thread?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T14:00:16.183",
"Id": "72750",
"Score": "1",
"body": "@drg exactly.... if it is not daemon, and, if your program does not somehow explicitly stop it, then your program will not exit.... (unless you do a *hard* exit like `System.exit(...)`... which is ugly)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T14:09:36.540",
"Id": "72752",
"Score": "0",
"body": "@rolfl-trying to see if I understand...would your (can't figure out how to get code in block) `if (!generatorRunning.compareAndSet(false, true)) {\n // already running....\n return false;\n}` be equivalent to:`if( generatorRunning.get())\n return;\n else\n generatorRunning.set(true);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T14:22:55.683",
"Id": "72753",
"Score": "0",
"body": "You say: \"you should check the generatorRunning.get() after the sleep, and before the set, rather than before the sleep. You have the risk here that you stop the generator, and then it still generates a value half a second later\". I see the point completely. But wouldn't you want (at least in this case) to check **before** as well-to stop it from going into sleep if not needed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:01:38.237",
"Id": "72779",
"Score": "1",
"body": "About the generatorRunning - yes, it is logically similar to your suggestion, except it is [atomic](http://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html) which makes it thread-safe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:03:36.607",
"Id": "72780",
"Score": "0",
"body": "About the *check after the sleep* - sleep, and the random get, are both cheap operations. What you want to avoid is the visual inconsistency if a user ***sees*** things change after pressing 'stop'. If you want to, you can check before the sleep as well, but the most critical thing is to check before updating the screen"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:07:42.753",
"Id": "42178",
"ParentId": "42089",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>AFAIK and according to <a href=\"https://en.wikipedia.org/wiki/Event_dispatching_thread\" rel=\"nofollow\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>all user interface components should be created and <strong>accessed</strong> only from the AWT event dispatch thread.</p>\n</blockquote>\n\n<p>including <code>view.list.getSelectedIndices()</code> in the <code>deleteElement()</code> method. The good news is that the <code>actionPerformed</code> event handler (which calls <code>deleteElement()</code>) is already runned by this thread so it's fine but you could get rid of the <code>EventQueue.invokeLater</code> and call <code>view.listModel.remove(index)</code> directly there.</p></li>\n<li><p>The index/indices manipulation is not so convenient in the <code>deleteElement()</code> method:</p>\n\n<pre><code>final int index = indices[indices.length - 1 - i];\n</code></pre>\n\n<p>It took a while to figure out what it is doing and this is needed becase removing an element from a list shifts the indexes of elements after the removed one so you have to remove them in reversed order.</p>\n\n<p>I'd simply reverse the array and use a foreach loop:</p>\n\n<pre><code>ArrayUtils.reverse(indices);\nfor (final int elementIndex: indices) {\n view.listModel.remove(elementIndex);\n}\n</code></pre>\n\n<p><code>ArrayUtils</code> is from <a href=\"https://commons.apache.org/lang/\" rel=\"nofollow\">Apache Commons Lang</a>. (It's <a href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/ArrayUtils.java?view=markup\" rel=\"nofollow\">open-source</a> so you can copy-paste that method to your code if you don't want to include a library only for one helper method.)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:15:44.683",
"Id": "72762",
"Score": "0",
"body": "@palacsint-Point 1: So the fact that actionPerformed is in EDT, then the code in that method that launches the thread, means the thread is in the EDT, thus requests for deleteElement(), etc are in EDT?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:45:10.690",
"Id": "72773",
"Score": "1",
"body": "@drg: Every method which is called by `actionPerformed` is in EDT. You can print the current thread name with `System.out.println(Thread.currentThread().getName())`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:57:19.700",
"Id": "72816",
"Score": "0",
"body": "@palacsint-You suggested `indices=view.list.getSelectedIndices()` in general would be issued inside `invokeLater()`, however, I'd have to declare an instance variable to do that(!). I couldn't declare a final local variable as it can't be assigned to, and I need `indices` after `invokeLater()` I guess I could move the code that requires `indices` inside the `invokeLater()`. Any ideas on the best way to go about that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:15:35.953",
"Id": "72818",
"Score": "1",
"body": "@drg: If I understand correctly I probably would use a `CopyOnWriteArrayList` field for that which is thread-safe."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T06:17:24.050",
"Id": "42267",
"ParentId": "42089",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42267",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:57:11.253",
"Id": "42089",
"Score": "4",
"Tags": [
"java",
"thread-safety",
"swing"
],
"Title": "Long Thread & EDT"
}
|
42089
|
<p>I have written a password checker using PHP, consisting of many <code>if else</code> statements. Is there any possible way to shorten this code?</p>
<pre><code>function passtest($pass) {
if (!empty($pass)) { //check if string is empty
if (ctype_alnum($pass)) { //check if string is alphanumeric
if (7 < strlen($pass)){ //check if string meets 8 or more characters
if (strcspn($pass, '0123456789') != strlen($pass)){ //check if string has numbers
if (strcspn($pass, 'abcdefghijklmnopqrstuvwxyz') != strlen($pass)) { //check if string has small letters
if (strcspn($pass, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') != strlen($pass)) { //check if string has capital letters
return "<br />Password passed";
}
else {
return "<br />No capital letter";
}
}
else {
return "<br />No small letter";
}
}
else {
return "<br />No number";
}
}
else {
return "<br />Password is short";
}
}
else {
return "<br />Password has special character";
}
}
else {
return "<br />Password field is empty";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T08:46:33.760",
"Id": "72460",
"Score": "1",
"body": "Related: [Verifying password strength using JavaScript](http://codereview.stackexchange.com/questions/40944/verifying-password-strength-using-javascript)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:52:27.927",
"Id": "72474",
"Score": "0",
"body": "As an aside, don't just do your password validation only on the server side. Having a client-side Javascript solution as well means your users will get faster feedback that their password is not allowed, improving their user experience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:26:37.043",
"Id": "72573",
"Score": "1",
"body": "Negate and un-nest. `if (empty($pass)) return 'empty'; if (ctype_alnum($pass)) return 'has special character';` etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:03:23.913",
"Id": "72650",
"Score": "0",
"body": "You're storing hashes of passwords, aren't you? Of course you are. In that case, why do you care whether they have special characters? What's the problem with them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:01:33.810",
"Id": "72999",
"Score": "0",
"body": "Relevant: http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html"
}
] |
[
{
"body": "<p><a href=\"http://css.dzone.com/articles/practical-php-refactoring-24\" rel=\"nofollow noreferrer\">Create clause guards</a>:</p>\n\n<pre><code>if (empty($pass)) {\n return \"<br />Password field is empty\";\n}\nif (!ctype_alnum($pass)) {\n return \"<br />Password has special character\";\n}\n</code></pre>\n\n<p>However, this all seems like a lot for an average user. If the user wants a weak password, let them have it. Just make sure you're doing all you can to protect them in your database.</p>\n\n<p>I read that somewhere, let me see if I can find the source. Oh, and why would you not let them have special characters in their password?</p>\n\n<p><a href=\"https://security.stackexchange.com/a/29865/38125\">Found something</a> sort of like what I was talking about</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:33:51.187",
"Id": "72433",
"Score": "0",
"body": "Nice link on password complexity. I personally take a test based approach to creating passwords - pick the password I want without even reading the complexity requirements and then change it to pass the unit tests. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:41:58.710",
"Id": "72437",
"Score": "0",
"body": "Haha after reading all the responses on security.se regarding passwords, I've got a unique passphrase (that's memorizable!!) for each website! I have yet to find a site which won't allow it. Except my bank. They don't allow passwords > 14 characters!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:11:40.170",
"Id": "72475",
"Score": "1",
"body": "\"Oh, and why would you not let them have special characters in their password?\" -- A pet peeve of mine. Not only does it mean I have to generate a less secure password, but it can be symptomatic of bad backend code (blocking special characters to prevent SQL injection, for example) which does not make me confident in the site's protection of my data."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:10:13.120",
"Id": "42096",
"ParentId": "42095",
"Score": "11"
}
},
{
"body": "<p>First thing first - if your else condition ends with a return, you don't need nest your if statements. Just reverse all of your test conditions and return if they are true. This also makes your code much more readable, because the condition you are returning is next to the test in your code, not the reciprocal of it's distance from the top of your nest:</p>\n\n<pre><code>function passtest($pass) {\n if (empty($pass)) \n {\n return \"<br />Password field is empty\";\n } \n if (!ctype_alnum($pass))\n {\n return \"<br />Password has special character\";\n } \n //etc... \n</code></pre>\n\n<p>The second thing that I'd mention is a usability issue (and a pet-peeve of a lot of validations I run across). If there is more than 1 thing that is being validated, and the user has to pass all of the checks, let them <em>know everything that was wrong</em> the first time. It's possible to have no capital, no number, and be too short -- don't make the user attempt a password 3 times to figure that out (and don't assume they'll read the instructions first).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T03:02:32.020",
"Id": "72440",
"Score": "1",
"body": "On your second point - one possible implementation is to append an error message to a string for everything that was wrong, and return that entire string at the end. Personally, I'd prefer flags for proper processing of error messages later, instead of directly returning text/markup to be displayed - separation of logic and presentation and all that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T03:13:24.553",
"Id": "72441",
"Score": "0",
"body": "For me, the implementation usually depends on how many conditions I'm checking. Agreed on the logic and presentation and all that - validations belong in the business logic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:15:16.790",
"Id": "42097",
"ParentId": "42095",
"Score": "12"
}
},
{
"body": "<p>I have an answer which also changes the logic of your code but I think there is a good reason why you should consider it:</p>\n\n<pre><code>function passtest($pass) {\n $errors = array();\n if (empty($pass)) $errors[] = 'Password field is empty';\n if (ctype_alnum($pass)) $errors[] = 'Password has special character';\n [...]\n\n return '<br />' . implode('<br>', $errors);\n}\n</code></pre>\n\n<p>Since it appears like this is somehow shown to the user I would notifyabout all the errors that happened in choosing the password, so that they can all be corrected in a single try.</p>\n\n<p>Another sidenote: Since your code reminds me of the time where I was just getting started and this seems to be at least somewhat related:\nDon't save passwords, save their hashes. And use a good hashing implementation. If you're using PHP >= 5.5, there is <a href=\"http://www.php.net/manual/en/function.password-hash.php\">a really easy way</a>.</p>\n\n<p>And thanks to \"Fge\", I can also give you <a href=\"https://github.com/ircmaxell/password_compat\">a slightly less easy way</a> for earlier PHP versions (>= 5.3.7).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T08:48:17.143",
"Id": "72461",
"Score": "0",
"body": "Was it the intention that you check for empty twice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:29:01.693",
"Id": "72469",
"Score": "0",
"body": "And for those not using PHP5.5+ there is https://github.com/ircmaxell/password_compat for backward compability :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:50:58.393",
"Id": "72496",
"Score": "2",
"body": "erm... `$errors.push('...')` <-- I take it you mean `$errors[] = '...';` and `$errors.join('<br>')` --> implode('<br>', $errors)`. If you're not using XHTML (and seeing as we're shifting towards HTML5, this is likely not to be the case), `<br>` will do fine. If you're posting on code-review, and your answer contains code, please ensure that the code you post isn't in need of additional reviewing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:42:36.713",
"Id": "72540",
"Score": "0",
"body": "@EliasVanOotegem Thank you, you're 100% right. I should have checked it before. Too much JS and self-confidence on my side..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-16T14:14:55.877",
"Id": "170608",
"Score": "0",
"body": "Shouldn't that be `if (!ctype_alnum($pass))`? And again, I question the necessity of that check at all. Any decent program should be able to deal with all of Unicode, especially since it's being hashed. (It *is* being hashed, isn't it?)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T03:38:12.970",
"Id": "42102",
"ParentId": "42095",
"Score": "20"
}
},
{
"body": "<p>Not only can this validation be made shorter, it can also be improved on...<br>\nHere's the list of remarks I have, I'll be elaborating on them as we go along:</p>\n\n<ol>\n<li>Don't restrict users from using passwords containing chars other than alphanumeric chars. You accept <code>f00barer</code>, but <em>not</em> <code>f00b@r!#</code>.</li>\n<li>In light of this, returning specific errors (such as an error message saying the password contains a special char), it won't take me long to work out what kinds of passwords users of your app may be using. I can then compile a more targeted list of possible passwords for a brute-force attack. Bottom line: your error messages are <em>too</em> specific, and your password rules are too strict. Combine the two and you end up with a possible security issue</li>\n<li>In a function, it's very easy (and it often improves readability) to chance <code>if (true) {/*do stuff*/} else { return $stuff; }</code> to <code>if (false) { return $stuff;} /*do stuff*/</code>. this essentially gets rid of all of those pesky <code>else</code>'s</li>\n<li>Though you have to be careful not to overdo it, <em>all but one</em> of your if's can be replaced with a single <code>preg_match</code> call</li>\n</ol>\n\n<p>I'll address the first and last issue in one go. I will admit, the regex isn't that simple, but here goes:</p>\n\n<pre><code>$pattern = '/(?<=\\d).*((?<=[a-z]).*[A-Z]|(?<=[A-Z]).*[a-z])|(?<=[a-z]).*((?<=[A-Z]).*\\d|(?<=\\d).*[A-Z])|(?<=[A-Z]).*((?<=[a-z]).*\\d|(?<=\\d).*[a-z])/';\n$pass = trim($pass);\nif (!empty($pass) && strlen($pass) > 7 && preg_match($pattern, $pass))\n{//not empty, match ANY character after trimming the string 8 or more times\n return 'Pass approved';\n}\nreturn 'Pass not approved';\n</code></pre>\n\n<p>I'm accepting alphanumeric chars, aswel as special chars for people to use in their password.<Br>\nThe pattern basically repeats the same principle three times, this is the basic idea:</p>\n\n<pre><code>(?<=\\d).*((?<=[a-z]).*[A-Z]|(?<=[A-Z]).*[a-z])\n</code></pre>\n\n<ul>\n<li><code>(?<=\\d)</code> If the previous char was a digit</li>\n<li><code>.*</code> match <em>any</em> char zero or more times</li>\n<li><code>(?<=[a-z]).*[A-Z]</code>: find a lower-case char, followed by zero or more chars, and an upper-case letter</li>\n<li><code>|</code>: <em>OR</em>\n-<code>(?<=[A-Z]).*[a-z]</code>: After the initial digit, if the lower-case followed by an upper case wasn't found: find an upper-case char that is followed by zero or more chars of any type <em>and</em> a lower-case letter.</li>\n</ul>\n\n<p>Now this matches things like <em>\"foO()!naR\"</em>. After the digit, there are still upper and lower-case letters. However, the digit <em>may</em> be at the end of the string, or either the upper or lower-case character(s) might precede the digit. That's why I've repeated the same pattern three times, only changing the order in which we search:</p>\n\n<pre><code>(?<=\\d).*((?<=[a-z]).*[A-Z]|(?<=[A-Z]).*[a-z]) | //digit followed by upper and lower OR\n(?<=[a-z]).*((?<=[A-Z]).*\\d|(?<=\\d).*[A-Z])| //lower followed by digit and upper OR\n(?<=[A-Z]).*((?<=[a-z]).*\\d|(?<=\\d).*[a-z]) //upper followed by lower and digit\n</code></pre>\n\n<p>Either way, we'll find the sucker. To ensure a length of 8 or more chars, all you do is call <code>strlen</code>. Make sure the <code>preg_match</code> is the last condition you check: PHP short-circuits evaluations. if the string isn't long enough, <code>preg_match</code> won't be called. given that <code>preg_match</code> can be slow, we don't want to call it unless we really need it.</p>\n\n<p>I'm returning a generic error message here, because the pass is not accepted. That's all the user really needs to know. Have some div on your page say that a pass can contain any char, must contain upper, lower and digit characters and has to be <em>at least</em> 8 chars long, in case of <em>any</em> password rejection. If the user can type, he can read, and should be able to work out why the pass was rejected.</p>\n\n<p>Now, all these if's and elses are gone, but still: if you find yourself nesting <code>if-else</code> blocks, consider re-writing that code to:</p>\n\n<pre><code>if (strlen($string) < 8)\n{\n return 'string is too short';\n}\n//no else, string is long enough\nif (in_array($string, $forbiddenWords))\n{\n return 'illegal word';\n}\n//string is long enough, not forbidden word...\n</code></pre>\n\n<p>Also consider using a <code>switch-case</code>. It's easier to read, and you can exploit the fall-through <em>\"bug\"</em>. (some call it a bug, I call it a feature):</p>\n\n<pre><code>switch(true)\n{//true!\n case empty($string): return 'no string';\n case strlen($string) < 8: return 'too short';\n case false: return 'Impossible';\n case true:\n $var = 'passed all checks, only then this case will be true';\n //no break\n default: return $var;//returns ^^\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:58:29.567",
"Id": "42144",
"ParentId": "42095",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:02:50.443",
"Id": "42095",
"Score": "9",
"Tags": [
"php",
"validation"
],
"Title": "Password checker in PHP"
}
|
42095
|
<p>I have the following code:</p>
<pre><code>public EmployeeProcessOutput RetrieveEmployee(EmployeeProcessInput input)
{
var employee = input.Employee;
if (input.EmployeeId == null)
employee= CreateEmployee(employee);
return new EmployeeProcessOutput
{
Employee = employee,
State = "Stored"
};
}
private Employee CreateEmployee(employee)
{
//Call a service to create an employee in the system using the employee info
//such as name, address etc and will generate an id and other employee info.
var output = Service(employee)
var employee = output.Employee;
return employee;
}
</code></pre>
<p>Is there a clean way and of passing the <code>employee</code> parameter to the <code>CreateEmployee</code> method? I feel that this line could be cleaner: </p>
<pre><code>employee = CreateEmployee(employee);
</code></pre>
<p>Any thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:15:56.140",
"Id": "72449",
"Score": "0",
"body": "What don't you like about it wizkid?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:31:45.623",
"Id": "72489",
"Score": "1",
"body": "Next time, could you please make sure to include code that actually compiles?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:16:17.913",
"Id": "72501",
"Score": "0",
"body": "Small note, possible failure point, you are checking if input.Employee == null but if input is null your app will crash, i'd suggest performing a if(input == null) throw new NullArgumentException(\"input\") to assist in debugging later."
}
] |
[
{
"body": "<p>Have a look at <a href=\"http://msdn.microsoft.com/en-us/library/0f66670z.aspx\" rel=\"nofollow noreferrer\">this</a>. I think the real question is pass by value vs pass by reference. </p>\n\n<p>More info <a href=\"https://stackoverflow.com/questions/8708632/passing-objects-by-reference-or-value-in-c-sharp\">here</a>.</p>\n\n<p><strong>Edit:</strong>\nThe line could be modified to following:</p>\n\n<pre><code>CreateEmployee(ref employee);\n</code></pre>\n\n<p>and the method name would be: </p>\n\n<pre><code>private void CreateEmployee(ref employee)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:27:10.993",
"Id": "72447",
"Score": "3",
"body": "Could you add anything from these links? Link-only answers are discouraged here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:38:08.593",
"Id": "72448",
"Score": "0",
"body": "I'm not familiar with c#. But taking that its a OOP originated from c, I had given the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:42:31.693",
"Id": "72450",
"Score": "0",
"body": "objects are always passed by reference. \"ref\" is redundant here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:58:28.103",
"Id": "72453",
"Score": "0",
"body": "@wizzardz I'm not familiar with c#, I thought `ref` may pass the parameter by reference. Thankx for a valuable comment :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:49:05.767",
"Id": "72495",
"Score": "2",
"body": "@wizzards No, it's not redundant. For reference types, the reference is passed by value, unless you use ref. And since the reference changes here, that ref is necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:57:59.137",
"Id": "72610",
"Score": "1",
"body": "@wizzardz: You are suffering from a common misconception which even some prominent Microsoft developers (those who participated in *Framework Design Guidelines*) suffer from. Svick is totally correct in pointing this out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:44:06.203",
"Id": "72696",
"Score": "0",
"body": "@svick: Thanks a lot for correcting myself, mate. That was a major misconception from my side"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T06:05:54.287",
"Id": "72703",
"Score": "0",
"body": "@svick, but it is redundant here. The new reference is returned by `CreateEmployee` method. I see absoultely no reason to pass parameter by `ref`, unless you are willing to add a quite confusing side effect to this method or make the method `void`. Not to mention, that since original code contains multiple compilation errors it is really hard to tell if the reference changes at all :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:48:42.750",
"Id": "73138",
"Score": "0",
"body": "@NikitaBrizhak You're right about that. I was assuming `CreateEmployee` would be changed to use `ref`, but also return `void`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T06:19:02.767",
"Id": "73177",
"Score": "0",
"body": "@NikitaBrizhak Thankx for pointing that out. I almost forgot that."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:21:23.927",
"Id": "42106",
"ParentId": "42105",
"Score": "3"
}
},
{
"body": "<p>Well, your code is really confusing. Here is what i think what your signatures should look like:</p>\n\n<pre><code>public bool StoreEmployee(Employee employee)\n{\n //here you set ID, etc. and store eployee into your system\n //the return value indicates whether operaration succeeded\n //alternatively you can return void and throw an exception in case of error\n}\n\npublic Employee GetEmployee(string id)\n{\n //here you fetch employee by id from your system\n //returns null or throws an exception if employee was not found\n}\n\n\npublic Employee GetEmployee(EmployeeName name)\n{\n //here you fetch employee by name from your system\n //where EmployeeName contains required info (first and last names?)\n //returns null or throws an exception if employee was not found\n}\n</code></pre>\n\n<p>I am not sure where your input/output classes are coming from, but they feel really outdated. This is definetely NOT how you want to design a C# application. If you absolutely must return a state of operation - use method return value for that. And use <code>bool</code> or enums for that, not strings. But it is not something to build your application around when you are using an OOP language.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:50:17.153",
"Id": "42109",
"ParentId": "42105",
"Score": "1"
}
},
{
"body": "<p>Rather than finding a better way for calling method you need to re-factor your code. Depending on the situation you may create a new class which will provide you a fresh employee. But if this is a single task and need only once extract method can be a good solution. I've just extracted some code from your <code>RetriveEmployee</code> method into two methods.</p>\n\n<pre><code>public EmployeeProcessOutput RetrieveEmployee(EmployeeProcessInput input)\n{\n return new EmployeeProcessOutput\n {\n Employee = GetFreshEmployee(input),\n State = \"Stored\" \n };\n}\n\nprivate Employee GetFreshEmployee(EmployeeProcessInput imput)\n{\n if (HasValidEmployee(input))\n {\n return input.Employee\n }\n else\n {\n return CreateEmployee(input.Employee)\n }\n}\n\nprivate bool HasValidEmployee(EmployeeProcessInput input)\n{\n return input.EmployeeId != null;\n}\n</code></pre>\n\n<p>Hopefully it is easier to understand then the original implementation. If you prefer ternary for single line conditional branching use it in <code>GetFreshEmployee</code> which will concise your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:55:21.627",
"Id": "42110",
"ParentId": "42105",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:11:32.953",
"Id": "42105",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Clean way of passing parameters"
}
|
42105
|
<p>My goal was to get my hands dirty in OOP by designing and using classes and getting started with inheritance and other OOP concepts. </p>
<p>I have written a very small code to play a card Game called "War". The rules are simple. Each person playing the game is given 1 card. The person with the highest card wins. I am not worrying too much about Ties right now. My code <em>does</em> work but I wanted feedback on my OOP usage.</p>
<hr>
<pre><code>import itertools
import random
class Cards:
def __init__(self):
self.suits = ['Spades','Hearts','Diamonds','Clubs']
self.values = range(1,14)
self.ActualCards = [] #Empty List to Append
for Card in itertools.product(self.suits,self.values):
self.ActualCards.append(Card) #Cartesian Product to Create Deck
def GetRandomCard(self):
RandomNumber = random.randint(0,51)
CardToBeReturned = self.ActualCards[RandomNumber] #Generates Random Card
return(CardToBeReturned)
class Player:
def __init__(self,ID,Card):
self.PlayerID = ID
self.CardForPlayer = Card
class Game:
def __init__(self,NameOfGame):
self.name = NameOfGame
class SimpleWar(Game):
def __init__(self,NumberOfPlayers):
self.NumberOfPlayers = NumberOfPlayers
self.PlayerList = []
def StartGame(self):
DeckOfCards = Cards()
for playerID in range(0,self.NumberOfPlayers):
CardForPlayer = DeckOfCards.GetRandomCard() #Deal Card to Player
NewPlayer = Player(playerID,CardForPlayer) #Save Player ID and Card
self.PlayerList.append(NewPlayer)
self.DecideWinner()
def DecideWinner(self):
WinningID = self.PlayerList[0] #Choose Player 0 as Potential Winner
for playerID in self.PlayerList:
if(playerID.CardForPlayer[1]>WinningID.CardForPlayer[1]):
WinningID = playerID #Find the Player with Highest Card
print "Winner is Player "+str(WinningID.PlayerID)
print "Her Card was "+ str(WinningID.CardForPlayer[1]) + " of " + str(WinningID.CardForPlayer[0])
if __name__=="__main__":
NewGame = SimpleWar(2)
NewGame.StartGame()
</code></pre>
|
[] |
[
{
"body": "<p>Cool app. My comments aren't intended to be critical or haughty, just me thinking out loud.</p>\n\n<ul>\n<li><p>Python 3? If not, make sure your classes extend <code>object</code>.</p></li>\n<li><p>I probably wouldn't define and extend <code>Game</code>. It doesn't add anything. You don't need to generalize or abstract the idea of a <code>Game</code>, especially in this context.</p></li>\n<li><p>More broadly, it's a good practice to avoid inheritance. Do a search on \"favor composition over inheritance\" for more on that.</p></li>\n<li><p>The state of <code>Cards</code> doesn't change... the point of having a class is managing state. So I'd have something like <code>pick_card</code> that actually removes the selected card from the deck. Otherwise you'd probably be better off just using a function—at least in Python. Classes are all about bundling data and functions so you can manage state safely. Absent that, they kind of lose their luster (unless you're writing Java ;) ).</p></li>\n<li><p>This is just me, but I wouldn't have <code>StartGame</code> run the loop or decide the winner. Again, I'd have <code>__init__</code> start the game, and then have something like <code>run_game</code>. Again, rely on the class to manage the state. Each method is supposed to move it farther along.</p></li>\n<li><p>Knowing me, I'd break out <code>__init__</code>, <code>play_a_turn</code>, <code>decide_game</code>, and <code>show_game</code> as methods and loop <em>outside</em> the class to keep the calling structure flat.</p></li>\n<li><p>IMHO your logic for deciding the winner, and the logic for <em>displaying</em> the winner could go in separate methods. I like keeping methods small, light, and targeted.</p></li>\n<li><p>Again, I'd make <code>SimpleWar.__init__</code> do more, and <code>StartGame</code> do less. If I had a <code>StartGame</code> at all.</p></li>\n</ul>\n\n<p><strong>EDIT:</strong> I like to define my classes closely to the things they model. So instead of <code>Cards</code>, I'd probably have Deck, with methods shuffle and pick. I also like the comment above about spinning off a separate method to compare cards—I'd definitely do that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:43:17.050",
"Id": "72561",
"Score": "0",
"body": "It's not Python 3, because it uses Python 2's `print` syntax."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:00:25.510",
"Id": "72583",
"Score": "0",
"body": "ah, good call. I'm still self-conscious about not having migrated. In that case, make sure that your __init__ methods invoke the base class's __init__, either directly or with super()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:36:32.193",
"Id": "72809",
"Score": "0",
"body": "For future reference, use \\`\\_\\_init\\_\\_\\` to make it display properly. Or if you want to bold it, `**\\_\\_init\\_\\_**`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T07:14:43.077",
"Id": "42112",
"ParentId": "42107",
"Score": "11"
}
},
{
"body": "<p>At a glance, I would recommend putting a <code>CompareTo(OtherCard)</code> function in the <code>Card</code> class, and using that for <code>DecideWinner</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:05:42.970",
"Id": "72568",
"Score": "1",
"body": "The value of a card is game dependent. In a world, where those cards could be used for many different games, the cards wouldn't know their own values. So, I think, the `WarGame` object is a good place, to put this decision in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:50:36.153",
"Id": "72623",
"Score": "0",
"body": "@stofl The only thing that would change for numerical comparison is whether aces are high or low, and it actually doesn't matter at all unless aces could be either within the same game, or if cards are passed between games for some reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:05:56.990",
"Id": "72627",
"Score": "1",
"body": "If the value of a card is an attribute of the card, then a compare method makes sense in the card class. If the value of a card is defined in the game rules, then the card class would be not the right place for a compare method. In the concrete code, we have the value in the cards - in real world we most often don't: Cards have many different values in different games."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:30:42.913",
"Id": "72637",
"Score": "0",
"body": "@stofl I think that what's in the code is more relevant than what's in real life; and in the code, there is only one game, and only one definition of card comparison."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T07:30:22.123",
"Id": "42113",
"ParentId": "42107",
"Score": "5"
}
},
{
"body": "<h3>Syntax Error</h3>\n\n<p>In <code>Cards.GetRandomCard()</code>, the <code>return</code> statement is incorrectly indented. (Also, I would recommend writing the <code>return</code> without parentheses.)</p>\n\n<h3>Style Conventions</h3>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\">Use <code>lower_case_names</code> for variables and methods.</a></p>\n\n<p>For readability, please add one <kbd>space</kbd> after each comma, and one <kbd>newline</kbd> between functions definitions.</p>\n\n<h3>Modeling</h3>\n\n<p>Your <code>Game</code> class isn't useful. You never set or use <code>NameOfGame</code>. I recommend getting rid of the <code>Game</code> class altogether.</p>\n\n<p>In a real-life card game, you would deal a card from the deck to each player, without replacement. In your code, you deal with replacement (i.e., <strong>there is a chance of dealing the same card to both players</strong>). A more realistic simulation would do a <code>random.shuffle()</code> on the array. When dealing, you would <code>pop()</code> a card from the list to remove it from the deck. 51 is a \"magic\" number; you should use <code>len(self.ActualCards) - 1</code>.</p>\n\n<p><code>Cards</code> is really a <code>Deck</code>. Rather than just a tuple of strings, you should have a <code>Card</code> class representing a single card. The <code>Card</code> class should have a <code>__str__()</code> method that returns a string such as <code>\"Ace of diamonds\"</code>. If you also define <a href=\"http://docs.python.org/2/library/operator.html\">comparison operators</a>, then you can determine the winner using <code>max(self.PlayerList, key=lambda player: player.CardForPlayer)</code>.</p>\n\n<h3>Expressiveness</h3>\n\n<p>In Python, you can usually avoid creating an empty list and appending to it:</p>\n\n<pre><code>self.ActualCards = [] #Empty List to Append\nfor Card in itertools.product(self.suits,self.values):\n self.ActualCards.append(Card) #Cartesian Product to Create Deck\n</code></pre>\n\n<p>Instead, you should be able to build it all at once:</p>\n\n<pre><code>self.actual_cards = list(itertools.product(self.suits, self.values))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:44:00.977",
"Id": "72562",
"Score": "0",
"body": "[PEP 8](http://www.python.org/dev/peps/pep-0008/) suggests *two* newlines between function and class definitions. However, one is better than nothing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:12:07.107",
"Id": "72606",
"Score": "1",
"body": "@nyuszika7h PEP 8 only calls for one blank line between method definitions within a class, which is what matters here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:02:08.563",
"Id": "72611",
"Score": "1",
"body": "@200_success: It would be hard to define a comparison for the `Card`s, as the order only has meaning in the context of a particular game. So it's a `Game` responsibility (War, Solitaire, etc) to compare two cards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:30:17.070",
"Id": "72805",
"Score": "0",
"body": "@200_success You're right, I didn't bother to check if it's within a class."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T07:34:46.410",
"Id": "42114",
"ParentId": "42107",
"Score": "18"
}
},
{
"body": "<p>From a testing perspective, it would be good, to inject the deck (<code>Cards</code>) and the players into the game. Also printing the results in the game object is not a very good idea, I think. Maybe it would be better, to return the round, that contains the winner. This could then also be used for logging or a mastership :)</p>\n\n<pre><code>Deck = Deck()\nGame = SimpleWar(Deck)\nGame.addPlayer(Player('Andrea'))\nGame.addPlayer(Player('Bert'))\nRound = Game.play()\nWinner = Round.get_winner()\nprint('The winner is: ' + str(Winner))\nprint('The winning card is: ' + str(Winner.get_last_card()))\n\nDeck.shuffle()\nRound = Game.play()\n</code></pre>\n\n<p>As said before, the deck should contain card objects (or an array and build the card objects, when requested, if those card objects would be expensive) and the cards should have to be put back into the deck after each game round (or a <code>reset()</code> method of the deck could be called by the game). The question then would be, who remembers the winning card, after all cards have been returned into the deck. In the example above, this is the player (<code>get_last_card()</code>), but it could be stored in the <code>Round</code>, too.</p>\n\n<p>This way you don't have any object instantiation in your classes, except for the deck, that builds card objects. This would be very good testable. For example, you can pass a deck mock into the game and define, which cards it should return in the single requests to test the detection of the winner.</p>\n\n<p>Search the web for \"dependency injection\" for more information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:11:32.880",
"Id": "72630",
"Score": "1",
"body": "what I like about your design is that you've thought through the interactions between objects, and that defines their methods. Also big plus for dependency injection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:40:41.583",
"Id": "42134",
"ParentId": "42107",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "42114",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:43:45.353",
"Id": "42107",
"Score": "26",
"Tags": [
"python",
"object-oriented",
"game",
"playing-cards"
],
"Title": "Simple card game to learn OOP"
}
|
42107
|
<p>I have written an HTTP client wrapped the libcurl. It should be able to do HTTP get/post with string/map param, with cookies and proxy.</p>
<p>Can somebody review the code? B.T.W., I'm not sure the way pass a map into HTTP header is correct, maybe I should remove these two interface</p>
<p><code>CURLcode do_http_post(std::string post_url, std::map<std::string, std::string> map_param, void* user_data);</code> </p>
<p>and </p>
<p><code>void set_http_header(std::map<std::string, std::string> map_param);</code>.</p>
<p>curl_wrapper.h</p>
<pre><code>#ifndef CURL_WRAPPER
#define CURL_WRAPPER
#include <string>
#include <exception>
#include "curl.h"
#include <map>
#define DATA_MAX_LEN CURL_MAX_WRITE_SIZE*30
struct client_data;
class curl_client{
public:
curl_client();
~curl_client();
CURLcode do_http_get(std::string get_url, void* user_data);
CURLcode do_http_post(std::string post_url, std::map<std::string, std::string> map_param, void* user_data);
CURLcode do_http_post(std::string post_url, std::string post_fields, void* user_data);
void set_http_header(std::string header_param);
void set_http_header(std::map<std::string, std::string> map_param);
void set_http_cookie(std::string cookie_file);
void set_http_proxy(std::string proxy_url);
private:
static size_t write_data( char *ptr, size_t size, size_t nmemb, void *user_data);
void set_common_opt(std::string url, void* user_data);
void set_post_fields(std::string post_fields);
void set_post_fields(std::map<std::string, std::string> map_param);
CURLcode perform();
private:
CURL* curl_;
CURLcode res_;
curl_slist* p_header_list_;
};
struct client_data {
client_data() {
size = DATA_MAX_LEN;
used = 0;
buf = new char[DATA_MAX_LEN];
}
~client_data(){
if (buf!=nullptr){
delete[] buf;
}
}
char *buf;
int size;
int used;
};
#endif
</code></pre>
<p>curl_wrapper.cpp</p>
<pre><code>#include "curl_wrapper.h"
curl_client::curl_client(){
curl_ = curl_easy_init();
p_header_list_ = nullptr;
}
curl_client::~curl_client(){
curl_easy_cleanup(curl_);
curl_slist_free_all(p_header_list_);
}
CURLcode curl_client::do_http_get(std::string get_url, void* user_data){
set_common_opt(get_url, user_data);
return perform();
}
CURLcode curl_client::do_http_post(std::string post_url, std::map<std::string, std::string> map_param, void* user_data){
set_common_opt(post_url, user_data);
set_post_fields(map_param);
return perform();
}
CURLcode curl_client::do_http_post(std::string post_url, std::string post_fields, void* user_data){
set_common_opt(post_url, user_data);
set_post_fields(post_fields);
return perform();
}
void curl_client::set_common_opt(std::string url, void* user_data){
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_client::write_data);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, user_data);
curl_easy_setopt(curl_, CURLOPT_HEADER, 1);
curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1);
// not verify host and ca for https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0);
#ifdef DEBUG
curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1);
#endif
}
void curl_client::set_post_fields(std::map<std::string, std::string> map_param){
std::string post_fields;
std::map<std::string, std::string>::iterator it;
for (it = map_param.begin(); it!=map_param.end(); ++it){
if (it!=map_param.begin()){
post_fields += "&";
}
post_fields += it->first + "=" + it->second;
}
set_post_fields(post_fields);
}
void curl_client::set_post_fields(std::string post_fields){
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, post_fields.c_str());
curl_easy_setopt(curl_, CURLOPT_POST, 1);
}
void curl_client::set_http_header(std::string header_param){
if (p_header_list_){
curl_slist_free_all(p_header_list_);
p_header_list_ = nullptr;
}
p_header_list_ = curl_slist_append(p_header_list_, header_param.c_str());
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, p_header_list_);
}
void curl_client::set_http_header(std::map<std::string, std::string> map_param){
std::string header_param;
std::map<std::string, std::string>::iterator it;
for (it = map_param.begin(); it!=map_param.end(); ++it){
if (it!=map_param.begin()){
header_param += "&";
}
header_param += it->first + "=" + it->second;
}
set_http_header(header_param);
}
void curl_client::set_http_cookie(std::string cookie_file) {
curl_easy_setopt(curl_, CURLOPT_COOKIEJAR, cookie_file.c_str());//save to
curl_easy_setopt(curl_, CURLOPT_COOKIEFILE, cookie_file.c_str());//read from
}
void curl_client::set_http_proxy(std::string proxy_url){
curl_easy_setopt(curl_, CURLOPT_PROXY, proxy_url.c_str());
}
size_t curl_client::write_data( char *ptr, size_t size, size_t nmemb, void *user_data){
client_data *the_buf = (client_data *)user_data;
int bytes_passed_in = size * nmemb;
int bytes_written = 0;
if (the_buf->used + bytes_passed_in < DATA_MAX_LEN){
memcpy(the_buf->buf + the_buf->used, ptr, bytes_passed_in);
the_buf->used += bytes_passed_in;
*(the_buf->buf + the_buf->used) = 0;
bytes_written = bytes_passed_in;
}else {
memcpy(the_buf->buf + the_buf->used, ptr, DATA_MAX_LEN - the_buf->used - 1);
bytes_written = DATA_MAX_LEN - the_buf->used - 1;
the_buf->used = DATA_MAX_LEN;
*(the_buf->buf + DATA_MAX_LEN - 1) = 0;
// here libcurl will signal an error for intact data written.
}
return bytes_written;
}
CURLcode curl_client::perform(){
if (curl_) {
res_ = CURL_LAST;
try {
res_ = curl_easy_perform(curl_);
} catch (std::exception e){
}
return res_;
}
}
</code></pre>
<p>An HTTP get test case:</p>
<pre><code> void curl_get_googleplay(){
curl_client curl;
client_data user_data;
CURLcode res = curl.do_http_get(std::string("play.google.com/store/apps/details?id=com.teamviewer.teamviewer.market.mobile"), &user_data);
}
</code></pre>
|
[] |
[
{
"body": "<p>Looking at your header file:</p>\n\n<ul>\n<li><p>Replace the <code>#define DATA_MAX_LEN</code> with a <code>static const</code> variable; Do the same with any other constant that is <code>#define</code>-d.</p></li>\n<li><p>Pass more complex parameters by const reference, to avoid making a copy (urls, parameters maps, etc).</p></li>\n<li><p>You define client_data structure for (I assume) receiving the results; If it is strongly typed, why do you pass it in by void*? This just allows client code to call your API in a way that will corrupt your code (e.g. a client might decide to pass there a pointer to a <code>std::vector<uint8_t></code> instead).</p></li>\n<li><p>You do not use RAII and smart pointers (you probably should)</p></li>\n<li><p>After looking at your code, it is still unclear to me, if I would be able to use it to read the HTTP response headers (e.g. \"I want to know if the response came with the \"Cache-Control\" header specified, and what was it's value\").</p></li>\n<li><p>Consider returning the result data as a return value (instead as an output parameter) and raising an exception in case you get a HTTP error. This would allow you to specify other error conditions as well.</p></li>\n<li><p>Just looking at the interface (not the implementation) I have no idea how your class will behave if I call with invalid parameters.</p></li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>curl_client curl;\nclient_data user_data;\ncurl.set_http_cookie(\"\\\\\"); // does this throw? What does it throw?\n</code></pre>\n\n<p>Looking at your implementation file:</p>\n\n<ul>\n<li><p>Your perform function calls curl_easy_perform (a <strong>C</strong> function) inside a try/catch block for std::exception. Exceptions are a C++ <em>thing</em> (i.e. <code>curl_easy_perform</code> will <em>never</em> throw an exception -- that's why it's using return codes to signal errors).</p></li>\n<li><p>You are using C-style casts; Don't! (see my point above about removing the void* code).</p></li>\n<li><p>There is no reason at all to use raw pointer and memcpy. Consider using std::vector instead (it will be safer, more efficient, exception-safe and already tested).</p></li>\n<li><p><code>set_post_fields</code> concatenates strings into a different string, in a loop. Consider using a <code>std::ostringstream</code> instead.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:01:15.420",
"Id": "42150",
"ParentId": "42121",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42150",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T08:59:38.013",
"Id": "42121",
"Score": "4",
"Tags": [
"c++",
"http",
"curl"
],
"Title": "Wrapping Curl, an HTTP client"
}
|
42121
|
<p>I'm creating a class-based signal generator that, given a buy threshold, sell threshold and a list of list of indicators, creates a 'buy' of 'sell' signal on a given day if the indicator from that day is greater than the sell threshold.</p>
<p>But the day before it wasn't greater, so basically when the indicator crosses over the buy threshold, it gives a sell signal and a buy signal when the indicator crosses under the buy threshold (it's lower than the threshold on a day, but the day before it wasn't).</p>
<p>I am wondering if this working code could be cleaned up using zip.</p>
<pre><code>class Directionalindicator_signals():
def __init__(self, buy_threshold, sell_threshold, list_of_indicators):
self.buy_threshold = buy_threshold
self.sell_threshold = sell_threshold
self.list_of_indicators = list_of_indicators
def calculate(self):
signals = ['']
for i in range(1, len(self.list_of_indicators)):
if self.list_of_indicators[i] > self.buy_threshold and self.list_of_indicators[i-1] <= self.buy_threshold:
signals.append('Sell')
elif self.list_of_indicators[i] < self.buy_threshold and self.list_of_indicators[i-1] >= self.buy_threshold:
signals.append('Buy')
else:
signals.append('')
return signals
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:26:47.297",
"Id": "72468",
"Score": "0",
"body": "Yes, it can, and I've shown you almost exactly how to do so on SO: http://stackoverflow.com/a/21851228/3001761"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:31:26.400",
"Id": "72470",
"Score": "5",
"body": "This question appears to be off-topic because it is primarily asking for code to be written (after a very similar question was [already answered](http://stackoverflow.com/a/21851228/3001761) on Stack Overflow), rather than seeking a code review."
}
] |
[
{
"body": "<p>My first advice is <a href=\"http://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow\">stop writing classes</a> if you don't need to : your class has only two methods an <code>init</code> and a proper method. This could probably be written as a simple function :</p>\n\n<pre><code>def calculate_directions(buy_threshold, sell_threshold, list_of_indicators):\n signals = ['']\n for i in range(1, len(list_of_indicators)):\n if list_of_indicators[i] > buy_threshold and list_of_indicators[i-1] <= buy_threshold:\n signals.append('Sell')\n elif list_of_indicators[i] < buy_threshold and list_of_indicators[i-1] >= buy_threshold:\n signals.append('Buy')\n else:\n signals.append('')\n return signals\n</code></pre>\n\n<p>Then it seems a bit more obvious than sell_threshold is not useful.</p>\n\n<p>Also, as suggested by jonrsharpe's comment, you can use <code>zip</code> :</p>\n\n<pre><code>def calculate_directions(buy_threshold, list_of_indicators):\n signals = ['']\n for prev, curr in zip(list_of_indicators, list_of_indicators[1:]):\n if curr > buy_threshold and prev <= buy_threshold:\n signals.append('Sell')\n elif curr < buy_threshold and prev >= buy_threshold:\n signals.append('Buy')\n else:\n signals.append('')\n return signals\n</code></pre>\n\n<p>and this can be written using list comprehension :</p>\n\n<pre><code>def calculate_directions(buy_threshold, list_of_indicators):\n return ['']+[('Sell' if (curr > buy_threshold and prev <= buy_threshold) else ('Buy' if (curr < buy_threshold and prev >= buy_threshold) else '')) for prev, curr in zip(list_of_indicators, list_of_indicators[1:])]\n</code></pre>\n\n<p>In a real life situation, I'd recommend exctracting the logic in the list comprehension into a function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:42:59.317",
"Id": "42124",
"ParentId": "42122",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:15:37.867",
"Id": "42122",
"Score": "-1",
"Tags": [
"python",
"classes"
],
"Title": "Class-based signal generator"
}
|
42122
|
<p>script.py:</p>
<pre><code>#!/usr/bin/python
import os
srcDir = os.getcwd()
dirName = 'target_directory'
dstDir = os.path.abspath(dirName)
def ignore_list(path, files):
filesToIgnore = []
for fileName in files:
fullFileName = os.path.join(os.path.normpath(path), fileName)
if (not os.path.isdir(fullFileName)
and not fileName.endswith('pyc')
and not fileName.endswith('ui')
and not fileName.endswith('txt')
and not fileName == '__main__.py'
and not fileName == 'dcpp.bat'):
filesToIgnore.append(fileName)
return filesToIgnore
# start of script
shutil.copytree(srcDir, dstDir, ignore=ignore_list)
</code></pre>
<p>As <code>shutil.copytree()</code> has no option where I can give names for required files to copy like "ignore," I have modified the argument of ignore to give "required files to copy."</p>
<p>Review my code.</p>
|
[] |
[
{
"body": "<p>Looks ok for a specific task, but the code is not reusable at all. It would be more useful to create a function <code>ignore_except</code> that could be used like this to perform the same task:</p>\n\n<pre><code>shutil.copytree(srcDir, dstDir, \n ignore=ignore_except('*.pyc', '*.ui', '*.txt', '__main__.py', 'dcpp.bat'))\n</code></pre>\n\n<p>The <a href=\"https://hg.python.org/cpython/file/default/Lib/shutil.py#l261\" rel=\"nofollow noreferrer\">source code</a> of <code>shutil.ignore_patterns</code> would be a good starting point for such function. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T13:19:59.753",
"Id": "74566",
"Score": "0",
"body": "pls paste here code of ignore_except()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:11:26.903",
"Id": "404535",
"Score": "0",
"body": "@Patrick: See the `include_patterns()` function in [my answer](https://stackoverflow.com/a/35161407/355230) to a related Python question on [stackoverflow](https://stackoverflow.com/questions/tagged/python) titled [Copying specific files to a new folder, while maintaining the original subdirectory tree](https://stackoverflow.com/questions/35155382/copying-specific-files-to-a-new-folder-while-maintaining-the-original-subdirect)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-27T19:22:13.613",
"Id": "42974",
"ParentId": "42123",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-19T09:27:50.830",
"Id": "42123",
"Score": "4",
"Tags": [
"python",
"file-system",
"python-2.x"
],
"Title": "Copy a directory structure to another, but only copying specific files"
}
|
42123
|
<p>Lately I have been trying to <a href="https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop">extract till I drop</a>. Well not necessarily till I drop, but I've been trying to be more strict and look at some metrics of my code.</p>
<p>I have now come along an old class of mine which has a rather large switch case. Metrics say the method lines of code are beyond evil. It goes something like this:</p>
<pre><code>private void startProcessing(Map<MyKeyEnum, String> map) {
Processor myProcessor = new Processor();
for (Entry entry : map.entrySet()) {
switch(entry.getKey()) {
case KEY1:
myProcessor.processStuffAboutKey1(entry.getValue());
break;
case KEY2:
myProcessor.processStuffAboutKey2(entry.getValue());
break;
case KEY3:
myProcessor.processStuffAboutKey3(entry.getValue());
break;
case KEY4:
myProcessor.processStuffAboutKey4(entry.getValue());
break;
...
...
}
}
}
</code></pre>
<p>So basically you can gather that it is necessary for me to invoke very different things for each key <strong>IF</strong> it is in the map. I have therefore already created the <code>Processor</code> class and mind you this is already the absolute shortest and most compact that I was able to come up with. Basically this method <em>does</em> already do only one thing.</p>
<p>But isn't it possible to build this differently so that it is shorter? I currently have 25+ cases to handle</p>
<p><strong>Edit:</strong> made clear what <code>Key,Value</code>-Pair is and what they're used for</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:16:04.310",
"Id": "72477",
"Score": "1",
"body": "You're passing in `Map<Key, Value> map` but you're only using the `map.keySet()`. Are you using the `Value`s in the `Map` for anything, or passing them into the `Processor` subroutines?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:24:23.050",
"Id": "72479",
"Score": "25",
"body": "**BEEP - BEEP - BEEP!** Strategy Pattern Alert!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:11:47.210",
"Id": "72677",
"Score": "0",
"body": "More fundamentally, see if you can't just have one processStuffAboutKey(...) and simply parameterize it based on a string/int, like @dss539. (Are the actions actually key-specific?)\n\nUnless yes, then Strategy Pattern is overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:20:03.887",
"Id": "72709",
"Score": "0",
"body": "They are very much key-specific and will do very different things"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:08:16.360",
"Id": "72817",
"Score": "1",
"body": "@SimonAndréForsberg BEEP BEEP BEEP you can also use the visitor pattern for more flexibility but added complexity!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-24T14:50:47.913",
"Id": "135897",
"Score": "0",
"body": "Although it is something that abounds in java programs, I would strongly recommend against passing containers/collections as parameters & return values. You have no idea what people can/are doing with them - the caller is free to mutate, copy etc etc. It is probably a type waiting to be found."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-15T02:03:16.707",
"Id": "294067",
"Score": "0",
"body": "@SimonForsberg When I read the question, Strategy Pattern came to mind. But if he has 25+ cases, would not that mean he has to add 25 more classes to apply the Strategy Pattern?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-15T08:01:46.573",
"Id": "294110",
"Score": "0",
"body": "@LazyNinja Or 25 methods and using lambdas. Java 8 introduces the `Consumer<T>` interface would be useful here, then you can implement each `Consumer<T>` in its own method and refer to them using a lambda."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-16T01:28:53.423",
"Id": "294299",
"Score": "0",
"body": "@SimonForsberg Thank you! I will look at it. Actually I am facing the same problem which I have posted here .\nhttp://codereview.stackexchange.com/q/155396/131044\nBut unfortunately it is put on hold as off topic."
}
] |
[
{
"body": "<p>You can create a <code>KeyProcessor</code> interface and implementation for every key (move the body of the current <code>Processor.processStuffAboutKeyX()</code> methods to these classes):</p>\n\n<pre><code>public interface KeyProcessor {\n void processStuff(String data);\n}\n</code></pre>\n\n<p>Then fill a map with the available implementations:</p>\n\n<pre><code>Map<Key, KeyProcessor> processors = new HashMap<>();\nprocessors.add(key1, new Key1Processor());\n...\nprocessors.add(key4, new Key2Processor());\n</code></pre>\n\n<p>And use that map in the loop:</p>\n\n<pre><code>for (Entry<Key, String> entry: map.entrySet()) {\n Key key = entry.getKey();\n KeyProcessor keyProcessor = processors.get(key);\n if (keyProcessor == null) {\n throw new IllegalStateException(\"Unknown processor for key \" + key);\n }\n final String value = entry.getValue();\n keyProcessor.processStuff(value);\n}\n</code></pre>\n\n<p>With the original 25+ cases the switch-case method is at least 75 lines long (25 <code>case</code> statement, 25 <code>break</code> statement, and at least 1-1 method call line for every case). The separate classes reduces the size and complexity which a developer see at once (+no need to scroll), the code is easier to maintain and test because you can test every case in isolation.</p>\n\n<p>I think it's a lot more easier to have (and handle) a couple of small classes and corresponding *Test classes (with a few test methods for every class) than having a big class (25+ cases) and a lot of tests in one corresponding *Test class or a lot of *Test classes which test separate case branches of the same <code>startProcessing</code> method.</p>\n\n<p>I admit that these arguments might be weak ones but without an actual implementation of the <code>Processor</code> class and the code which creates the input map is hard to say more.</p>\n\n<p>Further readings:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\">Replace Conditional with Polymorphism</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:24:51.770",
"Id": "72480",
"Score": "7",
"body": "Exactly what I was going to say, you beat me to it. StrategyPattern FTW!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:00:35.637",
"Id": "72546",
"Score": "9",
"body": "since `Key`is an `enum`, `EnumMap` should be used instead of `HashMap`. It's way more efficient (Effective Java, Item 33)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:10:54.013",
"Id": "72550",
"Score": "0",
"body": "@SeanPatrickFloyd: Thank you, good point, I've missed that. Write it as an answer, I'd upvote it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:22:39.510",
"Id": "72587",
"Score": "0",
"body": "I don't have much experience in Java, and what I have is very dated, but doesn't Java support first class functions? In C#, I'd probably make a `Dictionary<MyKeyEnum, Action<string>> processorLookup`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:27:49.093",
"Id": "72590",
"Score": "2",
"body": "@dss539 https://www.google.com/search?q=java+delegate suggests Java doesn't support such delegates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:58:38.220",
"Id": "72601",
"Score": "0",
"body": "@ChrisW thanks. I just looked and Java 8 still does not support it, even though they added \"functional interfaces\". It appears that you have to use Scala or Clojure if you want higher order functions in a JVM language. :( Glad I don't have to use Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:34:10.247",
"Id": "72608",
"Score": "8",
"body": "I might be missing something, but how is this any better than the `switch` solution? You just moved the 25 \"cases\" from one function to another (the one which initializes the map), plus you introduced 25 new classes. This is certainly \"more object-oriented\" than a `switch`, but that doesn't mean it's better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:50:44.617",
"Id": "72609",
"Score": "2",
"body": "The map is only better when you can use key, lambda. If you have to make a new derived class it's the bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:18:02.237",
"Id": "72633",
"Score": "0",
"body": "@FredOverflow: Good points, I've updated the answer a little bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:25:58.980",
"Id": "72652",
"Score": "3",
"body": "You could even go ahead and save the corresponding key in the class itself (getProcessedKey()). Thus the creation of all those classes and the filling of the map could be \"automated\". I used this approach once for a similar problem and found it to be quite maintainable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T22:42:12.070",
"Id": "72659",
"Score": "0",
"body": "You said \"a couple of small classes\", but isn't it \"25 small classes\" (a separate class for each key value)? So the LOC is 25 times however many lines it takes to define a class, plus 25 `processors.add` statements. Also I'm not sure how this would work if, instead of processStuffAboutKey1 etc being various methods of `new Processor` (which can presumably be replaced by diverse new subclasses of Processor), the processStuffAboutKey1 etc were all methods of the class which contains the switch statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:14:52.883",
"Id": "72706",
"Score": "1",
"body": "I think OO-wise this is the best answer so you'll get my green checkmark. But for future readers I think it's important to keep the comments of @FredOverflow and ChrisW in mind: this will probably not reduce the LOC"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:16:00.120",
"Id": "72819",
"Score": "0",
"body": "Its worth noting that if you were not using Enums but a non singleton object for the key you could use **Visitor Pattern** but since Java doesn't support multiple dispatch the downside of this approach is an uber interface that knows about all the types (classic *expression problem*)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:45:42.243",
"Id": "72822",
"Score": "0",
"body": "The problem with this answer is that your dictionary is, essentially, acting as a vtable. That's all well and good, but the language itself directly supports vtable lookup (i.e. inheritance) Using the built-in vtable (i.e. by creating a base KeyType with a virtual method `processStuff`) requires fewer LOC and is easier to maintain because it is DRY."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:06:43.267",
"Id": "72835",
"Score": "0",
"body": "@ChrisW: Yes, it's 25 small classes. I think LOC is not so important. It's interesting to see that what we do just (in general) to break a complex problem to manageable smaller chunks (otherwise we could use one class with one main method without line breaks). I think having small classes makes it easier to cope with. I agree with *Carsten*, I've used this a few times and it was really enjoyable to work with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:07:26.787",
"Id": "72837",
"Score": "0",
"body": "@ChrisW: If I understand correctly the second part, it could be more complex and harder to manage because the `processStuffAboutKey` method could access other fields (not just the passed String value). I might not access other fields/methods, but a maintainer can't be sure at first sight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:26:48.177",
"Id": "73842",
"Score": "3",
"body": "Moving away from switch is better as it promote open-close principle. Now generating this map can be even configurable, for e.g. reading keys from file and instantiating respective objects using runtime support, if needed. Which is not be possible with switch."
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:23:38.417",
"Id": "42126",
"ParentId": "42125",
"Score": "48"
}
},
{
"body": "<p>You can replace each case in the switch statement with a virtual function call, as shown in palacsint's answer.</p>\n\n<p>IMO palacsint's answer is little better (and arguably worse: more lines of code) than the original code. For example when you need to add support for a new key value, in your code you need to add a new case statement, and in palacsint's code you need to add a new class (derived from <code>KeyProcessor</code>) and add a new entry to the <code>processors</code> map.</p>\n\n<p>palacsint's strategy is much more worth implementing if you have <strong>two</strong> switch statements which do various things based on the key value (in which case <code>KeyProcessor</code> has more than one abstract method, a different method to replace each switch statement). Having one such switch statement isn't necessarily a bad idea.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/q/505454/49942\">Large Switch statements: Bad OOP?</a></p>\n\n<p>Also, you haven't said what types <code>Key</code> and <code>Value</code> are:perhaps one of these types could be constructed such that it contains an appropriate abstract method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:48:27.670",
"Id": "72494",
"Score": "0",
"body": "The `key` is an `enum` I built and the `value` is `String`. Edited the question accordingly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:59:06.990",
"Id": "72498",
"Score": "1",
"body": "You can put `processStuff` method in the `enum` using strategy pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:59:35.473",
"Id": "72603",
"Score": "0",
"body": "@avalancha How do you build the enum values? Instead of creating enum values, can you create instances of subclasses of an abstract class instead (or, select a flightweight singleton of a subclass)?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:39:10.070",
"Id": "42129",
"ParentId": "42125",
"Score": "7"
}
},
{
"body": "<p>An addition to the strategy and code of @palacsint is to use <code>Reflection</code> to automatically bind the classes that implement <code>KeyProcessor</code> to the dictionary. This way, you don't have to add each <code>KeyProcessor</code> manually and you don't have to remember it.</p>\n\n<p>Make sure that you only 'reflect' once because it is relatively slow. Thus add it to a static block or in the constructor of a singleton.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:23:19.480",
"Id": "72555",
"Score": "1",
"body": "I don't think using reflection would be a good advise"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:25:56.443",
"Id": "72558",
"Score": "0",
"body": "@GonzaloNaveira: Please elaborate. IMO **instead of remembering, I implement rules** via Reflection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:45:45.530",
"Id": "72563",
"Score": "2",
"body": "@Mimpen IMO in this case it doesn't worth it and I don't even mention the problems regarding the performances issues, refactoring and error prone it could be. By the other hand, yes, **somethimes** reflection is great; but not always."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:07:10.673",
"Id": "42146",
"ParentId": "42125",
"Score": "5"
}
},
{
"body": "<p>How about adding the functionality of the process methods to the enum itself? This way the enum itself knows how to process, and if you add a value to the enum you dont have to search for all switch statements in your code base to update these. \nYou can read more about this approach in Effective Java, by Joshua Bloch\nSomething like this:</p>\n\n<pre><code>private void startProcessing(Map<MyKeyEnum, String> map) {\n for (Entry entry : map.entrySet()) {\n entry.getKey().process(entry.getValue());\n }\n}\n\n\npublic enum MyKeyEnum {\n VALUE1 {\n public void process(String s) {\n // do specific processing for VALUE1\n }\n },\n VALUE2 {\n public void process(String s) {\n // do specific processing for VALUE2\n }\n }\n ...\n ;\n\n public abstract void process(String s);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:25:25.417",
"Id": "72557",
"Score": "3",
"body": "This is a good idea for small enums, but it is going to get messy when the enum grows. I'd prefer the EnumMap solution"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:11:26.150",
"Id": "72569",
"Score": "5",
"body": "With the EnumMap solution you still have the boilerplate code to add all the processors to the map, and 25+ Processor classes. I think it's a matter of taste."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:27:53.737",
"Id": "72591",
"Score": "0",
"body": "Yeah for this answer I'd say so, too. But could you give the exact item number in Effective Java you are referring to please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:30:34.313",
"Id": "72592",
"Score": "5",
"body": "This solution is the cleanest. You have identified the core problem being that `MyKeyEnum` really should be a base class with derived types KEY1, KEY2, etc. IMO, this enum shouldn't be an enum. Switch statement's like the OP's are a code smell that indicates an opportunity for polymorphism."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:46:02.703",
"Id": "72644",
"Score": "0",
"body": "@avalancha Item 30 in Effective Java 2nd edition. Look for the example with enum Operator, and onwards."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:22:31.240",
"Id": "42153",
"ParentId": "42125",
"Score": "12"
}
},
{
"body": "<p>Your enum should actually be a base class with the virtual method <code>processStuff(string)</code>.\nEach key should be it's own class and should implement the virtual method.</p>\n\n<p>This approach is similar to answer by <a href=\"https://codereview.stackexchange.com/a/42153/30851\">Paul S</a> but is more true to OO style.</p>\n\n<p>Applying the strategy pattern here is not a good idea in my opinion because it hides the core design problem and creates a lot of boilerplate.</p>\n\n<p>Of course, I'm not a fan of the strategy pattern in general:</p>\n\n<blockquote>\n <p>The Strategy pattern is beautiful on the surface, but Strategy objects are typically stateless, which means they're really just first-order functions in disguise. (If they have state, then they're Closures in disguise.) Etc. You either get this, because you've done functional programming before, or you don't, in which case I sound like I'm a babbling idiot, so I guess I'll wrap it up.</p>\n</blockquote>\n\n<p><a href=\"https://sites.google.com/site/steveyegge2/singleton-considered-stupid\" rel=\"nofollow noreferrer\">https://sites.google.com/site/steveyegge2/singleton-considered-stupid</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:59:23.957",
"Id": "72846",
"Score": "0",
"body": "+1. It does not have two similar object inheritance trees (which is a smell); encapsulates the data and operation in the same class; if you have a new key you just have to create a new subclass and don't have to modify the code in several places, you won't forget to add a case to the switch, etc. (single responsibility principle, DRY); and you don't have a long class, just small ones. (But I'd use an interface, not an abstract parent class. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:47:37.737",
"Id": "42169",
"ParentId": "42125",
"Score": "5"
}
},
{
"body": "<p>In line with @M. Mimpen's answer, get all methods of <code>Processor</code> object and store them in <code>Map<MyKeyEnum, Method></code>, where the key refers to the key from your parameter <code>map</code>. </p>\n\n<p>An alternative to this, is putting an entry to Map every time an entry is added to your <code>map</code> (the one you pass to the method).</p>\n\n<pre><code>//assume there is a populated Map<MyKeyEnum, Method>. Let's say it's named processorMethodMap\n\n private void startProcessing(Map<MyKeyEnum, String> map) {\n Processor myProcessor = new Processor();\n for (Entry entry : map.entrySet()) {\n //call the appropriate method\n processorMethodMap.get(entry.getValue()).invoke(<pass argument(s) here>);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T07:23:13.677",
"Id": "64359",
"ParentId": "42125",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "42126",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:08:47.307",
"Id": "42125",
"Score": "37",
"Tags": [
"java"
],
"Title": "Refactoring large switch statement"
}
|
42125
|
<p>I wrote a PHP function 7 days back , which avoids (calculate spamming severity) via manual spamming . So was just a curious to know, what if I create a JS plugin (my first) which can act as an SPAM validator on client side.</p>
<p>So here I am with my new jQuery plugin(beta version) which validate the existence of Spams in online forms etc( user input).</p>
<p>This plugin is in its starting point, and this is my first time when I am creating a jQuery plugin. I will really appreciate the valuable feedback.</p>
<p>Please point me whether I am wrong in my approach and how can I make it even better (is it feasible?).</p>
<p><a href="https://github.com/codingantGit/SpamDetection-Beta" rel="nofollow noreferrer">GITHUB link</a></p>
<p><a href="http://plugins.jquery.com/spamDetector-Beta/" rel="nofollow noreferrer">On jQuery</a></p>
<p><strong>Plugin code</strong></p>
<pre><code>(function ( $ ) //IIFE
{
$.fn.spamDetector = function(options)
{
var thisObj = this;
var is_spam = 0;
var settings = $.extend({
spamWordsInUri : ['free', 'vote', 'play'],
bannedWords : ['Levitra', 'viagra', 'casino', '*'],
alertText : 'Sorry, your content seems spammy , please check',
onlyReturnStatus: false,
spamLevel : 2,
checkOnType : true,
textLimit : 200,
displayWarning : true,
formObj : false,
warningStyle : { 'color': 'red', 'background-color': 'snow', 'padding': '1px','border': '2px solid red'}
}, options );
$(settings.errorTextContainer).html('<span id="error_text" style="display:none;">'+settings.alertText+'</span>');
$('#error_text').css(settings.warningStyle);
var calculateSpam = function(){
var text = thisObj.val();
var source = (text || '').toString();
var spam_point = 0;
var spamWordsInUri;
var urlArray = [];
var url;
var matchArray;
var return_array = [];
var regexToken = /(www\.|https?:\/\/)?[a-z0-9]+\.[a-z0-9]{2,4}\S*/gi;
while( (matchArray = regexToken.exec( source )) !== null ){
var token = matchArray[0];
urlArray.push( token );
}
var number_of_url = urlArray.length;
if(number_of_url > 0){
if(number_of_url > settings.maxUrlAllowed){
spam_point += settings.spamLevel ;
}
else{
spamWordsInUri = ['free', 'vote', 'play'];
$.each( urlArray, function( index, value ){
if(value.length > settings.maxUrlLength)
spam_point += 1;
$.each( settings.spamWordsInUri, function( index, value_spams ){
if (value.toLowerCase().indexOf(value_spams) >= 0){
spam_point += 1;
}
});
});
}
}
bannedWords = ['Levitra', 'viagra', 'casino', '*'];
$.each( settings.bannedWords, function( index, value ){
if (text.toLowerCase().indexOf(value) >= 0){
spam_point += settings.spamLevel;
}
});
if(settings.textLimit && settings.textLimit != ''){
if(text.length > settings.textLimit){
spam_point += settings.spamLevel;
}
}
if(spam_point >= settings.spamLevel){
if(! settings.onlyReturnStatus){
if(settings.displayWarning){
$('#error_text').show();
}
}
is_spam = 1;
}
else{
if(settings.displayWarning){
$('#error_text').hide();
}
is_spam = 0;
}
return is_spam;
};
if(! settings.onlyReturnStatus)
{
if(settings.checkOnType)
{
$( thisObj ).bind( "keyup keydown", function(e) {
calculateSpam();
if(settings.textLimit && settings.textLimit != ''){
$(settings.limitTextContainer).html("<span id='limit_box'></span>");
$('#limit_box').css(settings.limitStyle);
if(thisObj.val().length > settings.textLimit){
if( e.keyCode === 8 || e.keyCode === 46 ) {
return; // backspace (8) / delete (46)
}
if( e.keyCode >= 37 && e.keyCode <= 40 ) {
return; // arrow keys
}
e.preventDefault();
$('#limit_box').text("you can not exceed "+ ((settings.textLimit))+' characters limit');
}
else{
$('#limit_box').text("you have " + ((settings.textLimit)-thisObj.val().length)+' characters left');
}
}
});
}
if($(settings.formObj)){
$( settings.formObj).bind( "submit", function() {
if(calculateSpam())
return false;
});
}
}
else{
return calculateSpam();
}
};
}( jQuery ));
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><script type="text/javascript">
$( document ).ready(function(){
$( "#commentbox" ).spamDetector({
spamWordsInUri : ['free', 'vote', 'play'],
bannedWords : ['Levitra', 'viagra', 'casino', '*'],
alertText : 'Sorry, your content seems spammy , please check',
onlyReturnStatus : false,
spamLevel : 2,
textLimit : 200,
checkOnType : true,
displayWarning : true,
maxUrlAllowed : 2,
maxUrlLength : 150,
formObj : '#myForm',
errorTextContainer : '#myErrorDiv',
limitTextContainer : '#myLimitDiv',
warningStyle : { 'color': 'black', 'background-color': 'snow', 'padding': '.2px','border': '1px solid red'},
limitStyle : { 'color': '#580000' , 'background-color': '#E0E0E0'}
}
);
});
</script>
<div id='demo'><b>Demo</b></div>
<form id='myForm' >
<textarea rows="12" cols="80" name="comment" name='comment' id='commentbox'>Enter Comments here</textarea>
<div id='myErrorDiv' ></div>
<br/>
<div id='myLimitDiv' ></div>
<input type='submit' value='Enter'/>
</form>
</div>
</code></pre>
<p><img src="https://i.stack.imgur.com/2VokA.png" alt="FYI : configuartion settings"></p>
<p><strong>Basic configuration</strong> </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:18:08.817",
"Id": "72485",
"Score": "0",
"body": "I would point out that your code style isn't very JavaScript idiomatic. Too much whitespace makes it hard to read and KNF's style (braces on the same line) is preferred over Allman's."
}
] |
[
{
"body": "<p>I don't know if blocking specific few words (aka, creating a black list) is effective against spamming. Minor changes in the spelling will pass through your verification.</p>\n\n<p>I don't really think that many real people will loose their time posting spams. Even if they do, they will easily overcome your verification because there are TOO MANY ways of writing a word that makes it understandable by a human, but not by a machine:</p>\n\n<blockquote>\n <p>viagra ViAgrA VIAGRA V*iagra Vi*agra V*i*a*g*r*a V/i/a/g/r/a Vi//agra</p>\n</blockquote>\n\n<p>This cannot be simply preddicted, you'd need an AI algorithm to detect potential spammers.</p>\n\n<p>Other problems is that you prohibit legitimate users from using the <em>viagra</em> word just because it's used on spams, but you can't know for sure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:59:48.453",
"Id": "72513",
"Score": "0",
"body": "Yep agreed , as you can See I said \"manual spamming\" , for automated Bots we can use reCaptcha or so"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:01:52.720",
"Id": "72515",
"Score": "0",
"body": "That's true. Didn't noticed it. Edited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:04:11.613",
"Id": "72516",
"Score": "0",
"body": "anyways thanks @henrique for the comment/ suggestion . one thing I would like to point out is that we have a wide varity of option , which will ensure(may be not 100%) in stopping spams."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:14:28.463",
"Id": "72521",
"Score": "0",
"body": "I disagree, see the edited answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:21:38.983",
"Id": "72525",
"Score": "0",
"body": "see viagra ViAgrA VIAGRA V*iagra Vi*agra V*i*a*g*r*a all test it detected , other than last two . The point is to have atleast some form of check on spammers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:22:48.160",
"Id": "72527",
"Score": "0",
"body": "url length , content length and url words check are also other aspects whom you seems overlooking"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:25:08.147",
"Id": "72528",
"Score": "1",
"body": "URL length checking is very uneffective, since it's easy to shorten it using bit.ly, goo.gl, etc. I will not insist anymore, but your approach is not effective for preventing human spammers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:26:15.580",
"Id": "72529",
"Score": "0",
"body": "and we can ban that ip when detected for spamming via ajax request , what you say is that a good idea ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:30:04.833",
"Id": "72532",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13126/discussion-between-codingant-and-henrique-barcelos)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:33:03.517",
"Id": "72533",
"Score": "0",
"body": "see here itself , stackexchange not able to stop the spam word \"vi**gra\"..atleast my system would have notified"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:57:22.233",
"Id": "42143",
"ParentId": "42128",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:32:03.853",
"Id": "42128",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Spam validator - beta version"
}
|
42128
|
<p>I need to calculate the calendar week of a given date. Constraints:</p>
<ul>
<li>It should be properly calculated based on ISO 8601 if week starts on
Monday</li>
<li>It should calculate based on US standards if the week starts on
Sunday</li>
<li>It should be compact and fast, as the routine gets called very often</li>
<li>It should work even if the year start is not January (Fiscal Year starts on October for instance)</li>
</ul>
<p>That's what I have currently:</p>
<pre><code>Date.prototype.getWeek = function() { // ISO Week
this.firstDay = 4; // ISO 8601: Week with the first thursday which contains the 4th of January
this.thursday = 4; // 0 = Sunday OR Monday (if WeekStart = "M")
if ( this.weekStart != 'M' )
{
this.firstDay = 1; // switch to US norm: Week with the 1st of January
this.thursday = 0;
}
// finding the date of the "thursday" in this week
var donnerstag = function(datum, that) {
var Do = new Date(datum.getFullYear(), datum.getMonth(),
datum.getDate() - datum.getDay() + that.thursday, 0, 0, 0);
return Do;
};
// copy date, hourly times set to 0
var Datum = new Date(this.getFullYear(),this.getMonth(),this.getDate(), 0, 0, 0);
var DoDat = donnerstag(Datum, this); // the date of the first week
var kwjahr = DoDat.getFullYear(); // the year of that date
// diff from there to this date
var DoKW1 = donnerstag(new Date(kwjahr, this.FYStart, this.firstDay), this);
//console.log(DoDat + " - " + DoKW1);
// calculate the week
var kw = Math.floor(1.5+(DoDat.getTime()-DoKW1.getTime())/86400000/7)
// adjust overflow
if ( kw < 1 )
kw = 52 + kw;
return kw;
};
</code></pre>
<p>Is there any more compact algorithm or can this be optimized in terms of performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:11:05.897",
"Id": "72483",
"Score": "1",
"body": "Hmm, the mix of German variable names and English comments is amusing. For better understanding: `kw` stands for the *week of year*, `donnerstag` and `Do` are *Thursday*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:17:14.343",
"Id": "72484",
"Score": "0",
"body": "@amon: yepp, right. Reason for the mix: someone started (in German) and I took over. I am generally used to \"code\" in English entirely"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:03:29.683",
"Id": "72499",
"Score": "1",
"body": "If your project does many date manipulations involving javascript, it might be useful to get a 3rd party library like moment.js. Of course, for a single function this would be abit much, but if you have many of these functions, it could be worth investing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:09:49.410",
"Id": "72549",
"Score": "0",
"body": "@Nate: thanks for the tip. Way overloaded currently but good to know about it."
}
] |
[
{
"body": "<p>In my experience, Moment.js is somewhat too heavy for this simple task. Did some profiling not too long ago and the library does too much movement for this task. Maybe it's for robustness/scalability/compatibility purposes, but nevertheless, still heavy.</p>\n\n<p>Straight to the point, check out <a href=\"http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html\" rel=\"nofollow\">this blog post</a> which demonstrates his method of getting the ISO week. It appends an additional <code>getWeek</code> method to the native <code>Date</code> object. I have used this in one of my projects as substitute for Moment.js's ISO week function.</p>\n\n<pre><code>Date.prototype.getWeek = function () { \n // Create a copy of this date object \n var target = new Date(this.valueOf()); \n\n // ISO week date weeks start on monday so correct the day number \n var dayNr = (this.getDay() + 6) % 7; \n\n // ISO 8601 states that week 1 is the week with the first thursday of that year. \n // Set the target date to the thursday in the target week \n target.setDate(target.getDate() - dayNr + 3); \n\n // Store the millisecond value of the target date \n var firstThursday = target.valueOf(); \n\n // Set the target to the first thursday of the year \n // First set the target to january first \n target.setMonth(0, 1); \n // Not a thursday? Correct the date to the next thursday \n if (target.getDay() != 4) target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7); \n\n // The weeknumber is the number of weeks between the \n // first thursday of the year and the thursday in the target week \n return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000 \n} \n</code></pre>\n\n<p>As for your code:</p>\n\n<ul>\n<li><p>I suggest putting it in plain English as much as you can. Readability will be an issue for reviewers who prefer verbose, purposeful naming.</p></li>\n<li><p>Compared to the proposed code I have put up, your version creates way more <code>Date</code> objects (3 at my count). This could be a significant bottleneck if you are calling this function over a set of tabulated data. This is going to eat memory and CPU time.</p></li>\n<li><p>\"Cloning\" a <code>Date</code> is as simple as <code>var clone = new Date(original.valueOf());</code>. No need to individually call months, dates, etc. to setup the clone.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:35:00.737",
"Id": "72711",
"Score": "0",
"body": "Thanks for the code and reco's. Your solution does not take into account different start of Fiscal Year and can not switch to US standard. Anyway +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:07:17.093",
"Id": "72718",
"Score": "0",
"body": "Cloning the date is fine, BUT: in order to set the clock to midnight you need an additional call of setHours, ...Minutes, ...Seconds. Leaving the date at the current clock may result in rounding errors."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T01:40:28.223",
"Id": "42244",
"ParentId": "42131",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:56:42.897",
"Id": "42131",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"algorithm",
"datetime"
],
"Title": "Algorithm optimization on date calculation"
}
|
42131
|
<p>I've written a program to populate a particular object from multiple data sources, however I'm not convinced I'm going about this in the right way:</p>
<ol>
<li>I have no idea which (if any) design pattern I have used (possibly abstract factory)!</li>
<li>I really don't like the implementation as it doesn't feel right.</li>
</ol>
<p>I appreciate that this is verging on a little obsessive as the program works and meets the requirements for extensibility, however... is there a pattern that could be applied to solve this problem more effectively? What's right about my implementation? What's inherently wrong with my implementation? What could be done better?</p>
<p>NB. Please don't worry about the implementation of the <code>Provider.Load()</code> methods - it's the pattern I'm concerned about here.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
string xmlFileName = ConfigurationManager.AppSettings["CustomerLeadssXml"];
string csvFileName = ConfigurationManager.AppSettings["CustomerLeadssCsv"];
CustomerLeads customerLeadsFromXml = new CustomerLeads(new XmlCustomerLeadsProvider(xmlFileName));
customerLeadsFromXml.Load();
OutputCustomerLeads(customerLeadsFromXml);
Console.WriteLine("");
CustomerLeads customerLeadsFromCsv = new CustomerLeads(new CsvCustomerLeadsProvider(csvFileName));
customerLeadsFromCsv.Load();
OutputCustomerLeads(customerLeadsFromCsv);
Console.ReadKey();
}
static void OutputCustomerLeads(CustomerLeads customerLeads)
{
Console.WriteLine("CustomerLeads:");
foreach (CustomerLead customerLead in customerLeads.GetCustomerLeads())
{
Console.WriteLine("{0} {1} - {2}", customerLead.FirstName, customerLead.LastName, customerLead.EmailAddress);
}
Console.WriteLine("");
Console.WriteLine("CustomerLeadsSorted:");
foreach (CustomerLead customerLead in customerLeads.GetCustomerLeadsSorted())
{
Console.WriteLine("{0} {1} - {2}", customerLead.FirstName, customerLead.LastName, customerLead.EmailAddress);
}
}
}
</code></pre>
<hr>
<pre><code>public class CustomerLeads
{
private ICustomerLeadsProvider CustomerLeadsProvider { get; set; }
public CustomerLeads(ICustomerLeadsProvider customerLeadsProvider)
{
if (customerLeadsProvider == null)
throw new ArgumentException("CustomerLeadsProvider cannot be null", "customerLeadsProvider");
this.CustomerLeadsProvider = customerLeadsProvider;
}
public void Load()
{
this.CustomerLeadsProvider.Load();
}
public List<CustomerLead> GetCustomerLeads()
{
if (this.CustomerLeadsProvider.CustomerLeads == null)
return null;
return this.CustomerLeadsProvider.CustomerLeads.ToList<CustomerLead>();
}
public List<CustomerLead> GetCustomerLeadsSorted()
{
if (this.CustomerLeadsProvider.CustomerLeads == null)
return null;
return (from c in this.CustomerLeadsProvider.CustomerLeads
orderby c.LastName, c.FirstName, c.EmailAddress
select new CustomerLead()
{
FirstName = c.FirstName,
LastName = c.LastName,
EmailAddress = c.EmailAddress
}).ToList<CustomerLead>();
}
}
</code></pre>
<hr>
<pre><code>public interface ICustomerLeadsProvider
{
IEnumerable<CustomerLead> CustomerLeads { get; set; }
void Load();
}
</code></pre>
<hr>
<pre><code>public abstract class CustomerLeadsProvider : ICustomerLeadsProvider
{
public IEnumerable<CustomerLead> CustomerLeads { get; set; }
public abstract void Load();
protected bool IsValidFirstName(string firstName)
{
return !string.IsNullOrEmpty(firstName);
}
protected bool IsValidLastName(string lastName)
{
return !string.IsNullOrEmpty(lastName);
}
protected bool IsValidEmail(string emailAddress)
{
try
{
var mailAddress = new System.Net.Mail.MailAddress(emailAddress);
return true;
}
catch
{
return false;
}
}
}
</code></pre>
<hr>
<pre><code>public class XmlCustomerLeadsProvider : CustomerLeadsProvider
{
private string FileName { get; set; }
private XDocument CustomerLeadsXDocument { get; set; }
public XmlCustomerLeadsProvider(string fileName)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException("FileName cannot be null or empty.", "fileName");
this.FileName = fileName;
}
public override void Load()
{
this.CustomerLeadsXDocument = XDocument.Load(FileName);
base.CustomerLeads = from c in CustomerLeadsXDocument.Descendants("CustomerLead")
where base.IsValidFirstName((string)c.Descendants("FirstName").FirstOrDefault())
&& base.IsValidLastName((string)c.Descendants("LastName").FirstOrDefault())
&& base.IsValidEmail((string)c.Descendants("Email").FirstOrDefault())
select new CustomerLead()
{
FirstName = (string)c.Descendants("FirstName").FirstOrDefault(),
LastName = (string)c.Descendants("LastName").FirstOrDefault(),
EmailAddress = (string)c.Descendants("Email").FirstOrDefault()
};
}
}
</code></pre>
<hr>
<pre><code>public class CsvCustomerLeadsProvider : CustomerLeadsProvider
{
private string FileName { get; set; }
public CsvCustomerLeadsProvider(string fileName)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException("FileName cannot be null or empty.", "fileName");
this.FileName = fileName;
}
public override void Load()
{
this.CustomerLeads = from l in File.ReadAllLines(this.FileName).Skip(1)
let c = l.Split(',')
where base.IsValidFirstName(c[0])
&& base.IsValidLastName(c[1])
&& base.IsValidEmail(c[2])
select new CustomerLead
{
FirstName = c[0],
LastName = c[1],
EmailAddress = c[2]
};
}
}
</code></pre>
<hr>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<CustomerLeads>
<CustomerLead>
<FirstName>Paul</FirstName>
<LastName>Smith</LastName>
<Email>psmith@example.com</Email>
</CustomerLead>
<CustomerLead>
<FirstName>Nicole</FirstName>
<LastName>Farhi</LastName>
<Email>nicole.farhi@example.com</Email>
</CustomerLead>
<CustomerLead>
<FirstName>Raf</FirstName>
<LastName>Simons</LastName>
<Email>rafs@example.org</Email>
</CustomerLead>
</CustomerLeads>
</code></pre>
<hr>
<pre><code>FirstName,LastName,Email
Paul,Smith,psmith@example.com
Nicole,Farhi,nicole.farhi@example.com
Raf,Simons,rafs@example.org
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:40:55.510",
"Id": "72960",
"Score": "0",
"body": "This is referred to as the 'Repository pattern'. http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application"
}
] |
[
{
"body": "<blockquote>\n <p>What's right about my implementation?</p>\n</blockquote>\n\n<p>You are adhering to OCP principle, which is good - you can extend providers easily without changing other code.</p>\n\n<blockquote>\n <p>What's inherently wrong with my implementation?</p>\n</blockquote>\n\n<p>Your current implementation is good. You need some improvements, but nothing <em>inherently wrong</em> here.</p>\n\n<blockquote>\n <p>What could be done better?</p>\n</blockquote>\n\n<p>First thing which looks confusing to me is <code>Load()</code> method of provider:</p>\n\n<ul>\n<li>Somebody can forget to load data before reading CustomerLeads (I don't like methods which depend on other methods calls). At least you should throw something like <code>InvalidOperationException</code> if someone tries to get data from non-initialized provider.</li>\n<li>Loading all entities to provider and working with them can make your data obsolete, if files will be edited after you loaded data to provider. Especially that becomes problem if you will decide to keep data in shared database.</li>\n</ul>\n\n<p>Also there is a problem with setter of <code>CustomerLeads</code> property. I would expect that setting them back to provider will update my data in file. But actually I just change in-memory collection.</p>\n\n<p>So, I would remove <code>Load()</code> from provider interface, remove setter for CustomerLeads and also renamed provider to repository, because you are providing data, and <a href=\"http://martinfowler.com/eaaCatalog/repository.html\">repository</a> is more appropriate term for that:</p>\n\n<pre><code>public interface ICustomerLeadRepository\n{\n IEnumerable<CustomerLead> GetAll();\n}\n</code></pre>\n\n<p>Next is data verification. I think the best class wich knows what is appropriate values for first name, last name and email is CustomerLead itself. There is several options - one is adding guard conditions to each property setter, which will check if value is valid and throw exception if value is not valid:</p>\n\n<pre><code>public class CustomerLead\n{\n private string firstName;\n\n public string FirstName\n {\n get { return firstName; }\n set {\n if (String.IsNullOrEmpty(value))\n throw new ArgumentException();\n\n firstName = value;\n }\n }\n\n // ...\n}\n</code></pre>\n\n<p>Also you are missing very important part - you should log/notify about incorrect data in your datasource. If you have guard conditions, then parsing will throw exception rather than skipping incorrect data.</p>\n\n<p>So, implementation of repository can look like:</p>\n\n<pre><code>public class CustomerLeadsXmlRepository : ICustomerLeadRepository\n{\n private XDocument xdoc;\n\n public CustomerLeadsXmlRepository(string fileName)\n {\n xdoc = XDocument.Load(fileName);\n }\n\n public IEnumerable<CustomerLead> GetAll()\n {\n // reload xdoc if file was modified\n\n return from c in xdoc.Root.Elements(\"CustomerLead\")\n select new CustomerLead {\n FirstName = (string)c.Element(\"FirstName\"),\n LastName = (string)c.Element(\"LastName\")\n EmailAddress = (string)c.Element(\"EmailAddress\")\n }; \n }\n}\n</code></pre>\n\n<p>And last thing I would change is <code>CustomerLeads</code> class. I don't see any good reason for its existence - you can sort sequence of objects easily, especially if you will override Equals and GetHashCode methods of CustomerLead class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:01:08.230",
"Id": "72514",
"Score": "0",
"body": "you've not really answered the question, I'm interested in understanding the correct pattern to solve this problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:04:21.187",
"Id": "72517",
"Score": "0",
"body": "@JamesLaw [repository](http://martinfowler.com/eaaCatalog/repository.html) is a pattern"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:07:03.267",
"Id": "72518",
"Score": "0",
"body": "Yes, well done. I'm not convinced this is the right pattern to best solve the problem. What other pattern could be used more effectively?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:12:53.037",
"Id": "72520",
"Score": "0",
"body": "@JamesLaw patterns are used to solve problems. Here I can see one actual problem - abstracting data source from appication. That's what repositories intended to do. Other code is fine (well, I already pointed what I think can be improved). One more thing to be improved is `CustomerLeads` class. It would rename it to service and also removed `Load()` from it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:19:45.643",
"Id": "72523",
"Score": "0",
"body": "The problem isn't persisting the data (which is what I understand a repository pattern to be for), it's allowing the data to be loaded from several different sources (and for additional sources to be added with minimum effort) - I'm struggling here as you're really not answering the questions I'm asking - I don't want a critique of the code at a granular level, I want an understanding of the best way to approach these kind of problems and use and appropriate design pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:26:28.720",
"Id": "72530",
"Score": "0",
"body": "@JamesLaw I added explicit answers to your questions. I don't know what else you want to hear"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:33:12.650",
"Id": "72534",
"Score": "0",
"body": "What about \"is there a pattern that could be applied to solve this problem more effectively?\" - that's kind of the key one here. Thanks for your help nevertheless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:37:03.540",
"Id": "72538",
"Score": "0",
"body": "@JamesLaw more effectively than what? All you need to change data source is create and pass instance of appropriate provider. You thinkg that is inefficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:01:43.170",
"Id": "72547",
"Score": "0",
"body": "Not at all, it's a theoretical question - I know the code works but I want a \"perfect\" solution, not because I require one but because I want to understand better how I can apply design patterns to solving these sort of problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:41:55.580",
"Id": "72560",
"Score": "0",
"body": "@JamesLaw as I already stated, this sort of problems are solved by adhering to [OCP](http://www.oodesign.com/open-close-principle.html) - your `CustomerLeads` is closed for modification and opened for extension (i.e. adding new providers)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:38:22.153",
"Id": "42138",
"ParentId": "42133",
"Score": "10"
}
},
{
"body": "<p>For that I would just define a clean abstract interface class (lets say DataSource) and use Polymorhism.</p>\n\n<p>A factory will be good if you need more than one form of the same concrete type now and then and creating an object manually would be too stressfull (there are also other reasons for a factory like tracking the number of sources etc.). This really depends on the needs of your program and the big picture. </p>\n\n<p>Having a design pattern, where it does not make the situation clearer to understand is no good.</p>\n\n<p>Good naming, good specification to UML transformation, avoidance of code smells, KISS and SOLID are more important if you ask me. Master these and you are hell of a good programmer!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:12:00.713",
"Id": "42192",
"ParentId": "42133",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>I have no idea which (if any) design pattern I have used (possibly abstract factory)!</p>\n</blockquote>\n\n<p>You may be using <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy pattern</a>: implementing CustomerLeads methods using an abstract ICustomerLeadsProvider strategy.</p>\n\n<blockquote>\n <p>I really don't like the implementation as it doesn't feel right.</p>\n</blockquote>\n\n<p>The following changes would make the code simpler to use, simpler to implement, and/or faster to run:</p>\n\n<ul>\n<li>Instead of calling an explicit Load method, you could make Load private and invoke it automatically from the constructor.</li>\n<li>Instead of passing-in the filename you could invoke the ConfigurationManager.AppSettings method from inside the constructor.</li>\n<li>CustomerLeads doesn't do much (doesn't add much value): it mostly only delegates to the corresponding ICustomerLeadsProvider method. So you could get rid of CustomerLeads completely, and define its methods (e.g. GetCustomerLeads) in the CustomerLeadsProvider class instead.</li>\n<li>You could get rid of the ICustomerLeadsProvider interface and just use the abstract CustomerLeadsProvider class instead.</li>\n<li>You're storing the result of a Linq expression in the CustomerLeads property which is of type IEnumerable. Does that mean that the Linq expression is re-evaluated every time you iterate through the enumerable? If so is that what you want (e.g. because the underlying file contents are changing at run-time? Or would you prefer to iterate once and cache the result in a <code>List<></code>?</li>\n<li>GetCustomerLeadsSorted is creating new CustomerLead instances. Instead I'd copy existing CustomerLead instances into a new list (so that the same instance appears in both lists), and sort the new list.</li>\n</ul>\n\n<p>In summary you could do this with just three classes; one abstract CustomerLeadsProvider class:</p>\n\n<pre><code>public abstract class CustomerLeadsProvider\n{\n private List<CustomerLead> ListCustomerLeads;\n\n // or return IEnumerable<CustomerLead> so we don't need to copy the list\n public List<CustomerLead> GetCustomerLeads()\n {\n // return a copy of the list because otherwise caller can change the list\n // see http://programmers.stackexchange.com/q/185166/19237 for example\n return new List<CustomerLead>(ListCustomerLeads);\n }\n\n public List<CustomerLead> GetCustomerLeadsSorted()\n {\n // TODO: return a sorted copy of the list\n }\n\n // called from constructor of subclass on Load\n protected IEnumerable<CustomerLead> CustomerLeads\n {\n set { ListCustomerLeads = new List<CustomerLead>(value); }\n }\n\n protected bool IsValidFirstName(string firstName)\n {\n return !string.IsNullOrEmpty(firstName);\n }\n\n protected bool IsValidLastName(string lastName)\n {\n return !string.IsNullOrEmpty(lastName);\n }\n\n protected bool IsValidEmail(string emailAddress)\n {\n try\n {\n var mailAddress = new System.Net.Mail.MailAddress(emailAddress);\n return true;\n }\n catch\n {\n return false;\n }\n }\n}\n</code></pre>\n\n<p>... and two corresponding subclasses.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:50:34.700",
"Id": "42196",
"ParentId": "42133",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:29:18.970",
"Id": "42133",
"Score": "14",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
".net"
],
"Title": "Design pattern for implementing multiple data sources"
}
|
42133
|
<p>I've been unable to find a PHP function that will convert eol in files. This is what I have so far. It works, no errors.</p>
<p>Your educated opinions, thoughts, improvements, potential bugs and suggestions are welcome.</p>
<pre><code>/*
$file_name - full/path/to/file.name
$eol - wanted end of line: "\n", "\r", "\r\n"
from "\n" to "\r" || "\r\n"
from "\r\n" to "\r" || "\n"
from "\r" to "\n"
$len - buffer size
return true on success or false on fail
*/
function file_eol($file, $eol, $len=8192) {
$ok = FALSE;
$extension = '.my_temp';
$hread = FALSE;
if (is_string($file)) $hread = fopen($file, 'rb');
if ($hread === FALSE) e("Bad file in file_eol(): $file");
if (!is_resource($hread) || get_resource_type($hread) !== 'stream') e("Bad hread in file_eol(): $hread");
$hsave = fopen($file.$extension, 'wb');
if ($hsave === FALSE) e("Bad hsave file in file_eol(): $file.my_temp");
switch ($eol) {
case "\n": $order = array("\r\n", "\r"); // from "\r\n" || "\r" -> "\n"
break;
case "\r": $order = array("\r\n", "\n"); // from "\r\n" || "\n" -> "\r"
break;
case "\r\n": $order = array("\n", "\r\r\n"); // from "\n" -> "\r\n"
break;
default:
e("Bad eol in file_eol(): $eol");
}
while (($str = fread($hread, $len)) && $str !== FALSE) { // error or eof
$new = str_replace($order, $eol, $str);
// if (is_string($new)) $ok = fwrite($hsave, $new); // this ???
if ($new !== '') $ok = fwrite($hsave, $new);
if ($ok === FALSE) break; // or e("Error writing file: $file$extension");
}
$ok = $ok === FALSE ? FALSE : TRUE; // ok could be valid 0bytes
$ok = $ok && ((bool)$str || feof($hread)); // check if fread and feof failed
$ok = $ok && fclose($hread) && fclose($hsave); // ALWAYS check for fclose!
if ($ok) $ok = rename($file.$extension, $file); // overwrite $file, and delete $file.$extension
// else leave both files for later inspection
return $ok;
}
</code></pre>
<p>P.S. copy/paste should work if you create error handler function <code>e()</code> that will take string inputs or just change <code>e()</code> to <code>trigger_error</code> or whatever you want.</p>
<p><strong>Edit:</strong></p>
<p>Must include <code>feof()</code></p>
<pre><code>$ok = $ok && ((bool)$str || feof($hread)); // check if fread and feof failed
</code></pre>
|
[] |
[
{
"body": "<p>First of all, your function name sounds weird. The name of the function should brefly describe what it does, so, a name like <code>convertEol</code> would be more appropriate.</p>\n\n<p>Second, I see much redundancy on your code, like this part:</p>\n\n<pre><code>if ($hread === FALSE) e(\"Bad file in file_eol(): $file\");\nif (!is_resource($hread) || get_resource_type($hread) !== 'stream') e(\"Bad hread in file_eol(): $hread\");\n</code></pre>\n\n<p>As you can see on the <a href=\"http://www.php.net/manual/en/function.fopen.php\">PHP manual of <code>fopen</code> function</a>, it will return <code>false</code> if it is not able to open de file, otherwhise, it will ALWAYS return a <code>resource</code>, no matter what (except that you are doing something really crazy, like opening more files than a process is allowed to do).</p>\n\n<p>So, your second verification is redundant.</p>\n\n<p>Also, returning <code>boolean</code>s in functions that do not check for some condition it too old-fashioned, too 80's. The same way, triggering uncatchable errors is almost a crime.</p>\n\n<p>You should really learn how to work with <a href=\"http://www.php.net/manual/en/language.exceptions.php\"><code>Exceptions</code></a>.</p>\n\n<p>Here is what I would do, not necessarily the only one correct implementation:</p>\n\n<pre><code>function convertEol($fileName, $eolChar) {\n /* For windows, unix and mac.\n * IMPORTANT: for this implementation, \\r\\n MUST be the first element on the array\n */\n static $replaceableChars = array(\"\\r\\n\", \"\\n\", \"\\r\"); \n\n $originalFile, $tmpFile;\n\n try {\n $originalFile = new SplFileObject($fileName, 'r'); // open a file for reading\n } catch (RuntimeException $e) {\n throw new Exception(\"Unable to open file {$fileName} for reading\", null, $e);\n }\n\n try {\n $tmpFile = new SplFileObject(uniqid() . '.tmp', 'w+'); // open or create a file for writing\n } catch (RuntimeException $e) {\n throw new Exception(\"Unable to create temp file\", null, $e);\n }\n\n // iterates over the original file, line by line\n foreach ($originalFile as $line) {\n // writes the replaced string\n $tmpFile->fwrite(str_replace($replaceableChars, $eol, $line));\n }\n\n $tmpFile->fflush(); // makes sure file was written\n\n rename($tmpFile->getPathname(), $originalFile->getPathname());\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>// Normal\nconvertEol('path/to/file', \"\\n\");\n\n// Unexistent file\nconvertEol('path/to/unexistent/file', \"\\n\"); // will throw an exception\n\n// Catching error\ntry {\n convertEol('path/to/unexistent/file', \"\\n\");\n} catch (Exception $e) {\n echo 'Oops, something went wrong:' . $e->getTraceAsString();\n}\n// ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:42:42.723",
"Id": "72541",
"Score": "0",
"body": "Thank you :) Questions: How do you limit memory usage? Some lines could be few megabytes long. And, in your opinion, is it ok to create e() as function e($str){throw new Exception($str);}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:48:01.567",
"Id": "72543",
"Score": "0",
"body": "You still have to read until the end of the line to be able to change its EOL char. PHP can properly handle some few megabytes file. Don't worry about problems you might remotely have.\n\nAbout your function, there's a problem when you need an `Exception` subtype, like `RuntimeException`, `InvalidParameterException`, etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:39:28.910",
"Id": "42139",
"ParentId": "42135",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:45:24.407",
"Id": "42135",
"Score": "5",
"Tags": [
"php",
"converting",
"file"
],
"Title": "Function that converts file eol's"
}
|
42135
|
<p>This is the code I'm currently using to run a shell command on the current machine, intended for use only with GNU/Linux at the moment:</p>
<pre><code>std::string getCmdOutput(const std::string& mStr)
{
std::string result, file;
FILE* pipe{popen(mStr.c_str(), "r")};
char buffer[256];
while(fgets(buffer, sizeof(buffer), pipe) != NULL)
{
file = buffer;
result += file.substr(0, file.size() - 1);
}
pclose(pipe);
return result;
}
</code></pre>
<p>Example use:</p>
<pre><code>getCmdOutput(R"( sudo pacman -Syyuu )");
auto output(getCmdOutput(R"( echo /etc/pacman.conf )"));
</code></pre>
<p>I use this when making simple <em>script-like</em> C++ programs (mostly for personal use). </p>
<p>Is this the "correct" way of doing it? What can be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:11:48.370",
"Id": "72570",
"Score": "1",
"body": "In C++ I believe it is a bit more idiomatic to use fstream to open files instead of using FILE* which is a C API, but there doesn't appear to be anything wrong with what you're doing in that regard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T22:43:14.053",
"Id": "72660",
"Score": "0",
"body": "The pipe opens up a two way pipe so you can write to standard input of the application you started. I would rather wrap it up inside an stream so you can read/write from/to the stream and it ends up going to the application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:02:47.183",
"Id": "72674",
"Score": "0",
"body": "@YoungJohn: Could you please show me an example of using `std::ifstream` to get the output of a shell command? I tried using `std::getline` but I do not receive any output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:06:57.663",
"Id": "75658",
"Score": "0",
"body": "I would also like to know how to get the bash output into an ifstream."
}
] |
[
{
"body": "<p>Prefer comparing pointers to <code>nullptr</code> instead of to <code>NULL</code> in C++11. <code>nullptr</code> exists for exactly that reason. The <code>NULL</code> macro is not portable. While it exists in many different environments there is no guarantee how it will be implemented or what it is intended to be used for. It may be implemented as <code>0</code>, <code>'\\0'</code>, or as some pointer type, or anything else, and every different environment may define it differently or not at all. It is non-standard. <code>nullptr</code> is defined by the standard and all C++11 standard compliant compilers must support it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:12:38.047",
"Id": "42155",
"ParentId": "42148",
"Score": "5"
}
},
{
"body": "<p>Skipping the C++ specific parts, I would encourage you to do more for the error handling...</p>\n\n<ul>\n<li>check the return value of <code>popen</code>!!! (<code>nullptr</code> for the <code>FILE*</code>)</li>\n<li>check the return-value of <code>pclose()</code> If the pipe failed for any reason (including if there was an exit-code from the called script), the <code>pclose()</code> will be set to an error.</li>\n<li>you are not trapping the STDERR of the process you call, which means you are not capturing/buffering the output, and you may end up with crap on your console, or missing data you expect, or both.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:04:07.697",
"Id": "42172",
"ParentId": "42148",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42172",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:53:35.093",
"Id": "42148",
"Score": "8",
"Tags": [
"c++",
"c++11",
"bash",
"linux",
"shell"
],
"Title": "Running a shell command and getting output"
}
|
42148
|
<p>The following code will be used for educational purposes. It is to demonstrate various way that the box-shadow property can be used. Any feedback on areas where I have not used best practices would be great.</p>
<p><a href="http://jsbin.com/netonozi/2" rel="nofollow">Working example</a></p>
<p><strong>HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
<head>
<title>Box Shadow</title>
<link rel="stylesheet" type="text/css" href="boxshadow.css">
</head>
<body>
<!-- Introduction to the text shadow property -->
<div class="container one">
<div class="shadow1 box left"></div>
<div class="shadow2 box right"></div>
</div>
<div class="container two">
<div class="shadow3 box left"></div>
<div class="shadow4 box right"></div>
</div>
<div class="container three">
<div class="shadow5 box left"></div>
<div class="shadow6 box right"></div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre class="lang-css prettyprint-override"><code>body{
background: #ccc;
margin: 0;
}
.container{
padding: 20px 50px;
overflow: hidden;
}
.box{
background-color: #fff;
width: 500px;
height: 200px;
}
.left{
float: left;
}
.right{
float: right;
}
/* Basic Shadow */
.shadow1{
box-shadow: 5px 5px 0 rgba(150,150,150,0.5);
}
/* Inset Shadow and blur radius Variety */
.shadow2{
box-shadow: inset 0 0 10px black;
}
/* Inset Shadow and blur radius */
.shadow3{
background: #F2F2F2;
box-shadow: inset 3px 3px 3px #BFBFBF, inset -3px -3px 3px #8C8C8C;
border-radius: 10px;
}
/* Spread radius Shadow */
.shadow4{
box-shadow: 0 20px 10px -10px rgba(150,150,150,0.8);
}
/* Curved Shadows */
.shadow5{
position: relative;
overflow:hidden;
}
.shadow5:before{
content: "";
position: absolute;
z-index: 1;
width: 96%;
top: -15px;
height: 15px;
left: 2%;
border-radius: 100px / 5px;
box-shadow: 0 0 39px rgba(0,0,0,0.6);
}
.shadow5:after{
content: "";
position: absolute;
z-index: 1;
width: 96%;
bottom: -15px;
height: 15px;
left: 2%;
border-radius: 100px / 5px;
box-shadow: 0 0 39px rgba(0,0,0,0.6);
}
.shadow6{
position: relative;
overflow:hidden;
}
.shadow6:before{
content: "";
position:absolute;
z-index: 1;
width:10px;
top: 5%;
height: 90%;
left: -10px;
border-radius: 5px / 100px;
box-shadow:0 0 13px rgba(0,0,0,0.6);
}
.shadow6:after{
content: "";
position:absolute;
z-index: 1;
width:15px;
top: 5%;
height: 96%;
right: -15px;
border-radius: 5px / 100px;
box-shadow:0 0 13px rgba(0,0,0,0.6);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:15:44.570",
"Id": "73292",
"Score": "0",
"body": "One comment, more about the style than the code. Since your are demonstrating the shadows, I would: a) set the body background to white. Make clearer what is the shadow. b) set a distinct border on all the elements (may be blue, or green) make clearer when the shadow is inset or outset, and the relationship of it with the border"
}
] |
[
{
"body": "<p>they are all <code>.box</code> class. </p>\n\n<p>I am thinking that you should get rid of the container divs and get rid of the <code>.box</code> class and give it to all divs because after you get rid of the container divs all the divs will be the boxes.</p>\n\n<p>you should do one of those fancy HTML5 Tags for the content section instead of having a container classed div. </p>\n\n<p><a href=\"http://jsbin.com/netonozi/3\">check this out</a>, I have removed some tags and some CSS classes to make the code a little cleaner. the output is slightly different but I think this is a little bit better. if you need a width on the content you can add that as well.</p>\n\n<p>what happens when the browser window is resized is that the boxes are now hugging the left and right sides of the content, if you want to keep it to two rows at the max you would just add a width to the <code>content</code> tag</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I changed some more things to make this so that you could add more examples with ease, and so that it would be more view-able on mobile devices.</p>\n\n<p>This is the <a href=\"http://jsbin.com/jipusuxu/1/\">New Version</a> that I came up with</p>\n\n<p>I removed the <code>Left</code> and <code>Right</code> Classes, and moved the float left into the Styling for the Div tags, this way the boxes will wrap the viewport is resized. </p>\n\n<p>I also changed the size of the boxes.</p>\n\n<p>I removed the <code>container</code> classes as they weren't needed.</p>\n\n<p>I added the styling from the <code>box</code> class to the div's themselves.</p>\n\n<p>I am apparently wrong about sizing the <code>content</code> tag that I created, maybe it's not proper HTML5 or I was doing something wrong. </p>\n\n<p>Here is the code that I have after the changes that I made</p>\n\n<pre><code><!DOCTYPE HTML>\n<html>\n<head>\n <title>Box Shadow</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"boxshadow.css\">\n</head>\n<body>\n <!-- Introduction to the text shadow property -->\n <content> \n <div class=\"shadow1\"></div>\n <div class=\"shadow2\"></div>\n <div class=\"shadow3\"></div>\n <div class=\"shadow4\"></div>\n <div class=\"shadow5\"></div>\n <div class=\"shadow6\"></div>\n </content\n</body>\n</html>\n</code></pre>\n\n<h2>CSS</h2>\n\n<pre><code>body{\n background: #ccc;\n margin: 0;\n}\ncontent{\n width:1000px;\n}\ndiv {\n background-color: #fff;\n width: 500px; \n height: 200px;\n padding:15px;\n margin:15px;\n}\n.left{\n float: left;\n}\n.right{\n float: right;\n}\n/* Basic Shadow */\n.shadow1{\n box-shadow: 5px 5px 0 rgba(150,150,150,0.5);\n}\n/* Inset Shadow and blur radius Variety */\n.shadow2{\n box-shadow: inset 0 0 10px black;\n}\n/* Inset Shadow and blur radius */\n.shadow3{\n background: #F2F2F2;\n box-shadow: inset 3px 3px 3px #BFBFBF, inset -3px -3px 3px #8C8C8C;\n border-radius: 10px;\n}\n/* Spread radius Shadow */\n.shadow4{\n box-shadow: 0 20px 10px -10px rgba(150,150,150,0.8);\n}\n/* Curved Shadows */\n.shadow5{\n position: relative;\n overflow:hidden;\n}\n.shadow5:before{\n content: \"\";\n position: absolute;\n z-index: 1;\n width: 96%;\n top: -15px;\n height: 15px;\n left: 2%;\n border-radius: 100px / 5px;\n box-shadow: 0 0 39px rgba(0,0,0,0.6);\n}\n.shadow5:after{\n content: \"\";\n position: absolute;\n z-index: 1;\n width: 96%;\n bottom: -15px;\n height: 15px;\n left: 2%;\n border-radius: 100px / 5px;\n box-shadow: 0 0 39px rgba(0,0,0,0.6);\n}\n.shadow6{\n position: relative;\n overflow:hidden;\n}\n.shadow6:before{\n content: \"\"; \n position:absolute; \n z-index: 1; \n width:10px; \n top: 5%; \n height: 90%; \n left: -10px; \n border-radius: 5px / 100px; \n box-shadow:0 0 13px rgba(0,0,0,0.6); \n}\n.shadow6:after{\n content: \"\"; \n position:absolute; \n z-index: 1; \n width:15px; \n top: 5%; \n height: 96%; \n right: -15px; \n border-radius: 5px / 100px; \n box-shadow:0 0 13px rgba(0,0,0,0.6); \n}\n</code></pre>\n\n<p>Some other things that I noticed while pasting this new code is that you assign a <code>z-index</code> of 1 to some of your shadow styles and not to the others, I don't think that this is necessary for what you are doing here. the <code>z-index</code> defaults to 1 or 0 if I remember right, and that should be fine for what you are doing here so you don't even need to add that in there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:01:51.847",
"Id": "72604",
"Score": "1",
"body": "Thanks for your feedback, very helpful. I like the simpler html and good point about the z-index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T08:13:50.750",
"Id": "72714",
"Score": "1",
"body": "There is no `content` element. You probably mean the `main` element. It would be better to have the general styling on a `shadow-box` class instead of `div`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:17:22.070",
"Id": "72742",
"Score": "0",
"body": "I agree with you on the shadow-box class, except for this is just for a demonstration of the shadows, if there was anything else on the page, then yes I would use a Shadow-box class, so I guess that I would break the rules to follow the rules one this one. there isn't anything else that is being styled like that and isn't going to ever be anything on this page styled like that. good thing to mention though @kleinfreund"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:20:55.427",
"Id": "72743",
"Score": "0",
"body": "It's more about __not__ selectin `div` because div's are everywhere. You need something more specific. What's better than the class I suggested?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:28:02.310",
"Id": "72746",
"Score": "0",
"body": "I agree with you @kleinfreund. I am just saying this is an example, no need to make it more complicated than it is by adding more elements than needed to show the concept of shadows. the good point was that what you are saying should also be taught, probably not in the same lesson though. instead of `div`s they could have been `p` tags or `a` tags, anchor tags probably would have been a better choice, maybe? and really the divs are colored one way and the Shadow is a separate class even in my example. so it really does do the styling you suggest"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:17:16.140",
"Id": "42156",
"ParentId": "42151",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42156",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T14:09:10.727",
"Id": "42151",
"Score": "5",
"Tags": [
"html",
"css"
],
"Title": "Various different box shadows"
}
|
42151
|
<p>I'm wanting to calculate exponential moving averages of a variable, <code>distance</code>. Is the logic (and math) correct in the below code?</p>
<p><code>time</code> and <code>lastTime</code> are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.</p>
<p><code>lastA</code> etc are the exponential moving averages from the last calculations.</p>
<p><code>a</code> etc will be left with the calculated exponential moving averages.</p>
<pre><code>var distance = ...;
var a = Math.pow(1.16, -(time-lastTime)),
b = Math.pow(1.19, -(time-lastTime)),
c = Math.pow(1.22, -(time-lastTime)),
d = Math.pow(1.26, -(time-lastTime)),
e = Math.pow(1.30, -(time-lastTime)),
f = Math.pow(1.35, -(time-lastTime)),
g = Math.pow(1.40, -(time-lastTime));
a = a*lastA + (1-a)*distance;
b = b*lastB + (1-b)*distance;
c = c*lastC + (1-c)*distance;
d = d*lastD + (1-d)*distance;
e = e*lastE + (1-e)*distance;
f = f*lastF + (1-f)*distance;
g = g*lastG + (1-g)*distance;
</code></pre>
|
[] |
[
{
"body": "<p>This is border line a bad question, as not enough code is given to properly review it.</p>\n\n<p>The variables a -> g look terrible, I would create an array with the numbers you need:</p>\n\n<pre><code>var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];\n</code></pre>\n\n<p>Then I would would loop over those points and create an averages object</p>\n\n<pre><code>var averages = {},\n value, x;\nfor(var i = 0, length = dataPoints.length ; i < length ; i++ ){\n value = dataPoints[i];\n x = Math.pow(value, -(time-lastTime));\n averages[value] = x * lastAverages[value] + (1-x) * distance;\n}\n</code></pre>\n\n<p>I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T01:42:50.077",
"Id": "72683",
"Score": "2",
"body": "Why use objects for storage, though? Just use plain arrays for `averages` and `lastAverages`. Indices will match the `dataPoints` array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:24:26.800",
"Id": "72744",
"Score": "1",
"body": "@200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:44:46.413",
"Id": "42195",
"ParentId": "42157",
"Score": "4"
}
},
{
"body": "<p>Either I'm confused by your notation, or you may have implemented something completely different from an <a href=\"http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\" rel=\"nofollow\">exponential moving average</a>, which is traditionally defined as</p>\n\n<blockquote>\n <p>\\$S_{t} = \\alpha Y_{t-1} + (1-\\alpha) S_{t-1}\\$</p>\n \n <p>where</p>\n \n <ul>\n <li>\\$\\alpha\\$ is the decay rate</li>\n <li>\\$Y_{t}\\$ is the value at time \\$t\\$</li>\n <li>\\$S_{t}\\$ is the exponential moving average at time \\$t\\$.</li>\n </ul>\n</blockquote>\n\n<p>How do your variables correspond to those in the definition? Let's just consider one of your letters instead of all seven:</p>\n\n<blockquote>\n<pre><code>var distance = ...;\nvar a = Math.pow(1.16, -(time-lastTime));\na = a*lastA + (1-a)*distance;\n</code></pre>\n</blockquote>\n\n<p>I'm guessing</p>\n\n<ul>\n<li><code>a</code> corresponds to \\$\\alpha\\$, and you adjust the decay per timeslice based on the duration of the timeslice</li>\n<li><code>lastA</code> corresponds to \\$Y_{t-1}\\$</li>\n<li><code>distance</code> corresponds to \\$S_{t-1}\\$</li>\n</ul>\n\n<p>But then, I'm confused:</p>\n\n<ol>\n<li>What's the purpose of the seven letters <code>a</code> … <code>g</code>? To track the results using multiple decay rates? If so, wouldn't the different decay rates result in a different series <em>S<sub>t</sub></em> for each decay rate?</li>\n<li>Why do all seven cases all share the same <code>distance</code> — isn't it the point to have a different <code>distance</code> series for each case?</li>\n<li>Why do you assign the final result to <code>a</code> (= the decay rate) rather than to <code>distance</code> or something?</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:12:59.017",
"Id": "42268",
"ParentId": "42157",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:36:37.673",
"Id": "42157",
"Score": "1",
"Tags": [
"javascript",
"mathematics"
],
"Title": "Calculating exponential moving averages"
}
|
42157
|
<p>I am writing a simple quiz app using Tornado and MongoDB. The user authentication is done using Facebook and each user is uniquely identified by their Facebook ID. When a user first creates an account, his score will be set to zero and he can access only questions whose ID is less than or equal to his current score. And question IF start from zero. </p>
<p>The questions are accessed with URL and answers also submitted using URL only. Following is the URL scheme for valid for accessing questions:</p>
<pre><code>myapp.com/q_id
myapp.com/1
myapp.com/1/
</code></pre>
<p>The following scheme is valid for submitting answers:</p>
<pre><code>myapp.com/q_id/answer
myapp.com/1/hi
myapp.com/1/hi/
</code></pre>
<p>So, in summary:</p>
<ul>
<li><p>User logs in via Facebook, his Facebook ID will be stored in cookie</p>
<pre><code>self.set_secure_cookie('user_id', str(user['id']))
</code></pre></li>
<li><p>He will presented with the homepage where his current score is displayed and link to next question by: <code>myapp.com/score</code></p>
<pre><code>user_id = self.get_secure_cookie('user_id')
if user_id:
users = self.application.db.users
search_user = users.find_one({'user_id': user_id})
if not search_user: #i.e. new user
score = 0
name = self._get_fb_name(user_id)
users.save({'user_id': user_id,
'score': score,
'name' : name
})
else:
score = search_user.get('score')
name = search_user.get('name')
</code></pre></li>
<li><p>The user can access only questions whose ID equal to his current score (i.e. his next challenge) or less than current score (i.e. previously correctly answered questions)</p>
<pre><code>current_score = int(self.get_secure_cookie('score'))
if int(q_id) > current_score:
self.write('You cannot access this question as your score is less')
return
</code></pre></li>
<li><p>User submits answers as explained in above URL schemes. If answer is correct, then his score is updated in DB.</p>
<pre><code>question_data = questions.find_one({'q_id': q_id})
if not question_data:
self.write('Huh, this question no exist')
return
if not answer:
# user is requesting for next question
self.render("quest-template.html", qdata = question_data)
return
else:
if answer in question_data['q_ans']:
current_score += 1
# update score in db and in cookie
self.write('Correct answer, move to next question')
return
else:
self.write('Wrong answer buddy')
</code></pre></li>
</ul>
<p>Here is the complete Tornado app code:</p>
<pre><code>#!/usr/bin/env python
import os.path
import os
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
import pymongo
from pymongo import MongoClient
import requests
import views
from settings import *
define("port", default=8080, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', MainHandler),
(r'/auth/login', LoginHandler),
(r'/auth/logout', LogoutHandler),
(r'/(\d+)(/?\w*)', Q0Handler)
]
settings = application_handler_setttings
conn = MongoClient()
self.db = conn["mydb"]
tornado.web.Application.__init__(self, handlers, **settings)
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
if self.get_secure_cookie('user_name'):
return True
return None
class MainHandler(tornado.web.RequestHandler):
def get(self):
user_id = self.get_secure_cookie('user_id')
if user_id:
users = self.application.db.users
search_user = users.find_one({'user_id': user_id})
if not search_user:
score = 0
name = self._get_fb_name(user_id)
users.save({'user_id': user_id,
'score': score,
'name' : name
})
else:
score = search_user.get('score')
name = search_user.get('name')
self.set_secure_cookie('score', str(score))
self.render("index.html", user_name = name, score = score)
else:
self.render("login.html")
def _get_fb_name(self, user_id):
fb_graph_api_url = 'https://graph.facebook.com/%s' % user_id
r = requests.get(fb_graph_api_url)
return dict(r.json()).get('name')
class Q0Handler(BaseHandler):
@tornado.web.authenticated
def get(self, q_id, answer=None):
answer = answer[1:]
questions = self.application.db.questions
users = self.application.db.users
user_id = self.get_secure_cookie('user_id')
current_score = int(self.get_secure_cookie('score'))
if int(q_id) > current_score:
self.write('You cannot access this question as your score is less')
return
question_data = questions.find_one({'q_id': q_id})
if not question_data:
self.write('Huh, this question no exist')
return
if not answer:
self.render("quest-template.html", qdata = question_data)
return
else:
if answer in question_data['q_ans']:
current_score += 1
self.set_secure_cookie('score', str(current_score))
users.update({'user_id': user_id}, {'$set': {'score': current_score}})
self.write('Correct answer, move to next question')
return
else:
self.write('Wrong answer buddy')
class LoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
def get(self):
user_id = self.get_secure_cookie('user_id')
if self.get_argument('code', None):
self.get_authenticated_user(
redirect_uri=redirect_url,
client_id=self.settings['facebook_api_key'],
client_secret=self.settings['facebook_secret'],
code=self.get_argument('code'),
callback=self.async_callback(self._on_facebook_login))
return
elif self.get_secure_cookie('access_token'):
self.redirect('/')
self.authorize_redirect(
redirect_uri=redirect_url,
client_id=self.settings['facebook_api_key'],
extra_params={'scope': 'user_photos, publish_stream'}
)
def _on_facebook_login(self, user):
if not user:
self.clear_all_cookies()
raise tornado.web.HTTPError(500, 'Facebook authentication failed')
self.set_secure_cookie('user_id', str(user['id']))
self.set_secure_cookie('user_name', str(user['name']))
self.set_secure_cookie('access_token', str(user['access_token']))
self.redirect('/')
class LogoutHandler(tornado.web.RequestHandler):
def get(self):
self.clear_all_cookies()
self.render('logout.html')
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
</code></pre>
<ol>
<li>How do I improve my regex and is there any to avoid <code>answer = answer[1:]</code>? Currently my regex is so that the second parameter <code>answer</code> also contains leading slash. To remove it I am using slicing.</li>
<li>At every correct answer, I am updating the database and also the cookie. However, when I need to check his score, I am only seeing the cookie. Is that bad?</li>
<li>Earlier, I was not updating the database at every current answer, instead I was saving it in just cookie. But when user logs out, I save the scores to the database. Is this the right/suggested way?</li>
</ol>
|
[] |
[
{
"body": "<p>I'm not a Tornado expert, so these comments will be general to Python web development.</p>\n\n<p>I'll first answer your specific questions</p>\n\n<ol>\n<li><p>I don't know about your regexp, but you have a serious problem with Q0Handler.get; when <code>answer = None</code> (as is the default parameter), the line <code>answer = answer[1:]</code> will fail. I don't know if the code never gets called with the default parameter, in which case you don't need the default, but otherwise, you should probabaly change this to something like <code>answer = answer[1:] if answer is not None or None</code>.</p></li>\n<li><p>I would recommend checking the DB. In general, I like to think of all user data coming under 3 categories: Untrusted, Trusted but not reliable, Trusted and reliable. In web development, we can think of cookies as Untrusted (i.e. the user may manipulate they at will), secure/encryped cookies as Trusted but not reliable (i.e. the user may not manipulate the contents without it being obvious to you, but it's not guaranteed to {be,stay} {there,well formed}), and the database can be trusted (i.e. if I put data in there, it should stay there, though I note you are using MongoDB, so that invariant may not be applicable here).</p></li>\n</ol>\n\n<p>When it comes to implementing those properties, I would say this: you need to handle the case where someone deletes a cookie (i.e. wrap <code>self.get_secure_cookie('score')</code> in a try catch or test for <code>'score'</code>'s existence before hand). You also need to deal with cases where people are logged in on two browsers; if you just get data from cookies, then these will have different scores, which could be frustrating for the user. So all in all, It would just be easier to use the database in most places.</p>\n\n<hr>\n\n<p>I'll give some general comments now</p>\n\n<h2>Application</h2>\n\n<p>You currently hard code your urls, which could lead to a very brittle structure, and make extensibility a pain. Have you considered using class decorators to register route handlers? They'd look something like this:</p>\n\n<pre><code>class Application(tornado.web.Application):\n handlers = []\n\n @staticmethod\n def register_route(route):\n def inner(handler_class):\n Application.handlers.append((route, handler_class))\n return handler_class\n return inner\n\n ... # The rest of your Application class\n\n @Application.register_route(r'/foobar/(\\d+)')\n class MyFoobarHandler(tornado.web.RequestHandler):\n .... # Standard handler junk\n</code></pre>\n\n<p>However, that's probably just because I'm a Flask user, so I'm in love with decorators.</p>\n\n<p>Conciser using <code>super(Application, self).__init__(...)</code> over explicitly calling the constructor of the super class (this may not be possible, due to complications with old style classes, though don't quote me on that).</p>\n\n<p><code>\"mydb\"</code> wins the word for the worst name for a database I've seen all year ;)</p>\n\n<h2>BaseHandler</h2>\n\n<p>Having a function that returns <code>True</code> or <code>None</code> is usually a code smell. If you want a function that returns <code>True</code> and some value indicating the converse of <code>True</code>, usually people use <code>False</code>. In that case, you can rewrite the function as</p>\n\n<pre><code>def get_current_user(self):\n return bool(self.get_secure_cookie(\"user_name\"))\n</code></pre>\n\n<h2>MainHandler</h2>\n\n<p>The name <code>MainHandler</code> tells me nothing. Due to your routes being defined in a different place, maybe naming it something like <code>IndexHandler</code> would be better (though I still don't like that).</p>\n\n<p>An oft advised idiom on this site is the use of guard clauses. I'd recommend using that here; instead of</p>\n\n<pre><code>if user_id:\n ...\n 10 lines of code and 3 indentation levels ommited\n ...\n self.render(\"index.html\")\nelse:\n self.render(\"login.html\")\n</code></pre>\n\n<p>Something like this will read easier</p>\n\n<pre><code>if not user_id:\n self.render(\"login.html\")\n return\n # Insert your 10 lines of code and many indentation levels here\n ...\n self.render(\"index.html\")\n</code></pre>\n\n<p>See <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">something like this</a> for a better justification.</p>\n\n<p>In <code>_get_fb_name</code>, some things to note:</p>\n\n<ul>\n<li>If you were feeling REALLY paranoid (it's the best way to be), you should call <code>urlencode</code> on the <code>user_id</code> variable before constructing a URL with it.</li>\n<li>You should check <code>r.status_code</code> to make sure the request succeeded.</li>\n<li>If the request is well formed, <code>r.json()</code> will return a python dict (assuming the json has an object on the top level); no need to wrap it in a <code>dict</code> call. I would however check that it is indeed a <code>dict</code> that you are getting.</li>\n<li>My, you seem to love returning <code>None</code> in place of raising an exception or something. I'd recommend against it; returning a <code>None</code> is easy to overlook, and exceptions give you a glorious traceback.</li>\n</ul>\n\n<h2>Q0Handler</h2>\n\n<p>Numbers in class names make me feel slightly sick, and I have no idea what <code>Q0</code> means; question 0? Because this view seems to handle all questions, not just question 0.</p>\n\n<p>We've already discussed the <code>answer = answer[1:]</code> bug. There are a couple of other bugs; if I delete my <code>score</code> cookie, I'll end up causing a bug when you try to do <code>int((self.get_secure_cookie('score'))</code>; <code>int(None) -> TypeError</code> (same problem exists for <code>user_id</code>).</p>\n\n<p>When you do <code>users.update</code> to increment the score, I think you could be vulnerable to a race condition, but that's not too big a problem (I think Mongo supports an atomic increment, use that instead).</p>\n\n<p>Python convention when passing named parameters is to use <code>foo(bar=foz)</code> spacing not <code>foo(bar = foz)</code>, but that's just stylistic.</p>\n\n<hr>\n\n<p>I think that covers it from me. There will probably be someone out there who will turn up shortly to shout at me for talking about security without a PhD, but I think you should be OK (Hash your passwords, kids!).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:45:19.490",
"Id": "72697",
"Score": "0",
"body": "Thank you very much for great feedback ;-) I agree `mydb` is the worst name! Earlier I was using different handlers for questions and answers, in the process of renaming, I forgot about `Q0Handler`. I agree again, another worse name. In `Q0Handler`, I think it never gets called with `answer=None`, thats why I am not getting any error when I am trying to do `answer=answer[1:]`. If the `answer` is not present in URL, then it will be called with empty string and that's why slicing doesn't throw any error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:46:15.460",
"Id": "72698",
"Score": "0",
"body": "I am not hardcoding URLs and I am following standard [examples](https://github.com/facebook/tornado/blob/master/demos/blog/blog.py) from Tornado itself. But I will look into it. I don't know Flask, so I cannot really comment. Rest all your advice makes sense to me and I will correct my mistakes :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:24:14.107",
"Id": "42180",
"ParentId": "42158",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:38:39.027",
"Id": "42158",
"Score": "3",
"Tags": [
"python",
"mongodb",
"tornado",
"quiz"
],
"Title": "Tornado quiz app"
}
|
42158
|
<p>Below is a script to create and manage text snippets. It is also posted on <a href="https://github.com/adamlazz/snp">GitHub</a>. Most of the code is error checking and displaying help because I wanted to make a solid command line interface. The <code>blanks</code> function is used when copying a snippet with a blank (<code>@</code>) character in it. The user fills in the blanks.</p>
<p>I am looking for a review of the script: Is it easy to use? Is the code confusing? Are there any horrible bugs that I left unnoticed?</p>
<p>It is tested in OS X, so I am not sure if the syntax will work elsewhere. Specifically, the <code>pbcopy</code> and <code>pbpaste</code> aliases are untested.</p>
<pre><code>#!/bin/sh
list() {
echo "snp snippets:\n"
echo "$(ls -R $snippets_dir)"
}
move() {
if [[ "$2" == "" && $3 == "" ]]; then
echo "snp usage:\n"
echo "snp move <name> <group>"
elif [[ -e $snippets_dir/$2 ]]; then
if -d $snippets_dir/$3 ]]; then
mv $snippets_dir/$2 $snippets_dir/$3/$2
else
echo "ERROR: Group $snippets_dir/$3 does not exist."; exit 1
fi
else
echo "ERROR: Snippet $2 does not exist."; exit 1
fi
}
new() {
if [[ "$2" == "" && "$3" == "" ]]; then
echo "snp usage:\n"
echo "snp new <name> \"<text>\""
echo "snp new group <name>"
elif [[ "$2" == "group" || "$2" == "g" ]]; then # New group
if [[ "$3" != "" ]]; then
mkdir $snippets_dir/$3
echo "Created new group \"$3\"."
else
echo "snp usage:\n"
echo "snp new group <name>"
fi
else # New snippet
if [[ "$2" == "" ]]; then
echo "snp usage:\n"
echo "snp new <name> \"<text>\""
else
if [[ -e $snippets_dir/$2 ]]; then
echo "Snippet $snippet_dir/$2 already exists."
echo "Overwrite? [y/n]"
read yn
if [[ $yn == "y" || $yn == "Y" ]]; then
rm $snippets_dir/$2
else
return
fi
fi
printf "$3" >> $snippets_dir/$2
echo "Created new snippet \"$2\"."
fi
fi
}
remove() {
if [[ "$2" == "" ]]; then
echo "snp usage:\n"
echo "snp remove <name>"
echo "snp remove group <name>"
elif [[ "$2" == "group" || "$2" == "g" ]]; then # Remove group
if [[ "$3" != "" ]]; then
if [[ -e "$snippets_dir/$3" ]]; then
rm -rf $snippets_dir/$3
echo "Removed group \"$3\"."
else
echo "ERROR: Group $3 does not exist."; exit 1
fi
else
echo "snp usage:\n"
echo "snp remove group <name>"
fi
elif [[ "$2" != "" ]]; then # Remove snippet
if [[ -e $snippets_dir/$2 ]]; then
rm $snippets_dir/$2
echo "Removed snippet \"$2\"."
else
echo "ERROR: Snippet $2 does not exist."; exit 1
fi
fi
}
blanks() {
data=$(cat $1)
count=0
OIFS=$IFS
IFS="@"
blanx=$(echo "$data" | tr -d -c '@' | wc -c | awk '{print $1}')
result=""
for x in $data; do
if [ $count -eq $blanx ]; then
echo "$x"
result="$result$x"
break
fi
echo "$x"
result="$result$x"
read -p"snp> " v
result="$result$v"
count=`expr $count + 1`
done
IFS=$OIFS
printf "$result" >> $1-tmp
}
copy() {
if [[ "$1" == "" ]]; then
usage
elif [[ -e $snippets_dir/$1 ]]; then
if [ ! $(uname -s) = "Darwin" ]; then
alias pbcopy='xsel --clipboard --input'
fi
blanks $snippets_dir/$1
cat $snippets_dir/$1-tmp | pbcopy
echo "Snippet text copied to clipboard."
rm $snippets_dir/$1-tmp
else
echo "ERROR: Snippet $1 does not exist."; exit 1
fi
}
paste() {
if [[ "$2" == "" ]]; then
usage
elif [[ -e $snippets_dir/$2 ]]; then
if [ ! $(uname -s) = "Darwin" ]; then
alias pbcopy='xsel --clipboard --input'
alias pbpaste='xsel --clipboard --output'
fi
blanks $snippets_dir/$2
cat $snippets_dir/$2-tmp | pbcopy
pbpaste
rm $snippets_dir/$2-tmp
else
echo "ERROR: Snippet $2 does not exist."; exit 1
fi
}
usage() {
echo "snp usage:\n"
echo "snp <name> # Copy snippet to clipboard"
echo "snp paste <name> # Paste name (from clipboard)"
echo "snp new <name> \"<text>\" # New snippet"
echo "snp new group <name> # New group"
echo "snp list # List snippets"
echo "snp move <name> <group> # Move snippet to group"
echo "snp remove <name> # Remove snippet"
echo "snp remove group <name> # Remove group"
echo "snp help # Display usage"
}
snippets_dir=~/".snp"
# Check for/create snippet dir
if [[ ! -d $snippets_dir ]]; then
echo "ERROR: $snippets_dir doesn't exist."
echo "Create it now? [y/n]"
read yn
if [[ $yn == "y" || $yn == "Y" ]]; then
mkdir $snippets_dir
echo "$snippets_dir created"
else
exit 0
fi
fi
case $1 in
p|paste)
paste "$@" ;;
n|new)
new "$@" ;;
l|list)
list ;;
m|move)
move "$@" ;;
r|remove)
remove "$@" ;;
h|help)
usage ;;
*)
copy "$@" ;;
esac
exit 0
</code></pre>
|
[] |
[
{
"body": "<p>Overall</p>\n\n<ul>\n<li>You're using some bash-specific things (<code>[[ ... && ... ]]</code>), so your shebang line should be <code>#!/bin/bash</code></li>\n<li>very good indentation, readable code</li>\n<li>more quotes: <code>mv \"$snippets_dir/$2\" \"$snippets_dir/$3/$2\"</code></li>\n</ul>\n\n<p><code>list</code> function</p>\n\n<ul>\n<li><code>ls</code> knows how to print to the screen, don't need <code>echo $(ls ...)</code></li>\n</ul>\n\n<p><code>move</code> function</p>\n\n<ul>\n<li>you need <code>echo -e</code> if you want <code>\\n</code> to be interpreted as a newline.</li>\n<li>syntax error on 2nd <code>if</code>, missing <code>[[</code></li>\n</ul>\n\n<p><code>new</code> function</p>\n\n<ul>\n<li>if you use outer single quotes, don't need to escape inner double quotes (unless you need variable interpolation, of course)</li>\n<li>I would test for \"yes\" like this: <code>if [[ ${yn,} == y* ]]</code> -- see <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion\">http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion</a></li>\n</ul>\n\n<p><code>blanks</code> function</p>\n\n<ul>\n<li>declare local variables with <code>local</code></li>\n<li>to read content from a file in bash: <code>data=$(< \"$1\")</code></li>\n<li>bash can do arithmetic: <code>(( count++ ))</code> -- see <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs\">http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs</a></li>\n<li><p>you only ever use this function to copy stuff to the clipboard, so you don't need a temp file:</p>\n\n<pre><code>blanks \"$snippets_dir/$1\" | pbcopy\n</code></pre></li>\n<li><p>don't use <code>printf \"$astring\"</code> -- if $astring contains %-directives you'll get \"not enough arguments\" errors. Stick to <code>echo</code>, or if you're specifically avoiding a trailing newline, <code>printf \"%s\" \"$astring\"</code></p></li>\n</ul>\n\n<p><code>paste</code> function</p>\n\n<ul>\n<li><p>I would use <code>case</code> here, if you decide you need OS-specific aliases:</p>\n\n<pre><code>case $(uname -a) in\n Darwin) : ;;\n *) alias pbcopy='...'\n alias pbpaste='...'\n ;;\nesac\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:58:36.147",
"Id": "72600",
"Score": "1",
"body": "One more thing I just noticed: the code where you set the pbcopy alias should not be in the copy function, it should be in the \"main\" scope, or in a `setup` or `config` function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:40:21.357",
"Id": "42167",
"ParentId": "42159",
"Score": "7"
}
},
{
"body": "<p>I am not a great fan of fall-through logic ... if there is an argument issue (missing argument, whatever), you are falling through the work functions, and letting the program end. I would make this more explicit with an <code>exit 3</code>. Programs should always set an exit code unless they successfully complete. I don't consider argument errors to be a successful completion.</p>\n\n<p><strong>aside</strong> - Bash has some reserved exit codes, which you should typically not use. <a href=\"http://tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF\" rel=\"noreferrer\"><code>1</code> is one of the reserved exit codes</a>. As a result, try to use values other than 1 or 2 for exit codes from shell scripts....</p>\n\n<p>I would recommend creating an error-handling function... something along the lines of:</p>\n\n<pre><code>generalerror() {\n echo \"snp usage:\"\n echo $1\n echo\n usage\n exit 3\n}\n\ncheckargument() {\n if [[ \"$1\" == \"\" ]]; then\n generalerror $2\n fi\n}\n</code></pre>\n\n<p>This will allow you to centralize a lot of your error handling with some simpler messages/handling... the reason I am suggesting this is because of the following:</p>\n\n<blockquote>\n<pre><code>remove() {\n if [[ \"$2\" == \"\" ]]; then\n echo \"snp usage:\\n\"\n echo \"snp remove <name>\"\n echo \"snp remove group <name>\"\n elif [[ \"$2\" == \"group\" || \"$2\" == \"g\" ]]; then # Remove group\n if [[ \"$3\" != \"\" ]]; then\n if [[ -e \"$snippets_dir/$3\" ]]; then\n rm -rf $snippets_dir/$3\n echo \"Removed group \\\"$3\\\".\"\n else\n echo \"ERROR: Group $3 does not exist.\"; exit 1\n fi\n else\n echo \"snp usage:\\n\"\n echo \"snp remove group <name>\"\n fi\n</code></pre>\n</blockquote>\n\n<p>That code does not <code>exit 1</code>.... probably because it was just an oversight... and this is why functions are good ;-)</p>\n\n<p>The above code could be:</p>\n\n<pre><code>remove() {\n checkargument $2 \"snp remove <name>\\nsnp remove group <name>\"\n if [[ \"$2\" == \"group\" || \"$2\" == \"g\" ]]; then # Remove group\n checkargument $3 \"snp remove group <name>\"\n ....\n</code></pre>\n\n<p>Right, then your error handling:</p>\n\n<blockquote>\n<pre><code>cat $snippets_dir/$1-tmp | pbcopy\n</code></pre>\n</blockquote>\n\n<p>The above line is critical to your program.... but, it does not check for errors.... Did the pbcopy succeed?</p>\n\n<p>So:</p>\n\n<ul>\n<li>functions to extract common logic are useful....</li>\n<li>exit code set for bad values.</li>\n<li>different exit code for functional problems ... (failed sub-commands)</li>\n<li>error handling!</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:56:11.730",
"Id": "72597",
"Score": "0",
"body": "Thanks for your answer, this is a very interesting recommendation. I will definitely consider implementing it in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:40:33.343",
"Id": "42168",
"ParentId": "42159",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42167",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:47:46.263",
"Id": "42159",
"Score": "6",
"Tags": [
"bash",
"shell"
],
"Title": "Text snippet creator/manager in Bash"
}
|
42159
|
<p>I was looking at the different possible threading methods that I could use in my single-threaded application. What I have written so far is a class that will lock the thread when I instantiate the object, then unlock the thread when the object becomes out of scope. Here is what the class looks like:</p>
<p>ProcessCritSec.h</p>
<pre><code>#ifndef AFX_PROCESS_CRIT_SEC_H_
#define AFX_PROCESS_CRIT_SEC_H_
class CProcessCritSec
{
public:
CProcessCritSec(CCriticalSection* pcCriticalSection);
virtual ~CProcessCritSec();
private:
CCriticalSection* m_pcProcessCritSect;
};
#endif // !defined(AFX_PROCESS_CRIT_SEC_H_)
</code></pre>
<p>ProcessCritSec.cpp</p>
<pre><code>#include "StdAfx.h"
#include "ProcessCritSec.h"
CProcessCritSec::CProcessCritSec(CCriticalSection* pcCriticalSection)
{
m_pcProcessCritSect = pcCriticalSection;
if (m_pcProcessCritSect != NULL)
{
m_pcProcessCritSect->Lock();
}
}
CProcessCritSec::~CProcessCritSec()
{
if (m_pcProcessCritSect != NULL)
{
m_pcProcessCritSect->Unlock();
}
}
</code></pre>
<p>When I want to lock a thread I call this in a function:</p>
<pre><code>CProcessCritSec cThreadSafety(&m_cCriticalSection);
</code></pre>
<p>Is this a safe way to locking a thread? Or is there a safer way to making my application single-threaded? Also I have a side question: When I instantiate this object in a try/catch block like so:</p>
<pre><code>try
{
CProcessCritSec cThreadSafety(&m_cCritialSection);
Foo();
}
catch(...)
{
//Log Exception
}
</code></pre>
<p>Will the thread become unlocked if an exception occurred within <code>Foo()</code> and the catch block catches the exception?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>Is this a safe way to locking a thread?</p>\n</blockquote>\n\n<p>Yes, it's the recommended way: see for example <a href=\"http://en.cppreference.com/w/cpp/thread/lock_guard\" rel=\"nofollow noreferrer\">std::lock_guard</a></p>\n\n<p>However:</p>\n\n<ul>\n<li>I don't see why the destructor is virtual</li>\n<li>You should probably disable/prevent the copy constructor and assignment operator</li>\n<li>The constructor should probably take a reference (which can't be null) not a pointer</li>\n<li>Try to ensure (though you're probably doing this already) that the <a href=\"https://stackoverflow.com/a/130123/49942\">destructor will not throw an exception</a></li>\n</ul>\n\n<blockquote>\n <p>Will the thread become unlocked if an exception occurred within Foo() and the catch block catches the exception?</p>\n</blockquote>\n\n<p>It will unlock when CProcessCritSec is destroys, which happens as soon as it goes out of scope, which happens whenever you leave the <code>try</code> statement (before you enter any <code>catch</code> statement).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:17:04.777",
"Id": "72586",
"Score": "0",
"body": "The virtual on the destructor was a coding standard that I followed in a job. So you're saying that if I have the constructor take a reference, I won't have to worry about checking if it's null and the application will return an error at compile time If i try to set it to null?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:25:05.067",
"Id": "72588",
"Score": "2",
"body": "If the parameter is a reference instead of a pointer, then: `CProcessCritSec cThreadSafety(m_cCritialSection);` is expected/legal; `CProcessCritSec cThreadSafety(null);` is a compiler error; and `CCriticalSection* pcCriticalSection = 0; CProcessCritSec cThreadSafety(*pcCriticalSection);` is a run-time error, but you are allowed to blame the person who wrote that statement (instead of blaming your CProcessCritSec class) for trying dereference a null pointer. I prefer a reference instead of a pointer, when I want to document that the value can't/mustn't be a null pointer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:30:39.190",
"Id": "72593",
"Score": "0",
"body": "Ok cool, this has answered my questions, Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:13:19.403",
"Id": "42163",
"ParentId": "42161",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42163",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:49:31.097",
"Id": "42161",
"Score": "5",
"Tags": [
"c++",
"thread-safety"
],
"Title": "What is a safe way to lock a thread in a single-threaded application?"
}
|
42161
|
<p>I am trying to develop a simple inventory system that takes JSON data gathered from a Powershell script, inputs the data into a MongoDB, and displays the info in an interesting manner for the user. It works well at the moment, but I do have a few interesting questions about how I did this, i.e. should I make the DB connection once at the top of my server.py file or every time I call a method? In a future edition, I'll try to have SSL and LDAP SSO integrated.</p>
<p><strong>1. Gather the information</strong></p>
<p>Right now, I am using Powershell + WMIC to get the information. I am not sure if there is a better way to get it (maybe an agent on a machine?), but here is the code and output for that:</p>
<p>fingerprint.ps1</p>
<pre><code><#####################################################################
Fingerprint by jeff Tindell
#####################################################################>
<#####################################################################
Global Variables
#####################################################################>
#dictionaries
#Drive type dictionary (from http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx)
$driveTypeDictionary = "Unknown","No Root Directory", "Removable Disk", "Local Disk", "Network Drive", "Compact Disk", "RAM Disk"
#OS Version number dictionary (from http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx)
$osProductTypeDictionary = "Unknown","Client","Domain Controller","Server"
#Windows Client Dictionaries
$winClientDictionary = @{"6.3" = "Windows 8.1"; "6.2" = "Windows 8"; "6.1" = "Windows 7"; "6.0" = "Windows Vista";
"5.2" = "Windows XP 64-Bit"; "5.1" = "Windows XP"}
$winServerDictionary = @{"6.3" = "Windows Server 2012 R2"; "6.2" = "Windows Server 2012"; "6.1" = "Windows Server 2008 R2";
"6.0" = "Windows Server 2008"; "5.2" = "Windows Server 2003 R2"; "5.1" = "Windows Server 2003"}
#variables
$masterOutput = @{}
<#####################################################################
Input Variables
#####################################################################>
<#####################################################################
WMI Calls
#####################################################################>
$computerSystemInfo = gwmi Win32_computerSystem
$motherboardInfo = gwmi Win32_baseboard
$cpuInfo = gwmi Win32_processor
$winInfo = gwmi Win32_operatingSystem
$memoryInfo = gwmi Win32_PhysicalMemory
$drivesInfo = gwmi Win32_LogicalDisk
$networkInfo = (gwmi win32_networkadapterconfiguration | where IPAddress -NE $NULL)
<#####################################################################
Logic
#####################################################################>
#Computer System Info
$domain = $computerSystemInfo.Domain
$manufacturer = $computerSystemInfo.Manufacturer
$model = $computerSystemInfo.Model
$computerName = $computerSystemInfo.Name
#computer system output
$systemInfoOutput = @{"computer_domain"= "$domain";"computer_name" = "$computerName"; "system_make"=$manufacturer; "system_model"=$model}
$masterOutput.Add("system_info", $systemInfoOutput)
#Motherboard Info
$mbMake = $motherboardInfo.Manufacturer
$mbSerial = $motherboardInfo.SerialNumber
#motherboard output
$mbOutput = @{"make" = "$mbMake"; "serial" = "$mbSerial"}
$masterOutput.Add("motherboard_info", $mbOutput)
#CPU Info
$cpuManufacturer = $cpuInfo.Manufacturer
$cpuSpeed = "{0:N1}" -f ($cpuInfo.MaxClockSpeed/1000) + "GHz"
$cpuName = $cpuInfo.Name
#cpuOutput
$cpuInfoOutput = @{"name" = "$cpuName"; "make" = "$cpuManufacturer"; "speed" = "$cpuSpeed"}
$masterOutput.Add("cpu_info", $cpuInfoOutput)
#os Info
$osProdType = $osProductTypeDictionary[($winInfo.ProductType)]
$osBit = $winInfo.OSArchitecture
$osMajorVersion = $winInfo.Version.Substring(0,3)
$winVersionName =""
switch ($osProdType) {
"Unknown" {$winVersionName = $winClientDictionary.get_Item($osMajorVersion)}
"Client" {$winVersionName = $winClientDictionary.get_Item($osMajorVersion)}
default {$winVersionName = $winServerDictionary.get_Item($osMajorVersion)}
}
$osVersionNumber = $winInfo.Version
#OS output
$osInfoOutput = @{"name" = "$winVersionName"; "osBit"= "$osBit"; version_number= "$osVersionNumber"; "type" = "$osProdType"}
$masterOutput.Add("os_info", $osInfoOutput)
#physical memory info
$memorySize = $memoryInfo.Capacity/1073741824 #in GB
$memorySpeed = $memoryInfo.Speed
#memory Output
$memoryOutput = @{"size" = "$memorySize"; "speed" = "$memorySpeed"}
$masterOutput.Add("memory_info", $memoryOutput)
#Hard drive Info
#drive Output
$drivesOutput = @{}
$currentDrive=1
foreach ($drive in $drivesInfo){
$currentDriveHash = @{}
$currentDriveHash.Add("device_id", $drive.DeviceID)
$currentDriveHash.Add("name", $drive.VolumeName)
$currentDriveHash.Add("type" , ($driveTypeDictionary[($drive.DriveType)]))
$currentDriveHash.Add("free", $drive.FreeSpace)
$currentDriveHash.Add("used", ($drive.size - $drive.FreeSpace))
$currentDriveHash.Add("max_size", $drive.Size)
$drivesOutput.add("drive_$currentDrive", $currentDriveHash)
$currentDrive++
}
$masterOutput.Add("drive_info", $drivesOutput)
$networkOutput = @{}
$currentNetDevice = 1
foreach ($netDevice in $networkInfo){
$currentIP = ($netDevice.IPAddress | Where-Object {$_ -like "*.*.*.*"})
$currentNetHash = @{}
$currentNetHash.Add("name", $netDevice.Description)
$currentNetHash.Add("dhcp", $netDevice.DHCPEnabled)
$currentNetHash.Add("ip", $currentIP)
$currentNetHash.Add("gw", $netDevice.defaultIPGateway)
$networkOutput.add("interface_$currentNetDevice", $currentNetHash)
$currentNetDevice++
}
$masterOutput.Add("net_info", $networkOutput)
<#####################################################################
Output
#####################################################################>
$jsonOutput = $masterOutput | ConvertTo-Json
Set-Content -Path "././$Computername.json" -Encoding UTF8 -Value $jsonOutput
<#####################################################################
import into mongodb
#####################################################################>
</code></pre>
<p>This would produce a sample output file (template.json):</p>
<pre><code>{
"device_name":"COMPUTERNAME",
"cpu_make": "GenuineIntel",
"cpu_name": "Intel(R) Core(TM) i7-3517U CPU @ 1.90GHz",
"cpu_speed": "2.4GHz",
"type" : "server",
"system_computer_domain": "WORKGROUP",
"system_computer_name": "COMPUTERNAME",
"system_make": "LENOVO",
"system_model": "20175",
"os_type": "Client",
"os_bit": "64-bit",
"os_name": "Windows 8.1",
"os_version_number": "6.3.9600",
"mb_serial": "EB32244241",
"mb_make": "LENOVO",
"eth0_gw": "192.168.101.1",
"eth0_dhcp": true,
"eth0_name": "ASIX AX88772B USB2.0 to Fast Ethernet Adapter",
"eth0_ip": "192.168.0.4",
"mem_size": "8",
"mem_speed": "1600",
"drive2_device_id": "D:",
"drive2_type": "Local Disk",
"drive2_used": 1830584320,
"drive2_max_size": 4294963200,
"drive2_name": "LENOVO",
"drive2_free": 2464378880,
"drive1_device_id": "C:",
"drive1_type": "Local Disk",
"drive1_used": 39408615424,
"drive1_max_size": 99026464768,
"drive1_name": "Windows8_OS",
"drive1_free": 59617849344
}
</code></pre>
<p><strong>2. Import the Data</strong></p>
<p>Next I import the data using the CL of <code>mongoimport</code>:</p>
<pre><code>mongoimport --host localhost --db pacman --collection {servers | net_devices} .\{FILENAME}
</code></pre>
<p><strong>3. Display the data</strong></p>
<p>Finally I display the data in a WebApp using bottle and pymongo. Here is my dir structure for the project (called "pacman" for performance and capacity management):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>PACMAN
|--static
|--css
|--style.css
|--img
|--delete.png
|--edit.png
|--views
|--file_control
|--add_file_to_existing.tpl
|--edit_existing_filename.tpl
|--device_view.tpl
|--home.tpl
|--server.py
</code></pre>
</blockquote>
<p><strong>Server.py</strong></p>
<pre class="lang-python prettyprint-override"><code>import copy
import mimetypes
import bottle
from bson import ObjectId
import gridfs
import pymongo
import sys
__author__ = 'Jeff Tindell'
# Preformance And Capacity MANagment (system)
# The point of this program is to take json documents consisting of server or network devices basic configuration
# and display it on a basic web form.
# It will also hold and link documents regarding the systems (config files or whatever).
#establish a connection to the db:
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.pacman
# get collections of my network devices and servers in the inventory
net_devices_col = db.net_devices
servers_col = db.servers
errors = []
#get gridfs for the two dbs
fs = gridfs.GridFS(db)
# Static Routes
@bottle.get('/<filename:re:.*\.js>')
def javascripts(filename):
return bottle.static_file(filename, root='static/js')
@bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
return bottle.static_file(filename, root='static/css')
@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
return bottle.static_file(filename, root='static/img')
@bottle.get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
return bottle.static_file(filename, root='static/fonts')
#home page
@bottle.route('/')
def home_page():
#copy any errors out of the errors dict, and then empty the dict
err_list = copy.deepcopy(errors)
errors[:] = []
#run a search for all servers and net_devices
net_devices = net_devices_col.find()
servers = servers_col.find()
#send the results to the home page:
template_args = {'network_devices': net_devices, 'servers': servers, 'errors': err_list}
return bottle.template('home.tpl', template_args)
@bottle.route('/showDevice')
def show_device():
# get the url information (passed in as /showDevice?id=35jfjae3...&type=server)
# type will either be server or net (for now).
device_id = bottle.request.query.id
device_type = bottle.request.query.type
cursor = None
device = {}
attached_files = {}
if device_id: # was an id sent in?
# if so, search the database for the proper object
query = {"_id" : ObjectId(device_id)}
if device_type == "server":
cursor = db.servers.find(query)
elif device_type == "net":
cursor = db.net_devices.find(query)
else: # couldnt find device type
errors.append({'text': 'device type not recognized'})
else: # no id was sent in
errors.append({'text':'Device not found, No id sent in.'})
#after the search
if cursor: #if the search turn up something
for documents in cursor: # get the dictionaries out of the cursor
device = documents
#search the files db for any attached files
attached_files = db.fs.files.find({"device_id" : ObjectId(device_id)})
# return the search results
return bottle.template('device_view.tpl', {'device': device, 'attached_files': attached_files})
else: #the search was unsucessful
errors.append({'text': 'search turned up no results'})
bottle.redirect('/')
@bottle.route('/addDevice')
def add_device():
return None
@bottle.route('/addFile')
def add_file():
device_id = bottle.request.query.id
device_name = bottle.request.query.name
device_type = bottle.request.query.type
device={'_id': device_id, 'name': device_name, 'type': device_type}
return bottle.template('file_control/add_file_to_existing.tpl', {'device':device})
@bottle.route('/upload', method='POST')
def do_upload():
data = bottle.request.files.data
did = bottle.request.query.id
type = bottle.request.query.type
device_url = '/showDevice?id=' + str(did) + '&type=' + type+'#files'
raw = data.file.read() # This is dangerous for big files
file_name = data.filename
try:
newfile_id = fs.put(raw, filename=file_name, device_id = ObjectId(did))
except:
return "error inserting new file"
return bottle.redirect(device_url)
@bottle.route('/download')
def download():
file_id = ObjectId(bottle.request.query.id)
if file_id:
try:
file_to_download = fs.get(file_id)
except:
return "document id not found for id:" + file_id, sys.exc_info()[0]
file_extension = str(file_to_download.name)[(str(file_to_download.name).index('.')):]
bottle.response.headers['Content-Type'] = (mimetypes.types_map[file_extension])
bottle.response.headers['Content-Disposition'] = 'attachment; filename=' + file_to_download.name
return file_to_download
@bottle.route('/editFilename')
def edit_page():
# in comes device id, device type, and file id, and filename
device_id = bottle.request.query.did
fid = bottle.request.query.fid
device_type = bottle.request.query.type
old_filename = bottle.request.query.ofn
filedict = {'_id': ObjectId(fid), 'ofn': old_filename}
device={'_id': ObjectId(device_id), 'type': device_type}
return bottle.template('file_control/edit_existing_filename.tpl', {'device':device, 'file':filedict})
@bottle.route('/updateFilename', method='POST')
def update_filename():
# /updateFilename?fid=FILE_ID&did=DEVICE_ID&type=TYPE
fid= ObjectId(bottle.request.query.fid)
did= ObjectId(bottle.request.query.did)
dtype = bottle.request.query.type
form_dict = bottle.request.forms
new_name = str(form_dict['new_filename']) + str(form_dict['ext'])
device_url = '/showDevice?id=' + str(did) + '&type=' + dtype + '#files'
db.fs.files.update({'_id': fid}, {'$set': {'filename': new_name}})
return bottle.redirect(device_url)
@bottle.route('/removeFile')
def delete_file():
# /removeFile?fid=FILE_ID&did=DEVICE_ID&type=TYPE
fid= ObjectId(bottle.request.query.fid)
did = ObjectId(bottle.request.query.did)
dtype = bottle.request.query.type
device_url = '/showDevice?id=' + str(did) + '&type=' + dtype + '#files'
fs.delete(fid)
return bottle.redirect(device_url)
@bottle.route('/removeDevice')
def delete_device():
# Need to delete any files related to this device, then delete the device
did = ObjectId(bottle.request.query.did)
dtype = bottle.request.query.type
results = db.fs.files.find({'device_id': did})
for file in results:
fs.delete(file['_id']) # delete all files associated with this entry
if dtype == 'net':
col = db.net_devices
elif dtype == 'server':
col = db.servers
else:
return bottle.redirect('/')
col.remove(did)
return bottle.redirect('/')
bottle.debug(True)
bottle.run(host='localhost', port=8080)
</code></pre>
<p>There is a lot more code, but rather than display it all, I'll just put up a img of the homepage and the page after clicking on a device:</p>
<p><strong>Home</strong></p>
<p><img src="https://i.stack.imgur.com/j3bSL.jpg" alt="home page"></p>
<p><strong>Device</strong></p>
<p><img src="https://i.stack.imgur.com/q60uN.jpg" alt="device page"></p>
<p>I am not a full-time developer, so I look forward to any insight anyone could provide.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:57:14.820",
"Id": "72598",
"Score": "3",
"body": "Providing screenshot is a really nice touch. Thanks for asking well documented question, I wish I could help you :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:20:37.907",
"Id": "73880",
"Score": "0",
"body": "Thanks Josay. I'll attempt to update my code, but to find the most up to date code: github.com/jdell64/IPACS"
}
] |
[
{
"body": "<p>Okay, so this looks quite good!</p>\n\n<ol>\n<li>Connecting to the database at the top makes sense, since you want to be connected to it at all times. This is the best option in bottle, especially if you are not afraid of loosing the connection. In more complete frameworks, the database connections are handled for you, and various options exist, such as <a href=\"https://docs.djangoproject.com/en/1.6/ref/databases/#persistent-connections\" rel=\"nofollow\">persistent connections</a> or connection pools.</li>\n<li>Small typo in your screenshot and your code, you meant 'Performance', not 'Preformance'.</li>\n<li>You should use docstrings instead of comments to document your functions. You can also look at PEP 8 to see how Python code is generally formatted.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T16:33:15.480",
"Id": "74083",
"Score": "0",
"body": "I'll take a look at docstrings (I'm new to python). Any examples on how to handle all static routes in one method? Would it be like, def incoming_request(url_string)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T21:57:22.910",
"Id": "74141",
"Score": "0",
"body": "Didn't notice the `root` parameter, sorry. Probably not a great advice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T09:14:16.440",
"Id": "42945",
"ParentId": "42165",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "42945",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:37:56.910",
"Id": "42165",
"Score": "5",
"Tags": [
"python",
"mongodb"
],
"Title": "MongoDB inventory system"
}
|
42165
|
<p>I'm using mongoose to seed a mongodb database based on my mongoose models.
I'm particular interested in improving the seed code.</p>
<p>I have two models, an article and a category.
The relationship between the models are as follows:</p>
<p>A category has many articles
An article has a parent category</p>
<p>The model schemas I'm using are listed below:</p>
<p>The category schema</p>
<pre><code>var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
title: String,
articles : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }]
});
mongoose.model('Category', categorySchema);
</code></pre>
<p>The article schema</p>
<pre><code>var mongoose = require('mongoose');
var articleSchema = mongoose.Schema({
category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
title: String
});
mongoose.model('Article', articleSchema);
</code></pre>
<p>I'm using the following code to seed:</p>
<p>Seeding the category </p>
<pre><code>var CategoryModel = require('mongoose').model('Category');
exports.seedCategories = function seedCategories() {
CategoryModel.find({}).exec(function (err, collection) {
if (collection.length === 0) {
CategoryModel.create({ title: 'Category One' });
CategoryModel.create({ title: 'Category Two' });
}
});
}
</code></pre>
<p>Seeding the article</p>
<pre><code>var CategoryModel = require('mongoose').model('Category');
var ArticleModel = require('mongoose').model('Article');
exports.seedArticles = function seedArticles() {
ArticleModel.find({}).exec(function (err, collection) {
if (collection.length === 0) {
seedArticle('Category One', 'Article One');
seedArticle('Category One', 'Article Two');
seedArticle('Category Two', 'Article Three');
seedArticle('Category Two', 'Article Four');
}
});
function seedArticle(categoryTitle, articleTitle) {
var parentCategory;
CategoryModel.findOne({ title: categoryTitle }).exec()
.then(function (category) {
parentCategory = category;
return ArticleModel.create({ title: articleTitle, _category: parentCategory._id });
}).then(function (article) {
parentCategory.articles.push(article._id);
parentCategory.save(function (saveError) {
if (!saveError) {
console.log("Seeded article");
} else {
console.log(saveError);
}
});
});
}
}
</code></pre>
<p>I'm particularly interested in methods for preventing the Christmas tree of doom, and removing the obstruent error handling. Any recommendations are welcome, and thanks in advance for the help. I hope this code helps others.</p>
<p>Mongoose have just implemented promises returned from saves, so that should help. It will be available in mongoose 3.10.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T13:29:33.293",
"Id": "446329",
"Score": "0",
"body": "Why are you assigning the value `parentCategory._id` of the article to the field `_category`?\n\nThe schema defines it as `category`. Am I misunderstanding something?"
}
] |
[
{
"body": "<p>It seems that you are storing the data with double links (article -> category AND category -> articles).</p>\n\n<p>I assume that you need to report on articles for a category. I would simple create an index on <code>Category</code> like this: </p>\n\n<pre><code>var articleSchema = mongoose.Schema({\n category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', index: true },\n title: String\n});\n</code></pre>\n\n<p>This way you can simplify your code a ton by keeping it <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">KISS</a>:</p>\n\n<pre><code>function seedArticle(categoryTitle, articleTitle) {\n CategoryModel.findOne({ title: categoryTitle }).exec()\n .then(function (category) {\n return ArticleModel.create({ title: articleTitle, category: category._id });\n });\n}\n</code></pre>\n\n<p>Other than that, I like your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:02:11.523",
"Id": "72673",
"Score": "0",
"body": "Thanks for your input. My reason for maintaining both links is the ability to use mongoose populate from the parent. But your suggestion is appealing as the code is tidier. Any other recommendations or pointers on how to achieve this are most welcome. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-16T13:28:20.020",
"Id": "157267",
"Score": "0",
"body": "what is the name and where is the file stored,? I am asking this regarding the second code snippet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-24T15:48:07.490",
"Id": "193411",
"Score": "0",
"body": "I too would like to know where/in which file is this code stored so node executes it and takes advantage of the mongoose schemas that are already in the models folder."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:36:21.870",
"Id": "42176",
"ParentId": "42171",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42176",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:01:24.177",
"Id": "42171",
"Score": "12",
"Tags": [
"javascript",
"node.js",
"mongodb",
"mongoose"
],
"Title": "Seeding MongoDB using Mongoose models"
}
|
42171
|
<p>The following code will be used for educational purposes. It is to simply demonstrate how to apply a drop-shadow using a CSS3 filter. Any feedback on areas where I have not used best practices would be great.</p>
<p><a href="http://jsbin.com/sibizudo/1" rel="nofollow">JSBin</a></p>
<p><strong>HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
<head>
<title>Drop Shadow</title>
<link rel="stylesheet" type="text/css" href="drop-shadow.css">
</head>
<body>
<!-- Introduction to the text shadow property -->
<div class="container one">
<img width="250" height="250" src="http://iancottam.co.uk/img/footy.png">
</div>
<div class="container two">
<img width="250" height="250" src="http://iancottam.co.uk/img/footy.png">
</div>
<!-- Support Info: http://caniuse.com/css-filters -->
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre class="lang-css prettyprint-override"><code> body{
background: #ccc;
margin: 0;
}
h1{
font-size: 5em;
font-family: Georgia;
}
.container{
padding: 20px 50px;
}
.one img{
-webkit-filter: drop-shadow(0 0 30px black);
}
.two{
background: black;
}
.two img{
-webkit-filter: drop-shadow(-15px 0px 20px white);
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code it's perfectly fine</p>\n\n<p>I would just change, to stress the fact that the images are the same:</p>\n\n<pre><code>.container img {\n width: 250px;\n height: 250px;\n content: url(\"http://iancottam.co.uk/img/footy.png\");\n}\n</code></pre>\n\n<p>and then </p>\n\n<pre><code><div class=\"container one\">\n <img>\n</div>\n<div class=\"container two\">\n <img>\n</div>\n</code></pre>\n\n<p><a href=\"http://jsbin.com/sibizudo/2/\" rel=\"nofollow\">jsbin</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:03:22.600",
"Id": "72626",
"Score": "0",
"body": "CSS backgrounds aren't semantically the same as `<img>` tags. For example, some browsers will ignore CSS backgrounds when printing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:06:44.230",
"Id": "72628",
"Score": "0",
"body": "@200_success: It's true that CSS backgrounds aren't the same than img; but I am not using CSS backgrounds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:34:48.507",
"Id": "72639",
"Score": "0",
"body": "Sorry, I stand corrected. I had read it carelessly since I wasn't familiar with this [feature of CSS 3](http://stackoverflow.com/q/11173991/1157100)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:38:23.183",
"Id": "72641",
"Score": "0",
"body": "Never mind :-) !!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:58:52.170",
"Id": "72648",
"Score": "0",
"body": "There's no real benefit to this suggestion, it's just change for the sake of change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T06:28:31.257",
"Id": "72704",
"Score": "0",
"body": "@cimmanon I mostly agree with you, there isn't much benefit in my answer. I admited that already ! It's only, for demonstration purposes, to make clearer that the images are the same, and that the difference comes from the filter."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:52:28.863",
"Id": "42183",
"ParentId": "42173",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:08:52.203",
"Id": "42173",
"Score": "5",
"Tags": [
"html",
"css"
],
"Title": "Use of filter and drop shadow"
}
|
42173
|
<p><strong>Getting Additional Help</strong></p>
<p>You may also subscribe to the <a href="http://groups.google.com/group/mongoose-orm" rel="nofollow">Google group</a>.</p>
<p>For examples and documentation visit: <a href="http://mongoosejs.com" rel="nofollow">http://mongoosejs.com</a></p>
<p>To open a bug or feature request, visit: <a href="https://github.com/learnboost/mongoose/issues/new" rel="nofollow">https://github.com/learnboost/mongoose/issues/new</a></p>
<p><a href="http://docs.mongodb.org/manual/reference/sql-comparison/" rel="nofollow">SQL to MongoDB Mapping Chart</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:21:03.060",
"Id": "42174",
"Score": "0",
"Tags": null,
"Title": null
}
|
42174
|
Mongoose is a MongoDB object modeling tool, written in JavaScript, designed to work in an asynchronous environment.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:21:03.060",
"Id": "42175",
"Score": "0",
"Tags": null,
"Title": null
}
|
42175
|
<p>I have fully functional code in class format, and as far as I am aware from my previous question, it conforms to PEP 8 and the code logic and implementation is suitably pythonic. My main concerns here is whether or not I have put <code>self.</code> in front of the correct variables, and some ambiguity surrounding my <code>@staticmethod</code>.</p>
<ol>
<li>Should I leave it as it is?</li>
<li>Should I change the logic so it is not static?</li>
<li>Should it be in the class at all?</li>
</ol>
<p></p>
<pre><code># This imports some necessary libraries.
import webbrowser
import tempfile
import urllib.request
from tkinter import *
class Browser:
"""This creates a relay that allows a user to directly view data sent from a web server."""
def __init__(self, master):
"""Sets up a browsing session."""
# Explicit global declarations are used to allow certain variable to be used in all methods.
global e1
# Here we create some temporary settings that allow us to create a client that ignores proxy settings.
self.proxy_handler = urllib.request.ProxyHandler(proxies=None)
self.opener = urllib.request.build_opener(self.proxy_handler)
# This sets up components for the GUI.
Label(master, text='Full Path').grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
Button(master, text='Go', command=self.browse).grid(row=0, column=2)
# This binds the return key to self.browse as an alternative to clicking the button.
root.bind('<Return>', self.browse)
@staticmethod
def parsed(data):
"""Cleans up the data so the file can be easily processed by the browser."""
# This removes removes all python-added special characters such as b'' and '\\n' to create understandable HTML.
initial = str(data)[2:-1]
lines = initial.split('\\n')
return lines
def navigate(self, query):
"""Gets raw data from the queried server, ready to be processed."""
# This gets the opener to query our request, and submit the response to be parsed.
response = self.opener.open(query)
html = response.read()
return html
def browse(self):
"""Wraps all functionality together for data reading and writing."""
# This inputs and outputs the necessary website data from user-specified parameters.
raw_data = self.navigate(e1.get())
clean_data = self.parsed(raw_data)
# This creates a temporary file in which we store our HTML data, and open it in the default browser.
with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as cache:
cache.writelines(line.encode('UTF-8') for line in clean_data)
webbrowser.open_new_tab(cache.name)
# Creates a Tk() window that is always in front of all other windows.
root = Tk()
root.wm_attributes('-topmost', 1)
# Starts the program by initializing the Browser object and main-looping the Tk() window.
anon = Browser(root)
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:43:56.697",
"Id": "72621",
"Score": "2",
"body": "\"Explicit global declarations are used to allow certain variable to be used in multiple methods.\" Huh? Instance attributes, eg. `self.e1` can be used in all methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:19:28.000",
"Id": "72634",
"Score": "0",
"body": "This code is not actually PEP8-compliant: it has [long lines](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) that mean we have to scroll horizontally to read it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:22:34.873",
"Id": "72635",
"Score": "0",
"body": "@Gareth Rees PEP 8 says a maximum of 79 characters. My code fulfils that condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:30:53.540",
"Id": "72638",
"Score": "1",
"body": "@anongeneric: How are you counting? I find that line 31 has 119 characters, for example. (If you can get it within the PEP8 limits, you'll find that there's no need to scroll it here.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:37:28.900",
"Id": "72640",
"Score": "0",
"body": "@Gareth Rees ok you're right, so there's that. Pycharm was using 120 as the limit for some reason.What about the actual concerns I mentioned?"
}
] |
[
{
"body": "<h2>Class Scoping</h2>\n\n<p>So your comment afore your global declaration of <code>e1</code> mentions how you wish for <code>e1</code> to be accessible in all methods. If you want a variable to be accessible in all methods of a class, the conventional way is to assign it as a property of <code>self</code>:</p>\n\n<pre><code>class Foo():\n def __init__(self, bar):\n self.boz = bar * 3\n\n def baz(self):\n # boz is now accessible here\n print(self.boz)\n</code></pre>\n\n<p>Note that <code>boz</code> is not a global; if I create two <code>Foo()</code> objects, I'll end up with 2 different <code>boz</code> variables:</p>\n\n<pre><code>>>> f1 = Foo(3)\n>>> f1.boz\n9\n>>> f2 = Foo(2)\n>>> f2.boz\n6\n>>> f1.boz\n9 # Still\n</code></pre>\n\n<h2>Static Methods</h2>\n\n<p>To answer your (most conceptual) questions about the static method:</p>\n\n<ol>\n<li>Potentially</li>\n<li>The function takes some data, and then performs an operation on it. It does not rely on any other state to decide what operation to perform, so it is a perfect candidate for being static.</li>\n<li>No, it does not need to be static; a static method is (conceptually) a function in all but name, so you could write it as a function. The main reasons to have something be a static variable is usually organizational or conceptual, so if you think that applies here, keep it as a <code>staticmethod</code>. Otherwise, consider making it a bog standard function.</li>\n</ol>\n\n<p>There is no definite rule for when to write a function and when to write a static method; it's something you learn over time. The two questions I ask myself when deciding to write a static method are \"Could I write this as a function?\" and \"Is this code very tightly linked (conceptually) to the class?\". If the answer to both of those questions is yes, then I might write it as a static method.</p>\n\n<p>In this case, I think a function might be more useful.</p>\n\n<h2>General bugs</h2>\n\n<p>Just some little things I noticed:</p>\n\n<ul>\n<li>Your <code>parsed</code> static method says that it removes cruft from a string, but it never checks to see if the characters it expects to be there actually exist. Personally, I would use a regexp to implement this function, but regardless, it might be wise to check that the characters you are deleting are the ones you expect to be there.</li>\n<li>In <code>__init__</code> you do <code>root.bind(...)</code>, where you could do <code>master.bind(...)</code>, which might be better, as it would avoid using a global variable.</li>\n<li>I'd recommend using a new style class by replacing <code>class Browser:</code> with <code>class Browser(object):</code>. The benefits of the syntax difference are subtle, but noticeable (and it helps with forward compatibility iirc).</li>\n<li>It might be a better idea to define a <code>main</code> function, and then call that instead of just doing loads of stuff in the global scope. You could also add a guard case of the form <code>if __name__ == \"__main__\": main()</code> to allow you to import the script into a REPL without running the code.</li>\n<li>Some of your variable names kinda suck. Try and find more descriptive names than <code>e1</code>!</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:52:35.337",
"Id": "72720",
"Score": "0",
"body": "so would the `main()` function just go around the stuff after the class is finished? And what is a regexp and how would I implement it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:46:40.017",
"Id": "72725",
"Score": "0",
"body": "So you'd have something like [this](https://gist.github.com/bluepeppers/eb817e11e75bd9f67666) for your main. A regexp is short for a regular expression, an incredibly powerful string parsing/extraction DSL (domain specific language). The Python docs have a [tutorial](http://docs.python.org/2/howto/regex.html) on them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:52:15.893",
"Id": "42242",
"ParentId": "42177",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "42242",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:56:53.930",
"Id": "42177",
"Score": "6",
"Tags": [
"python",
"object-oriented",
"classes",
"static",
"tkinter"
],
"Title": "Does this tkinter-based web browser widget use a well implemented class?"
}
|
42177
|
<p>I've got an assignment to do pure JS validation as well as submit with AJAX. Here is the code I've got so far. I'm wondering if I can do away with the whole "reason" bit. That was because it was originally meant to display a list of all the errors, but I've tweaked the code to instead display the errors right by the field.</p>
<p>Basically I want to call up the <code>validateFormOnSubmit</code> and just have it go through all the if statements instead of all the separate functions, then if it all passes execute <code>submitFormAjax</code>.</p>
<p>The AJAX is currently not working but don't want to troubleshoot that until I've cleaned up the JS code.</p>
<p><a href="http://jsfiddle.net/justinae/Ehg36/">JSfiddle</a></p>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="GET">
<div>
<label>First Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<div>
<label>Nickname</label>
<input placeholder="Nickname" type="text" name="nickname" id="nickname" tabindex="2" autofocus />
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error" class="error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
<div id="phone-error" class="error"></div>
</div>
<div>
<label>I prefer</label>
<input type="radio" name="pet" id="Dogs" tabindex="5" autofocus />Dogs
<input type="radio" name="pet" id="Cats" tabindex="6" autofocus />Cats
<input type="radio" name="pet" id="Neither" tabindex="7" autofocus />Neither
<div id="pet-error" class="error"></div>
</div>
<div>
<label>My favorite number between 1 and 50</label>
<input placeholder="Favorite number between 1 and 50" type="text" name="number" id="number" tabindex="8" autofocus />
<div id="number-error" class="error"></div>
</div>
<div>
<label>Disclaimer</label>
<input type="checkbox" name="disclaimer" id="disclaimer" tabindex="9" autofocus />I confirm that all the above information is true.
<div id="disclaimer-error" class="error"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="10">Send</button>
</div>
</form>
</code></pre>
<p><strong>JS</strong></p>
<pre class="lang-javascript prettyprint-override"><code>function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validatePet(contact.pet);
reason += validateNumber(contact.number);
reason += validateDisclaimer(contact.disclaimer);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
// Show some loading image and submit form
submitFormAjax();
}
}
// validate required fields
function validateName(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Red';
document.getElementById('name-error').innerHTML = "The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML = '';
}
return error;
}
// validate email as required field and format
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter an email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Red';
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML = '';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Red';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Red';
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Red';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
function validatePet(pet) {
if ((contact.pet[0].checked == false) && (contact.pet[1].checked == false) && (contact.pet[2].checked == false)) {
document.getElementById('pet-error').innerHTML = "Pet required";
var error = "2";
} else {
document.getElementById('pet-error').innerHTML = '';
}
return error;
}
function validateNumber(number) {
var num = document.forms["contact"]["number"];
var y = num.value;
if (!isNaN(y)) {
//alert('va');
if (y < 0 || y > 50) {
//Wrong
number.style.background = 'Red';
document.getElementById("number-error").innerHTML = "Must be between 0 and 50.";
var error = "10";
} else {
//Correct
number.style.background = 'White';
document.getElementById("number-error").innerHTML = "";
}
return error;
} else {
document.getElementById("number-error").innerHTML = "Must be a number.";
var error = "3";
}
return error;
}
function validateDisclaimer(disclaimer) {
var error = "";
if (document.getElementById("disclaimer").checked === false) {
document.getElementById('disclaimer-error').innerHTML = "Required";
var error = "4";
} else {
document.getElementById('disclaimer-error').innerHTML = '';
}
return error;
}
function submitFormAjax() {
var xmlhttp= window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert("Test Ready State"); // Here is the response
}
var name = document.getElementById('name').innerHTML;
var nickname = document.getElementById('nickname').innerHTML;
var email = document.getElementById('email').innerHTML;
var phone = document.getElementById('phone').innerHTML;
var pet = document.getElementById('pet').innerHTML;
var number = document.getElementById('number').innerHTML;
var disclaimer = document.getElementById('disclaimer').innerHTML;
xmlhttp.open("GET","form.php?name=" + name + "&nickname" + nickname + "&email=" + email, + "&phone" + phone + "&pet" + pet + "&number" + number + "&disclaimer" + disclaimer, true);
xmlhttp.send();
}
</code></pre>
<p><strong>PHP</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
$name = $_GET['name'];
$nickname = $_GET['nickname'];
$email = $_GET['email'];
$phone = $_GET['phone'];
$pet = $_GET['pet'];
$number = $_GET['number'];
$disclaimer = $_GET['disclaimer'];
$from = 'From: Test From';
$to = 'euteneier@gmail.com';
$subject = 'Hello';
$message = "This is a message.";
if ($_GET['submit']) {
if (mail ($to, $subject, $message)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:15:19.850",
"Id": "72632",
"Score": "1",
"body": "If you put 0 in the number field, it does not validate. The if statement says \"y < 0 || y > 50\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:42:36.710",
"Id": "72642",
"Score": "0",
"body": "Good catch @GonzaloNaveira. Thanks. I upvoted the comment."
}
] |
[
{
"body": "<p>If you don't have a strong reason for using the <code>onsubmit</code> attribute on your <code><form></code> element, I would suggest attaching the submit action to the form without it. This would work:</p>\n\n<pre><code>document.getElementById('contact').onsubmit(function () { return validateFormOnSubmit(this); });\n</code></pre>\n\n<p>Other than that, it might not be a good idea to send the user's email in plain text. You can have an AJAX request use the <code>POST</code> method as well as <code>GET</code>, which would improve (slightly) the security of personal information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:00:19.043",
"Id": "72671",
"Score": "0",
"body": "This doesn't look right, I think you missed an anonymous function there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:12:51.843",
"Id": "72678",
"Score": "0",
"body": "Whoops! Good catch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:46:44.087",
"Id": "42190",
"ParentId": "42182",
"Score": "2"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>You are repeating <code>.style.background = 'Red';</code> and <code>.style.background = 'White';</code> a ton, what if suddenly all these fields also have to get bold. I would suggest a function like <code>highlightField</code> that does the setting of the style:<br></p>\n\n<pre><code>function setHighlight( element , isHighlighted )\n{\n element.style.background = isHighlighted ? 'Red' : 'White';\n}\n</code></pre></li>\n<li>The reason being a number is silly, since you do not do anything with the number, I would simply return booleans and AND these booleans.</li>\n<li>It is considered a better style to have one single <code>var</code> statements, with comma separated variables.</li>\n<li><p>Then, you could change this:</p>\n\n<pre><code>function validateEmail(email) {\n var error = \"\";\n var temail = trim(email.value); // value of field with whitespace trimmed off\n var emailFilter = /^[^@]+@[^@.]+\\.[^@]*\\w\\w$/;\n var illegalChars = /[\\(\\)\\<\\>\\,\\;\\:\\\\\\\"\\[\\]]/;\n\n if (email.value == \"\") {\n email.style.background = 'Red';\n document.getElementById('email-error').innerHTML = \"Please enter an email address.\";\n var error = \"2\";\n } else if (!emailFilter.test(temail)) { //test email for illegal characters\n email.style.background = 'Red';\n document.getElementById('email-error').innerHTML = \"Please enter a valid email address.\";\n var error = \"3\";\n } else if (email.value.match(illegalChars)) {\n email.style.background = 'Red';\n var error = \"4\";\n document.getElementById('email-error').innerHTML = \"Email contains invalid characters.\";\n } else {\n email.style.background = 'White';\n document.getElementById('email-error').innerHTML = '';\n }\n return error;\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>function validateEmail(email) {\n var emailFilter = /^[^@]+@[^@.]+\\.[^@]*\\w\\w$/,\n illegalChars = /[\\(\\)\\<\\>\\,\\;\\:\\\\\\\"\\[\\]]/,\n errorMessage = '',\n isValid;\n\n //Do we have an error ?\n if (email.value == \"\") {\n errorMessage = \"Please enter an email address.\";\n } else if (!emailFilter.test(trim(email.value))) { //test for illegal chars\n errorMessage = \"Please enter a valid email address.\";\n } else if (email.value.match(illegalChars)) {\n errorMessage = \"Email contains invalid characters.\";\n }\n\n document.getElementById('email-error').innerHTML = errorMessage;\n isValid = !errorMessage.length;\n setHighlight( email , !isValid );\n return isValid;\n}\n</code></pre>\n\n<p>You could do this for every validation rule.</p></li>\n<li>You must declare all your variables with <code>var</code> so that you do not pollute the global namespace ( I am looking at you, <code>reason = \"\"</code> )</li>\n<li><p>If all validation functions will return a boolean, than you could rename <code>reason</code> to <code>isValid</code>:<br></p>\n\n<pre><code>var isValid = validateName(contact.name) &&\n validateEmail(contact.email) &&\n validatePhone(contact.phone) &&\n validatePet(contact.pet) &&\n validateNumber(contact.number) &&\n validateDisclaimer(contact.disclaimer);\n</code></pre>\n\n<p>obviously the <code>&&</code> does not have to be aligned, but it makes my heart beat faster :)</p></li>\n<li>There would still be the concern that the name <code>validateXxx</code> lies a little because it also returns a boolean, but since it also updates the UI and does the validation it would be hard to name this correctly without having a really long name.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:01:29.023",
"Id": "72672",
"Score": "0",
"body": "so basically the email functions returns \"false\" if any of those conditions are met. Where is it returning \"true\" or valid?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:07:50.980",
"Id": "72676",
"Score": "0",
"body": "`||` is a [short-circuit operator](http://en.wikipedia.org/wiki/Short-circuit_evaluation). If the name is false then it will check the email, if false, then the phone, if false, then the pet, etc..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:57:09.630",
"Id": "72749",
"Score": "0",
"body": "@elclanrs Actually I needed more coffee when I wrote that, it should be `&&` since validateXxx returns `true` if the value is valid. Fixed it now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:31:08.733",
"Id": "42193",
"ParentId": "42182",
"Score": "4"
}
},
{
"body": "<p>For your JS email validation, I'd consider taking a look at <a href=\"https://stackoverflow.com/a/46181/3234482\">this regular expression</a>.</p>\n\n<p>Also, I'd make sure you have a bit more security on that GET to form.php. That looks like an invitation for spammers!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:59:29.233",
"Id": "42257",
"ParentId": "42182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:26:06.547",
"Id": "42182",
"Score": "6",
"Tags": [
"javascript",
"php",
"beginner",
"form",
"validation"
],
"Title": "JS validation and submission with AJAX"
}
|
42182
|
<p>I have a class Employee that contains an ArrayList of Projects.</p>
<p>I'm storing the Employees in one table, and the Projects in another.</p>
<p>I'm trying to find the best way to create an ArrayList of Employee objects based on a result set. Simply creating an ArrayList of Employees based on a result set is pretty straightforward, but I'm finding that filling an ArrayList of Employees that each contains an ArrayList of Projects isn't so simple.</p>
<p>Right now, my getEmployees() function is using two nested SQL queries to accomplish this, something like this:</p>
<pre><code>public ArrayList<Employee> getEmployees()
{
PreparedStatement ps1 = null;
ResultSet rs1 = null;
PreparedStatement ps2 = null;
ResultSet rs2 = null;
ArrayList<Employee> employees = new ArrayList<Employee>();
String query1 = "SELECT * FROM employees "
+ "ORDER BY employee_id ASC";
try
{
ps1 = conn.prepareStatement(query1);
rs1 = ps1.executeQuery();
while (rs1.next())
{
Employee employee = new Employee();
int employeeID = rs1.getInt("employee_id");
employee.setEmployeeID(employeeID);
employee.setName(rs1.getString("employee_name"));
// Get projects for this employee
ArrayList<Project> projects = new ArrayList<Project>();
String query2 = "SELECT * FROM projects "
+ "WHERE employee_id = ?";
ps2 = conn.prepareStatement(query2);
ps2.setInt(1, employeeID);
rs2 = ps2.executeQuery();
while (rs2.next())
{
Project project = new Project();
project.setProjectID(rs2.getInt("project_id"));
project.setName(rs2.getInt("project_name"));
projects.add(project);
}
employee.setProjects(projects);
employees.add(employee);
}
return employees;
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
// close result sets and prepared statements
}
catch (SQLException e)
{
e.printStackTrace();
}
}
return null;
}
</code></pre>
<p>The above code works, but it seems messy to me. </p>
<p>Is there a way to do this without having to nest two separate SQL queries? I've tried using a LEFT JOIN to get a single result set back, but I was unable to figure out a way to use that single result set to fill the ArrayList of Employees, each containing an ArrayList of Projects.</p>
<p>EDIT: Assume the tables have the following structures:</p>
<p>employees table:</p>
<pre><code>employee_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT
employee_name varchar(60) NOT NULL
</code></pre>
<p>projects table:</p>
<pre><code>project_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT
employee_id int(11) NOT NULL
project_name varchar(60) NULL
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:22:51.660",
"Id": "72636",
"Score": "2",
"body": "Can you please give us the `DESCRIBE` of `employees` and `projects` table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:42:38.737",
"Id": "72643",
"Score": "1",
"body": "@tintinmj My database doesn't support the DESCRIBE statement, but I've done the best I can with the edit above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T05:51:08.857",
"Id": "72702",
"Score": "0",
"body": "Your problem is not so much that the code is messy, but that it is slow. Any time you execute a query repeatedly in a loop, you're likely to get a performance problem."
}
] |
[
{
"body": "<p>A standard way to do this is through break-processing, where you track one value, and when it changes, you do something special.... but you may find it easier to do a more unstructured system:</p>\n\n<pre><code>Map<Integer, List<Project>> employeeProjects = new HashMap<>();\nMap<Integer, Employee> employees = new TreeMap<>(); // Treeset ... sorted by employeeID\n\n// join the tables.\nString select = \" select e.employee_id, e.employee_name, p.project_id, p.project_name \"\n + \" from employees e\n left outer join projects p on e.employee_id = p.employee_id\"\n + \" order by e.employee_id, p.project_name\";\n\n// do the select.....\n\nwhile (rs.next()) {\n Integer employeeID = rs.get(\"employee_id\");\n Employee emp = employees.get(employeeID);\n if (emp == null) {\n emp = new Employee();\n emp.setName(rs.get(\"employee_name\");\n emp.setEmployeeID(employeeID);\n employees.put(employeeID, emp);\n // create a new list for this employee\n employeeProject.put(employeeID, new ArrayList<Project>());\n }\n\n String projectName = rs.getString(\"project_name\");\n\n if (!rs.wasNull()) {\n List<Project> projects = employeeProject.get(employeeID);\n Project proj = new Project();\n proj.setID(rs.getInt(\"project_id\"));\n proj.setName(projectName);\n projects.add(proj);\n }\n\n}\nrs.close();\n</code></pre>\n\n<p>Then, once you have the data structured the way you want, you can:</p>\n\n<pre><code>List<Employee> result = new ArrayList<>();\nfor (Employee emp : employees.values()) {\n emp.setProjects(employeeProjects.get(emp.getEmployeeID());\n result.add(emp);\n}\nreturn result;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:56:37.797",
"Id": "72646",
"Score": "0",
"body": "That's an amazing answer. I never would have thought of that on my own!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:43:03.300",
"Id": "42189",
"ParentId": "42185",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "42189",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:08:47.663",
"Id": "42185",
"Score": "6",
"Tags": [
"java",
"sql"
],
"Title": "How to fill an ArrayList of ArrayLists with a Left Join?"
}
|
42185
|
<p>Here is a simple function I wrote to parse record-jar data. I need it in a php5.3 application to validate bcp47 language tags. It converts the <a href="http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry" rel="nofollow">language subtag registry</a> among other things, into a nested php array. Any suggestions on how I can improve it?</p>
<pre><code>/**
* Quick script to parse any record-jar data into an array.
*
* In particular, this is of use to someone trying to validate bcp47 language codes.
* @see http://tools.ietf.org/search/bcp47#section-3.1.1
*/
function parse_record_jar($record_jar_string) {
$records = array();
$record = array();
foreach(explode('%%', $record_jar_string) as $recordstr) {
array_splice($record, null); // truncate $record
foreach(array_filter(explode("\n", $recordstr)) as $line) {
$parts = array_map('trim', explode(":", $line, 2));
if (count($parts) === 2) {
list($key, $value) = $parts;
} else {
// $key retains its value from the previous iteration.
$value = $parts[0];
}
if (!isset($record[$key])) {
$record[$key] = '';
}
$record[$key] .= $value;
}
$records[] = $record;
}
return $records;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:24:30.227",
"Id": "72651",
"Score": "0",
"body": "Could you supply a snippet of the source feed to the function. The code has a high cyclomatic complexity, which you might consider splitting up. Tests would be a good idea to ensure everything works"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:51:39.843",
"Id": "72653",
"Score": "0",
"body": "@RonniSkansing updated with link"
}
] |
[
{
"body": "<p>I'm no PHP expert, and this might be personal preference, but I like to initialize variables at the top of the function to make it clear that their scope is not limited to the constructs in which they're defined.</p>\n\n<pre><code>function parse_record_jar($record_jar_string) {\n $records = array();\n $record = array();\n $recordstr;\n $line;\n $parts;\n $key;\n $value;\n foreach(explode('%%', $record_jar_string) as $recordstr) {\n array_splice($record, null); // truncate $record\n foreach(array_filter(explode(\"\\n\", $recordstr)) as $line) {\n $parts = array_map('trim', explode(\":\", $line, 2));\n if (count($parts) === 2) {\n list($key, $value) = $parts;\n } else {\n // $key retains its value from the previous iteration.\n $value = $parts[0];\n }\n if (!isset($record[$key])) {\n $record[$key] = '';\n }\n $record[$key] .= $value;\n }\n $records[] = $record;\n }\n return $records;\n}\n</code></pre>\n\n<p>Other than that I'm having a hard time finding a way to improve the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T02:11:58.937",
"Id": "72688",
"Score": "1",
"body": "In dynamic languages such as Java and PHP it is often prefered to keep the variables alive for the shortest time possible and push them as far into the scope as possible. Some would argue for performence (Only in extreme cases). I think this answer hits it pretty well http://stackoverflow.com/a/10205934/924016 but in the end it is a preference."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:36:51.657",
"Id": "42187",
"ParentId": "42186",
"Score": "3"
}
},
{
"body": "<p>I have rewritten the script in another fashion. Beware all your code is almost exactly the same, but not entirely. If you are looking to just improve your script a bit, look closely at the parser.</p>\n\n<p>A number of personal preferences I would like to share that I thought while reading your code but which I did not fix in my own code in all cases:</p>\n\n<ul>\n<li><p>I like (foo === false) better then (! foo) or (foo !== true).</p></li>\n<li><p>Strings like '%%' should be replaced with constants, preferably some of the numbers also.</p></li>\n<li><p>Complex logic should be split up. Even my example does fully split up the responsibilities. </p></li>\n<li><p>Comments should be plentiful (and meaningful!).</p></li>\n</ul>\n\n<p>The code example is obese compared to the fine script you made. But I find it</p>\n\n<ul>\n<li>Faster to debug</li>\n<li>Testable</li>\n<li>Easy to replace dependencies</li>\n<li>Easy to change how the converter works (just write a couple parsers and converters)</li>\n</ul>\n\n<p>My code example is far from done. The code should strive towards SOLID principles (which this does not). The main issue I've addressed is to clarify some of the mixed responsibilities in your code. But the new code still has some issues, mainly missing tests and SRP violations (in my code the parser is doing the converter's job). This is to show the disadvantage of bundled complex code that handles too many responsibilities.</p>\n\n<p>I used 5.4 array syntax. PHP 5.3 series will enter an end of life cycle and has only received critical fixes as of March 2013.</p>\n\n<p>As mentioned the code is undone (as in breaks SOLID). If you want to further improve it, you could start by moving the converting part (toArray) of the algorithm into the ToArray class.</p>\n\n<pre><code>namespace jarrecord;\n\nInterface Parser {\n public function parse($parsable);\n}\n\nInterface Converter {\n public function convert($convertable);\n}\n\nclass StringParser implements Parser {\n const RECORD_SPLIT_TOKEN = '%%';\n const KEY_VALUE_SPLIT = ':';\n /**\n * Splits and trims unparsed lines and returns array with key value pair.\n *\n * @return array\n */\n private function splitUnparsedLineToKeyAndValue($line) \n {\n return array_map('trim', explode(self::KEY_VALUE_SPLIT, $line, 2));\n }\n\n private function splitToUnparsedRecords($recordJar)\n {\n return explode(self::RECORD_SPLIT_TOKEN, $recordJar);\n }\n\n private function splitToUnparsedLines($unparsedRecord)\n {\n $lines = explode(\\PHP_EOL, $unparsedRecord);\n // filter to remove null lines\n\n return array_filter($lines);\n }\n\n /**\n * Takes a array of strings and returns a record-like array\n * @param string $unparsedLines\n * @return array\n */\n private function unparsedLinesToRecord($lines)\n {\n $record = [];\n foreach($lines as $line)\n {\n $partialRecord = $this->splitUnparsedLineToKeyAndValue($line);\n if(count($partialRecord) === 2)\n {\n list($key, $value) = $partialRecord; \n }\n else\n {\n // $key retains its value from the previous iteration.\n $value = $partialRecord[0];\n }\n if(isset($record[$key]) === false)\n {\n $record[$key] = '';\n }\n $record[$key] .= $value;\n }\n\n return $record;\n }\n\n public function parse($parsable) \n {\n $unparsedRecords = $this->splitToUnparsedRecords($parsable);\n foreach($unparsedRecords as $unparsedRecord)\n {\n $unparsedLines = $this->splitToUnparsedLines($unparsedRecord);\n $record = $this->unparsedLinesToRecord($unparsedLines);\n $records[] = $record;\n }\n\n return $records;\n }\n}\n\nclass ToArray implements Converter {\n private $parser;\n\n /**\n * @param Parser $parser\n */\n public function __construct(Parser $parser)\n {\n $this->parser = $parser;\n }\n\n /**\n * Parses a Record-Jar string and returns it as a array.\n * @throws InvalidArgumentException\n * @param string $unparsedRecordJar\n * @return array\n */\n public function convert($unparsedRecordJar)\n {\n return $this->parser->parse($unparsedRecordJar);\n }\n}\n\n$parser = new StringParser();\n$Converter = new ToArray($parser);\n$array = $Converter->convert($source));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:04:40.863",
"Id": "72781",
"Score": "0",
"body": "I should have put this in my edit: beware that beware does not mean what you think it means (it means be *afraid*, as opposed to be *aware*)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:11:14.440",
"Id": "72786",
"Score": "0",
"body": "@davidkennedy85 thanks, I will try to remember that"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T01:08:20.153",
"Id": "42243",
"ParentId": "42186",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "42243",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:17:59.090",
"Id": "42186",
"Score": "4",
"Tags": [
"php",
"parsing",
"php5"
],
"Title": "Parsing record-jar format in PHP 5.3"
}
|
42186
|
<blockquote>
<p>SQL injection is a technique used to take advantage of non-validated
input vulnerabilities to pass SQL commands through a Web application
for execution by a backend database. Attackers take advantage of the
fact that programmers often chain together SQL commands with
user-provided parameters, and can therefore embed SQL commands inside
these parameters. The result is that the attacker can execute
arbitrary SQL queries and/or commands on the backend database server
through the Web application.</p>
</blockquote>
<p>Via <a href="https://security.stackexchange.com/tags/sql-injection/info">security.stackexchange.com</a></p>
<p>There is <a href="https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php">a community wiki on StackOverflow</a> which has some answers to the very common question, "How can I protect myself from SQL injection?" If your question involves PHP and SQL, make sure you have already read this to prevent unnecessary repetition.</p>
<p>An example SQL Injection could be:</p>
<pre><code>"; SELECT credit_cards FROM transactions; --
</code></pre>
<p>In which a normal query could transform into malicious code:</p>
<pre><code>SELECT username FROM users WHERE username = "$username";
</code></pre>
<p>into:</p>
<pre><code>SELECT username FROM users WHERE username = ""; SELECT credit_cards FROM transactions; --";
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:57:24.293",
"Id": "42198",
"Score": "0",
"Tags": null,
"Title": null
}
|
42198
|
SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:57:24.293",
"Id": "42199",
"Score": "0",
"Tags": null,
"Title": null
}
|
42199
|
<p>This is my solution for <a href="https://www.codeeval.com/browse/44/" rel="nofollow">CodeEval challenge 44</a>.</p>
<blockquote>
<p>You are writing out a list of numbers.Your list contains all numbers with exactly Di digits in its decimal representation which are equal to i, for each i between 1 and 9, inclusive. You are writing them out in ascending order. For example, you might be writing every number with two '1's and one '5'. Your list would begin 115, 151, 511, 1015, 1051. Given N, the last number you wrote, compute what the next number in the list will be. The number of 1s, 2s, ..., 9s is fixed but the number of 0s is arbitrary.</p>
<p><strong>INPUT SAMPLE:</strong></p>
<p>Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain an integer n < 10^6. E.g.</p>
<pre><code>115
842
8000
</code></pre>
<p><strong>OUTPUT SAMPLE:</strong></p>
<p>For each line of input, generate a line of output which is the next integer in the list. E.g.</p>
<pre><code>151
2048
80000
</code></pre>
</blockquote>
<p>The function <code>followingInteger</code> takes a number in its decimal representation and returns the next higher permutation of the digits of the number. If there isn't a larger permutation of the digits, a '0' may be added to the digits:</p>
<pre><code>ghci> followingInteger "123"
"132"
ghci> followingInteger "10"
"100"
</code></pre>
<p>The entire program can be used like this:</p>
<pre><code>./ch044_solution ch044_input
</code></pre>
<p>where ch044_input is a file containing one integer on each line.</p>
<p>The code:</p>
<pre><code>import Data.List (partition, sort)
import System.Environment (getArgs)
followingInteger :: String -> String
followingInteger digits
| isSortedDesc digits = lowestPermutation ('0' : digits)
| otherwise = nextHigherPermutation digits
isSortedDesc :: (Ord a) => [a] -> Bool
isSortedDesc xs = all (uncurry (>=)) $ zip xs (tail xs)
lowestPermutation :: String -> String
lowestPermutation digits = let (zeros, nonZeros) = partition (== '0') digits
(lowestNonZeroDigit:otherDigits) = sort nonZeros
in lowestNonZeroDigit : zeros ++ otherDigits
nextHigherPermutation :: String -> String
nextHigherPermutation = snd . foldr foldFun (False, "")
where foldFun d (True, digits) = (True, d:digits)
foldFun d (False, digits)
| null biggerDigits = (False, d:digits)
| otherwise = (True, newTail)
where (biggerDigits, smallerDigits) = partition (> d) digits
(swapDigit:otherDigits) = sort biggerDigits
newTail = swapDigit : sort smallerDigits ++ (d : otherDigits)
mapFileLines :: (String -> String) -> IO ()
mapFileLines f = do
(fileName:_) <- getArgs
contents <- readFile fileName
mapM_ (putStrLn . f) $ lines contents
main = mapFileLines followingInteger
</code></pre>
<p>I'm pretty new to Haskell, so please criticize my code in every way possible!</p>
<p>I'm especially interested in ways to make the code more readable!</p>
|
[] |
[
{
"body": "<p>First of all: your code is very readable and you seem to know your way around standard library functions, which is very important is Haskell. Good job!</p>\n\n<p>A couple of suggestions:</p>\n\n<ol>\n<li><p>A simpler isSortedDesc:</p>\n\n<pre><code>import Data.List.Ordered (isSortedBy)\n\nisSortedDesc :: (Ord a) => [a] -> Bool\nisSortedDesc = isSortedBy (>=)\n</code></pre>\n\n<p>Edit: Sorry, isSortedBy is not a standard function - it belongs to <a href=\"http://hackage.haskell.org/package/data-ordlist-0.2/docs/Data-List-Ordered.html\" rel=\"nofollow\">data-ordlist-0.2</a>. I'd implement it in a straightforward recursive manner:</p>\n\n<pre><code>isSortedDesc :: (Ord a) => [a] -> Bool\nisSortedDesc (x:y:xs') = x>=y && isSortedDesc (y:xs')\nisSortedDesc _ = True\n</code></pre></li>\n<li><p>foldFun:</p>\n\n<p>In foldFun, try to make the arguments more understandable. You can add a type signature, name the arguments or add a comment. For example, what is the purpose of the boolean argument?</p>\n\n<p>Another thing: nextHigherPermutation has two execution steps - find a digit we can swap, and then just copy the rest of the string. Personally I'm not a fun of the idea of passing extra information to fold (the boolean argument) and then discarding it. Instead, consider splitting it to two seperate functions - for example, one that finds the swap digit and another that performs the swap.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:31:14.603",
"Id": "76539",
"Score": "0",
"body": "Thanks for pointing me to data-ordlist, even if I can't use it on CodeEval! As I somehow prefer my version of `isSortedDesc` I'll try working on part 2 now. `foldFun` really is quite difficult to understand as is! I'll be back!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T17:25:14.513",
"Id": "44172",
"ParentId": "42200",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T21:16:00.160",
"Id": "42200",
"Score": "12",
"Tags": [
"beginner",
"haskell",
"programming-challenge"
],
"Title": "Finding the next higher digital permutation of a number"
}
|
42200
|
<p>I have written this small game for the "learn python the hard way" book. I ask for some opinions about it and how to improve it.</p>
<p>I know about pygame and others game engines but all the game runs in the terminal. The text file <code>orc.txt</code>, <code>cyclops.txt</code>, etc are ASCII drawings</p>
<pre><code>from PIL import Image
import numpy as np
import msvcrt
from time import sleep
from random import choice, randint
previous = 15 #start position tile
def createmap():
"""
The map is sketched in bmp, I make a array
to use it like a tileset
"""
global bmp
bmp = Image.open('sketch.bmp')
bmp_data = bmp.getdata()
bmp_array = np.array(bmp_data)
global map
map = bmp_array.reshape(bmp.size)
def array_to_text_map():
""" Tileset
# = Wall
. = sand
+ = door
e = enemy
D = dragon
$ = gold
@ = the player
numbers as due to the 16 color palette used
in the sketch
"""
text_map = open('map.txt', 'w')
for x in map:
for y in x:
if y == 0:
text_map.write('#')
elif y == 3:
text_map.write('.')
elif y == 8:
text_map.write('+')
elif y == 9:
text_map.write('e')
elif y == 10:
text_map.write('D')
elif y == 12:
text_map.write('$')
elif y == 13:
text_map.write('@')
elif y == 15:
text_map.write(' ')
text_map.write('\n')
text_map.close()
def print_text_map():
text_map = open('map.txt')
for x in range(bmp.size[1]):
print(text_map.readline(), end='')
def move_player_by_key():
wkey = msvcrt.getch
if wkey() == b"\xe0":
key2 = wkey()
if key2 == b"H":
move_in_matrix('up')
elif key2 == b"M":
move_in_matrix('right')
elif key2 == b"K":
move_in_matrix('left')
elif key2 == b"P":
move_in_matrix('down')
else:
exit()
def position():
ver = np.where(map == 13)[0][0]
hor = np.where(map == 13)[1][0]
return ver, hor
def move_in_matrix(direction):
ver, hor = position()
try:
if direction == 'up':
analize(ver-1 , hor)
elif direction == 'right':
analize(ver , hor+1)
elif direction == 'left':
analize(ver , hor-1)
elif direction == 'down':
analize(ver+1 , hor)
except IndexError:
console.append('Not that way')
def analize(verm, horm):
"""Take decision for each tile
verm and horm = next position
ver and hor = actual position
previous = keeps tile number for later
"""
global previous
ver, hor = position()
def restore(ver, hor, previous):
"""Restore color of the leaved tile"""
map[ver, hor] = previous
if map[verm, horm] == 0:
pass
elif map[verm, horm] == 3:
restore(ver, hor, previous)
previous = map[verm, horm]
map[verm, horm] = 13
elif map[verm, horm] == 8:
print('Open the door (yes/no)?', end='')
answer = input(' ')
if door(answer):
restore(verm, horm, 15)
console.append('The door was opened')
console.append(doors_dict[(verm, horm)]) #show the description
#attached to the door
elif map[verm, horm] == 9:
print('Do you want to fight against the monster (yes/no)?', end='')
answer = input(' ')
result = fight(answer)
if result and randint(0,1) == 1:
restore(verm, horm, 12)
elif result:
restore(verm, horm, 15)
elif map[verm, horm] == 10:
print('the beast seems asleep, you want to wake her?(yes/no)?', end='')
answer = input(' ')
result = fight(answer, dragon=True)
if result:
win()
elif map[verm, horm] == 12:
print("You want to grab the items in the floor (yes/no)?", end='')
if input(' ') == 'yes':
gold()
restore(verm, horm, 15)
elif map[verm, horm] == 15:
restore(ver, hor, previous)
previous = map[verm, horm]
map[verm, horm] = 13
def door(answer):
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
console.append('Invalid command')
def identify_doors():
"""Hardcode: Identify each door and zip() it with
a description stored previously
"""
doors_array = np.where(map == 8)
doors = zip(doors_array[0], doors_array[1])
dict_doors = {}
narrate = open('narrate.txt')
for x in doors:
dict_doors[x] = narrate.readline()
return dict_doors
def fight(answer, dragon=False):
if answer == 'yes':
if dragon == False:
monster = choice([Orc(), Goblin(), Cyclops()])
else:
monster = Dragon()
monster.show_appearance()
print('Fighting against', monster.name)
sleep(2)
while True:
monster.show_appearance()
print(monster.name, 'is attacking you', end = '')
answer = input('fight (1) or defend (2)? ')
if answer == '1':
player.defense = 1 + player.armor
monster.life = monster.life - player.damage
elif answer == '2':
player.defense = 1.5 + player.armor
else:
print('Invalid command')
continue
print(monster.name, 'counterattack!!')
player.life = player.life - (monster.damage / player.defense)
print(monster.life, 'remaining', monster.name, 'life')
print(player.life, 'remaining Player life')
if player.life <= 0:
print('The End')
exit()
if monster.life <= 0:
print('\n' * 5)
print('Enemy defeated')
print('You earn', monster.gold, 'gold coins')
player.gold += monster.gold
break
sleep(3)
return True
else:
return False
def moredamge(val):
player.damage += val
def morearmor(val):
player.armor += val
golds = {'Fire sword': (moredamge, 20),
'Oak shield': (morearmor, 0.1),
'Anhilation sword': (moredamge, 40),
'Iron shield': (morearmor, 0.2),
'Siege shield': (morearmor, 0.5)
}
def gold():
bunch = randint(10, 200)
print('You have found', bunch, 'gold coins')
player.gold += bunch
sleep(1)
print('Is there anything else?')
if randint(0, 10) > 7:
obtained = choice(list(golds))
print('You have get', obtained)
golds[obtained][0](golds[obtained][1]) #access to key: (function, quantity)
del golds[obtained]
else:
print('Oooohh.. nothing else')
sleep(2)
def win():
print('You have win the game')
print('You get', player.gold, 'gold coins!!')
exit()
class Orc():
def __init__(self):
self.name = 'Orc'
self.life = 100
self.damage = 10
self.defense = 1
self.gold = 100
self.appearance = open('orc.txt')
def show_appearance(self):
print(self.appearance.read())
class Player(Orc):
def __init__(self):
self.life = 1000
self.damage = 20
self.gold = 0
self.appearance = open('knight.txt')
self.armor = 0
class Goblin(Orc):
def __init__(self):
self.name = 'Goblin'
self.life = 50
self.damage = 10
self.gold = 50
self.appearance = open('goblin.txt')
class Dragon(Orc):
def __init__(self):
self.name = 'Dragon'
self.life = 400
self.damage = 40
self.gold = 2000
self.appearance = open('dragon.txt')
class Cyclops(Orc):
def __init__(self):
self.name = 'Cyclops'
self.life = 150
self.damage = 20
self.gold = 120
self.appearance = open('cyclops.txt')
def presentation():
print('\n'*2)
player.show_appearance()
print('Welcome hero, are you ready for fight?')
input()
if __name__ == "__main__":
player = Player()
presentation()
console = []
createmap()
array_to_text_map()
doors_dict = identify_doors()
print_text_map()
while True:
move_player_by_key()
array_to_text_map()
print_text_map()
if console:
for x in console:
print(x)
else:
print()
console = []
</code></pre>
|
[] |
[
{
"body": "<p>I'll assume you're fairly new to Python; tell me if you feel this stuff is too basic, and I'll start criticizing you for things that you don't deserve to be criticized for.</p>\n\n<h2>State</h2>\n\n<p>Ok, so the first thing that made me go \"eww\" in the code was <code>global</code>. In general, whenever you use <code>global</code>, you're probably doing something wrong. If I was to write your <code>createmap</code> function, it might look something more like this:</p>\n\n<pre><code>def createmap():\n \"\"\"\n The map is sketched in bmp, I make a array\n to use it like a tileset\n \"\"\"\n bmp = Image.open('sketch.bmp')\n bmp_data = bmp.getdata()\n bmp_array = np.array(bmp_data)\n map = bmp_array.reshape(bmp.size)\n return bmp, map\n</code></pre>\n\n<p>Instead of using a global <code>bmp</code> and <code>map</code> variable, I'm returning the non-global <code>bmp</code> and <code>map</code> variables. This means that I have a lot more flexibility in calling the function:</p>\n\n<pre><code># I can use it to create the old global variables:\nglobal bmp, map\nbmp, map = createmap()\n\n# Or some local ones\nlocal_bmp, local_map = createmap()\n\n# But most importantly, I can use it to create multiple sets of them\nbmp1, map1 = createmap()\nbmp2, map2 = createmap()\n</code></pre>\n\n<p>The last case is the most important; using your version of <code>createmap()</code>, when I call <code>createmap()</code> for the second time, it overwrites the previous <code>bmp</code> and <code>map</code> variables. This might not seem like a big problem; why would you ever need more than one map? but it makes it much harder to test things when they change global variables.</p>\n\n<p>We can do similar things to your other functions to avoid using global variables. The <code>array_to_text_map</code> function currently uses the <code>map</code> global variable, but we can replace that with a <code>map</code> argument. This way we will be able to convert any map to a text map, not just the one stored in the global <code>map</code> variable.</p>\n\n<p>One downside to this is that it does require more typing; I have to explicitly pass around all of my state. However, one of the core tenets of Python is that explicit is better than implicit, so get used to it ;) I should mention that people often wrap up their program's commonly used variables into classes, though that's probably more complex than you are looking for right now.</p>\n\n<h2>Switch Statements</h2>\n\n<p>Another thing that makes me feel uncomfortable about the code is when you have long chains of <code>elif</code> statements:</p>\n\n<pre><code>if y == 0:\n text_map.write('#')\nelif y == 3:\n text_map.write('.')\nelif y == 8:\n text_map.write('+')\nelif y == 9:\n text_map.write('e')\nelif y == 10:\n text_map.write('D')\nelif y == 12:\n text_map.write('$')\nelif y == 13:\n text_map.write('@')\nelif y == 15:\n text_map.write(' ')\n</code></pre>\n\n<p>This is ugly, and violates the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">DRY</a> principle. What you are doing here is looking up a value, based on the value of the variable <code>y</code>. The Pythonic (and sane) way of doing this is to define a dictionary (mapping) from the values of <code>y</code> to the string that should be written to <code>text_map</code>:</p>\n\n<pre><code>TEXT_MAP_CHARS = {\n 0: \"#\",\n 3: \".\",\n 8: \"+\",\n 9: \"e\",\n 10: \"D\",\n 12: \"$\",\n 15: \" \"\n}\n</code></pre>\n\n<p>We can then look up the correct character, and then write that to the file:</p>\n\n<pre><code>char = TEXT_MAP_CHARS[y]\ntext_map.write(char)\n</code></pre>\n\n<p>Which is much neater, and doesn't mix up program data (the mapping from numbers to characters) and program logic (the writing of the character to a file based on the value of y).</p>\n\n<hr>\n\n<p>With that said, I would praise you for your style. For every problem your code may have semantically, it is formatted very well (hooray for PEP8)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:20:01.467",
"Id": "42241",
"ParentId": "42203",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "42241",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T22:07:07.483",
"Id": "42203",
"Score": "6",
"Tags": [
"python",
"game",
"console"
],
"Title": "Simple console roguelike game"
}
|
42203
|
<p><a href="http://flask.pocoo.org/" rel="nofollow">Flask</a> is a micro-framework for Python 2.x and 3.3+. </p>
<p>To quote its creator:</p>
<blockquote>
<p>Flask is a micro-framework for Python based on <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a>, <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja 2</a> and good intentions</p>
</blockquote>
<p>It has exceptional <a href="http://flask.pocoo.org/docs/" rel="nofollow">documentation</a>, a large number of <a href="http://flask.pocoo.org/extensions/" rel="nofollow">extensions</a>, <a href="http://flask.pocoo.org/snippets/" rel="nofollow">snippets</a> and a friendly <a href="http://flask.pocoo.org/community/" rel="nofollow">community</a>.</p>
<p>Flask is <a href="https://github.com/mitsuhiko/flask" rel="nofollow">open-source and hosted on Github</a></p>
<h2>Tutorials</h2>
<ul>
<li><a href="http://flask.pocoo.org/docs/tutorial/" rel="nofollow">Official Tutorial</a></li>
<li><a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">Mega Tutorial</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:00:24.513",
"Id": "42208",
"Score": "0",
"Tags": null,
"Title": null
}
|
42208
|
Flask is a micro-framework for Python based on Werkzeug, Jinja 2 and good intentions.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:00:24.513",
"Id": "42209",
"Score": "0",
"Tags": null,
"Title": null
}
|
42209
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.